Skip to content

Models

The models module provides core data structures and types used throughout the application, following clean architecture principles.

DTOs (Data Transfer Objects)

Base DTOs

Base classes for all DTOs with common functionality.

from archipy.models.dtos.base_dtos import BaseDTO
from pydantic import BaseModel

class UserDTO(BaseDTO):
    id: str
    username: str
    email: str
    created_at: datetime

archipy.models.dtos.base_dtos.BaseDTO

Bases: BaseModel

Base Data Transfer Object class.

This class extends Pydantic's BaseModel to provide common configuration for all DTOs in the application.

Source code in archipy/models/dtos/base_dtos.py
class BaseDTO(BaseModel):
    """Base Data Transfer Object class.

    This class extends Pydantic's BaseModel to provide common configuration
    for all DTOs in the application.
    """

    model_config = ConfigDict(
        extra="ignore",
        validate_default=True,
        from_attributes=True,
        frozen=True,
        str_strip_whitespace=True,
        arbitrary_types_allowed=True,
    )

options: show_root_heading: true show_source: true

Email DTOs

DTOs for email-related operations.

from archipy.models.dtos.email_dtos import EmailAttachmentDTO

attachment = EmailAttachmentDTO(
    filename="document.pdf",
    content_type="application/pdf",
    content=b"..."
)

archipy.models.dtos.email_dtos.EmailAttachmentDTO

Bases: BaseDTO

Pydantic model for email attachments.

Source code in archipy/models/dtos/email_dtos.py
class EmailAttachmentDTO(BaseDTO):
    """Pydantic model for email attachments."""

    content: str | bytes | BinaryIO
    filename: str
    content_type: str | None = Field(default=None)
    content_disposition: EmailAttachmentDispositionType = Field(default=EmailAttachmentDispositionType.ATTACHMENT)
    content_id: str | None = Field(default=None)
    attachment_type: EmailAttachmentType
    max_size: int

    @field_validator("content_type")  # type: ignore[type-var]
    def set_content_type(self, v: str | None, values: dict) -> str | None:
        """Set content type based on filename extension if not provided.

        Args:
            v: The content type value
            values: Other field values

        Returns:
            The determined content type or the original value
        """
        if v is None and "filename" in values:
            content_type, _ = mimetypes.guess_type(values["filename"])
            return content_type or "application/octet-stream"
        return v

    @model_validator(mode="after")  # type: ignore[arg-type]
    def validate_attachment_size(self, model: Self) -> Self:
        """Validate that the attachment size does not exceed the maximum allowed size.

        Args:
            model: The model instance

        Returns:
            The validated model instance

        Raises:
            ValueError: If attachment size exceeds maximum allowed size
        """
        content = model.content
        if isinstance(content, str | bytes):
            content_size = len(content)
            if content_size > model.max_size:
                error_msg = f"Attachment size exceeds maximum allowed size of {model.max_size} bytes"
                raise ValueError(error_msg)
        return model

    @field_validator("content_id")  # type: ignore[type-var]
    def validate_content_id(self, v: str | None, _: dict) -> str | None:
        """Ensure content_id is properly formatted with angle brackets.

        Args:
            v: The content_id value
            _: Unused field values

        Returns:
            Properly formatted content_id
        """
        if v and not v.startswith("<"):
            return f"<{v}>"
        return v

archipy.models.dtos.email_dtos.EmailAttachmentDTO.set_content_type(v, values)

Set content type based on filename extension if not provided.

Parameters:

Name Type Description Default
v str | None

The content type value

required
values dict

Other field values

required

Returns:

Type Description
str | None

The determined content type or the original value

Source code in archipy/models/dtos/email_dtos.py
@field_validator("content_type")  # type: ignore[type-var]
def set_content_type(self, v: str | None, values: dict) -> str | None:
    """Set content type based on filename extension if not provided.

    Args:
        v: The content type value
        values: Other field values

    Returns:
        The determined content type or the original value
    """
    if v is None and "filename" in values:
        content_type, _ = mimetypes.guess_type(values["filename"])
        return content_type or "application/octet-stream"
    return v

archipy.models.dtos.email_dtos.EmailAttachmentDTO.validate_attachment_size(model)

Validate that the attachment size does not exceed the maximum allowed size.

Parameters:

Name Type Description Default
model Self

The model instance

required

Returns:

Type Description
Self

The validated model instance

Raises:

Type Description
ValueError

If attachment size exceeds maximum allowed size

Source code in archipy/models/dtos/email_dtos.py
@model_validator(mode="after")  # type: ignore[arg-type]
def validate_attachment_size(self, model: Self) -> Self:
    """Validate that the attachment size does not exceed the maximum allowed size.

    Args:
        model: The model instance

    Returns:
        The validated model instance

    Raises:
        ValueError: If attachment size exceeds maximum allowed size
    """
    content = model.content
    if isinstance(content, str | bytes):
        content_size = len(content)
        if content_size > model.max_size:
            error_msg = f"Attachment size exceeds maximum allowed size of {model.max_size} bytes"
            raise ValueError(error_msg)
    return model

archipy.models.dtos.email_dtos.EmailAttachmentDTO.validate_content_id(v, _)

Ensure content_id is properly formatted with angle brackets.

Parameters:

Name Type Description Default
v str | None

The content_id value

required
_ dict

Unused field values

required

Returns:

Type Description
str | None

Properly formatted content_id

Source code in archipy/models/dtos/email_dtos.py
@field_validator("content_id")  # type: ignore[type-var]
def validate_content_id(self, v: str | None, _: dict) -> str | None:
    """Ensure content_id is properly formatted with angle brackets.

    Args:
        v: The content_id value
        _: Unused field values

    Returns:
        Properly formatted content_id
    """
    if v and not v.startswith("<"):
        return f"<{v}>"
    return v

options: show_root_heading: true show_source: true

Error DTOs

Standardized error response format.

from archipy.models.dtos.error_dto import ErrorDetailDTO

error = ErrorDetailDTO(
    code="USER_NOT_FOUND",
    message_en="User not found",
)

archipy.models.dtos.error_dto.ErrorDetailDTO

Bases: BaseDTO

Standardized error detail model.

Source code in archipy/models/dtos/error_dto.py
class ErrorDetailDTO(BaseDTO):
    """Standardized error detail model."""

    code: str
    message_en: str
    message_fa: str
    http_status: int | None = None
    grpc_status: int | None = None

    @classmethod
    def create_error_detail(
        cls,
        code: str,
        message_en: str,
        message_fa: str,
        http_status: HTTPStatus | int | None = None,
        grpc_status: StatusCode | int | None = None,
    ) -> Self:
        """Creates an `ErrorDetailDTO` with appropriate status codes.

        Args:
            code (str): A unique error code.
            message_en (str): The error message in English.
            message_fa (str): The error message in Persian.
            http_status (HTTPStatus | int | None): The HTTP status code associated with the error.
            grpc_status (StatusCode | int  | None): The gRPC status code associated with the error.

        Returns:
            ErrorDetailDTO: The created exception detail object.
        """
        status_kwargs = {}

        if HTTP_AVAILABLE and http_status is not None:
            status_kwargs["http_status"] = http_status.value if isinstance(http_status, HTTPStatus) else http_status

        if GRPC_AVAILABLE and grpc_status is not None:
            # StatusCode.value can be a tuple, but we need only the first element (integer value)
            if isinstance(grpc_status, StatusCode):
                status_kwargs["grpc_status"] = (
                    grpc_status.value[0] if isinstance(grpc_status.value, tuple) else grpc_status.value
                )
            else:
                status_kwargs["grpc_status"] = grpc_status

        # We need to use cls() for proper typing with Self return type
        return cls(code=code, message_en=message_en, message_fa=message_fa, **status_kwargs)

archipy.models.dtos.error_dto.ErrorDetailDTO.create_error_detail(code, message_en, message_fa, http_status=None, grpc_status=None) classmethod

Creates an ErrorDetailDTO with appropriate status codes.

Parameters:

Name Type Description Default
code str

A unique error code.

required
message_en str

The error message in English.

required
message_fa str

The error message in Persian.

required
http_status HTTPStatus | int | None

The HTTP status code associated with the error.

None
grpc_status StatusCode | int | None

The gRPC status code associated with the error.

None

Returns:

Name Type Description
ErrorDetailDTO Self

The created exception detail object.

Source code in archipy/models/dtos/error_dto.py
@classmethod
def create_error_detail(
    cls,
    code: str,
    message_en: str,
    message_fa: str,
    http_status: HTTPStatus | int | None = None,
    grpc_status: StatusCode | int | None = None,
) -> Self:
    """Creates an `ErrorDetailDTO` with appropriate status codes.

    Args:
        code (str): A unique error code.
        message_en (str): The error message in English.
        message_fa (str): The error message in Persian.
        http_status (HTTPStatus | int | None): The HTTP status code associated with the error.
        grpc_status (StatusCode | int  | None): The gRPC status code associated with the error.

    Returns:
        ErrorDetailDTO: The created exception detail object.
    """
    status_kwargs = {}

    if HTTP_AVAILABLE and http_status is not None:
        status_kwargs["http_status"] = http_status.value if isinstance(http_status, HTTPStatus) else http_status

    if GRPC_AVAILABLE and grpc_status is not None:
        # StatusCode.value can be a tuple, but we need only the first element (integer value)
        if isinstance(grpc_status, StatusCode):
            status_kwargs["grpc_status"] = (
                grpc_status.value[0] if isinstance(grpc_status.value, tuple) else grpc_status.value
            )
        else:
            status_kwargs["grpc_status"] = grpc_status

    # We need to use cls() for proper typing with Self return type
    return cls(code=code, message_en=message_en, message_fa=message_fa, **status_kwargs)

options: show_root_heading: true show_source: true

Pagination DTO

Handles pagination parameters for queries.

from archipy.models.dtos.pagination_dto import PaginationDTO

pagination = PaginationDTO(
    page=1,
    page_size=10,
    total_items=100
)

archipy.models.dtos.pagination_dto.PaginationDTO

Bases: BaseDTO

Data Transfer Object for pagination parameters.

This DTO encapsulates pagination information for database queries and API responses, providing a standard way to specify which subset of results to retrieve.

Attributes:

Name Type Description
page int

The current page number (1-based indexing)

page_size int

Number of items per page

offset int

Calculated offset for database queries based on page and page_size

Examples:

>>> from archipy.models.dtos.pagination_dto import PaginationDTO
>>>
>>> # Default pagination (page 1, 10 items per page)
>>> pagination = PaginationDTO()
>>>
>>> # Custom pagination
>>> pagination = PaginationDTO(page=2, page_size=25)
>>> print(pagination.offset)  # Access offset as a property
25
>>>
>>> # Using with a database query
>>> def get_users(pagination: PaginationDTO):
...     query = select(User).offset(pagination.offset).limit(pagination.page_size)
...     return db.execute(query).scalars().all()
Source code in archipy/models/dtos/pagination_dto.py
class PaginationDTO(BaseDTO):
    """Data Transfer Object for pagination parameters.

    This DTO encapsulates pagination information for database queries and API responses,
    providing a standard way to specify which subset of results to retrieve.

    Attributes:
        page (int): The current page number (1-based indexing)
        page_size (int): Number of items per page
        offset (int): Calculated offset for database queries based on page and page_size

    Examples:
        >>> from archipy.models.dtos.pagination_dto import PaginationDTO
        >>>
        >>> # Default pagination (page 1, 10 items per page)
        >>> pagination = PaginationDTO()
        >>>
        >>> # Custom pagination
        >>> pagination = PaginationDTO(page=2, page_size=25)
        >>> print(pagination.offset)  # Access offset as a property
        25
        >>>
        >>> # Using with a database query
        >>> def get_users(pagination: PaginationDTO):
        ...     query = select(User).offset(pagination.offset).limit(pagination.page_size)
        ...     return db.execute(query).scalars().all()
    """

    page: int = Field(default=1, ge=1, description="Page number (1-indexed)")
    page_size: int = Field(default=10, ge=1, le=100, description="Number of items per page")

    MAX_ITEMS: ClassVar = 10000

    @model_validator(mode="after")
    def validate_pagination(self) -> Self:
        """Validate pagination limits to prevent excessive resource usage.

        Ensures that the requested number of items (page * page_size) doesn't exceed
        the maximum allowed limit.

        Returns:
            The validated model instance if valid.

        Raises:
            OutOfRangeError: If the total requested items exceeds MAX_ITEMS.
        """
        total_items = self.page * self.page_size
        if total_items > self.MAX_ITEMS:
            raise OutOfRangeError(field_name="pagination")
        return self

    @property
    def offset(self) -> int:
        """Calculate the offset for database queries.

        This property calculates how many records to skip based on the
        current page and page size.

        Returns:
            int: The number of records to skip

        Examples:
            >>> pagination = PaginationDTO(page=3, page_size=20)
            >>> pagination.offset
            40  # Skip the first 40 records (2 pages of 20 items)
        """
        return (self.page - 1) * self.page_size

archipy.models.dtos.pagination_dto.PaginationDTO.offset property

Calculate the offset for database queries.

This property calculates how many records to skip based on the current page and page size.

Returns:

Name Type Description
int int

The number of records to skip

Examples:

>>> pagination = PaginationDTO(page=3, page_size=20)
>>> pagination.offset
40  # Skip the first 40 records (2 pages of 20 items)

archipy.models.dtos.pagination_dto.PaginationDTO.validate_pagination()

Validate pagination limits to prevent excessive resource usage.

Ensures that the requested number of items (page * page_size) doesn't exceed the maximum allowed limit.

Returns:

Type Description
Self

The validated model instance if valid.

Raises:

Type Description
OutOfRangeError

If the total requested items exceeds MAX_ITEMS.

Source code in archipy/models/dtos/pagination_dto.py
@model_validator(mode="after")
def validate_pagination(self) -> Self:
    """Validate pagination limits to prevent excessive resource usage.

    Ensures that the requested number of items (page * page_size) doesn't exceed
    the maximum allowed limit.

    Returns:
        The validated model instance if valid.

    Raises:
        OutOfRangeError: If the total requested items exceeds MAX_ITEMS.
    """
    total_items = self.page * self.page_size
    if total_items > self.MAX_ITEMS:
        raise OutOfRangeError(field_name="pagination")
    return self

options: show_root_heading: true show_source: true

Range DTOs

Handles range-based queries and filters.

from archipy.models.dtos.range_dtos import (
    RangeDTO,
    IntegerRangeDTO,
    DateRangeDTO,
    DatetimeRangeDTO
)

# Integer range
int_range = IntegerRangeDTO(start=1, end=100)

# Date range
date_range = DateRangeDTO(
    start=date(2023, 1, 1),
    end=date(2023, 12, 31)
)

# Datetime range
dt_range = DatetimeRangeDTO(
    start=datetime(2023, 1, 1),
    end=datetime(2023, 12, 31)
)

archipy.models.dtos.range_dtos.BaseRangeDTO

Bases: BaseDTO, Generic[R]

Base Data Transfer Object for range queries.

Encapsulates a range of values with from_ and to fields. Provides validation to ensure range integrity.

Source code in archipy/models/dtos/range_dtos.py
class BaseRangeDTO(BaseDTO, Generic[R]):
    """Base Data Transfer Object for range queries.

    Encapsulates a range of values with from_ and to fields.
    Provides validation to ensure range integrity.
    """

    from_: R | None = None
    to: R | None = None

    @model_validator(mode="after")
    def validate_range(self) -> Self:
        """Validate that from_ is less than or equal to to when both are provided.

        Returns:
            Self: The validated model instance.

        Raises:
            OutOfRangeError: If from_ is greater than to.
        """
        if self.from_ is not None and self.to is not None and self.from_ > self.to:
            raise OutOfRangeError(field_name="from_")
        return self

archipy.models.dtos.range_dtos.BaseRangeDTO.validate_range()

Validate that from_ is less than or equal to to when both are provided.

Returns:

Name Type Description
Self Self

The validated model instance.

Raises:

Type Description
OutOfRangeError

If from_ is greater than to.

Source code in archipy/models/dtos/range_dtos.py
@model_validator(mode="after")
def validate_range(self) -> Self:
    """Validate that from_ is less than or equal to to when both are provided.

    Returns:
        Self: The validated model instance.

    Raises:
        OutOfRangeError: If from_ is greater than to.
    """
    if self.from_ is not None and self.to is not None and self.from_ > self.to:
        raise OutOfRangeError(field_name="from_")
    return self

archipy.models.dtos.range_dtos.DecimalRangeDTO

Bases: BaseRangeDTO[Decimal]

Data Transfer Object for decimal range queries.

Source code in archipy/models/dtos/range_dtos.py
class DecimalRangeDTO(BaseRangeDTO[Decimal]):
    """Data Transfer Object for decimal range queries."""

    from_: Decimal | None = None
    to: Decimal | None = None

    @field_validator("from_", "to", mode="before")
    @classmethod
    def convert_to_decimal(cls, value: Decimal | str | None) -> Decimal | None:
        """Convert input values to Decimal type.

        Args:
            value: The value to convert (None, string, or Decimal).

        Returns:
            Decimal | None: The converted Decimal value or None.

        Raises:
            InvalidArgumentError: If the value cannot be converted to Decimal.
        """
        if value is None:
            return None
        try:
            return Decimal(value)
        except (TypeError, ValueError) as e:
            raise InvalidArgumentError(argument_name="value") from e

archipy.models.dtos.range_dtos.DecimalRangeDTO.convert_to_decimal(value) classmethod

Convert input values to Decimal type.

Parameters:

Name Type Description Default
value Decimal | str | None

The value to convert (None, string, or Decimal).

required

Returns:

Type Description
Decimal | None

Decimal | None: The converted Decimal value or None.

Raises:

Type Description
InvalidArgumentError

If the value cannot be converted to Decimal.

Source code in archipy/models/dtos/range_dtos.py
@field_validator("from_", "to", mode="before")
@classmethod
def convert_to_decimal(cls, value: Decimal | str | None) -> Decimal | None:
    """Convert input values to Decimal type.

    Args:
        value: The value to convert (None, string, or Decimal).

    Returns:
        Decimal | None: The converted Decimal value or None.

    Raises:
        InvalidArgumentError: If the value cannot be converted to Decimal.
    """
    if value is None:
        return None
    try:
        return Decimal(value)
    except (TypeError, ValueError) as e:
        raise InvalidArgumentError(argument_name="value") from e

archipy.models.dtos.range_dtos.IntegerRangeDTO

Bases: BaseRangeDTO[int]

Data Transfer Object for integer range queries.

Source code in archipy/models/dtos/range_dtos.py
class IntegerRangeDTO(BaseRangeDTO[int]):
    """Data Transfer Object for integer range queries."""

    from_: int | None = None
    to: int | None = None

archipy.models.dtos.range_dtos.DateRangeDTO

Bases: BaseRangeDTO[date]

Data Transfer Object for date range queries.

Source code in archipy/models/dtos/range_dtos.py
class DateRangeDTO(BaseRangeDTO[date]):
    """Data Transfer Object for date range queries."""

    from_: date | None = None
    to: date | None = None

archipy.models.dtos.range_dtos.DatetimeRangeDTO

Bases: BaseRangeDTO[datetime]

Data Transfer Object for datetime range queries.

Source code in archipy/models/dtos/range_dtos.py
class DatetimeRangeDTO(BaseRangeDTO[datetime]):
    """Data Transfer Object for datetime range queries."""

    from_: datetime | None = None
    to: datetime | None = None

archipy.models.dtos.range_dtos.DatetimeIntervalRangeDTO

Bases: BaseRangeDTO[datetime]

Data Transfer Object for datetime range queries with interval.

Rejects requests if the number of intervals exceeds MAX_ITEMS or if interval-specific range size or 'to' age constraints are violated.

Source code in archipy/models/dtos/range_dtos.py
class DatetimeIntervalRangeDTO(BaseRangeDTO[datetime]):
    """Data Transfer Object for datetime range queries with interval.

    Rejects requests if the number of intervals exceeds MAX_ITEMS or if interval-specific
    range size or 'to' age constraints are violated.
    """

    from_: datetime
    to: datetime
    interval: TimeIntervalUnitType

    # Maximum number of intervals allowed
    MAX_ITEMS: ClassVar[int] = 100

    # Range size limits for each interval
    RANGE_SIZE_LIMITS: ClassVar[dict[TimeIntervalUnitType, timedelta]] = {
        TimeIntervalUnitType.SECONDS: timedelta(days=2),
        TimeIntervalUnitType.MINUTES: timedelta(days=7),
        TimeIntervalUnitType.HOURS: timedelta(days=30),
        TimeIntervalUnitType.DAYS: timedelta(days=365),
        TimeIntervalUnitType.WEEKS: timedelta(days=365 * 2),
        TimeIntervalUnitType.MONTHS: timedelta(days=365 * 5),  # No limit for MONTHS, set high
        TimeIntervalUnitType.YEAR: timedelta(days=365 * 10),  # No limit for YEAR, set high
    }

    # 'to' age limits for each interval
    TO_AGE_LIMITS: ClassVar[dict[TimeIntervalUnitType, timedelta]] = {
        TimeIntervalUnitType.SECONDS: timedelta(days=2),
        TimeIntervalUnitType.MINUTES: timedelta(days=7),
        TimeIntervalUnitType.HOURS: timedelta(days=30),
        TimeIntervalUnitType.DAYS: timedelta(days=365 * 5),
        TimeIntervalUnitType.WEEKS: timedelta(days=365 * 10),
        TimeIntervalUnitType.MONTHS: timedelta(days=365 * 20),  # No limit for MONTHS, set high
        TimeIntervalUnitType.YEAR: timedelta(days=365 * 50),  # No limit for YEAR, set high
    }

    # Mapping of intervals to timedelta for step size
    INTERVAL_TO_TIMEDELTA: ClassVar[dict[TimeIntervalUnitType, timedelta]] = {
        TimeIntervalUnitType.SECONDS: timedelta(seconds=1),
        TimeIntervalUnitType.MINUTES: timedelta(minutes=1),
        TimeIntervalUnitType.HOURS: timedelta(hours=1),
        TimeIntervalUnitType.DAYS: timedelta(days=1),
        TimeIntervalUnitType.WEEKS: timedelta(weeks=1),
        TimeIntervalUnitType.MONTHS: timedelta(days=30),  # Approximate
        TimeIntervalUnitType.YEAR: timedelta(days=365),  # Approximate
    }

    @model_validator(mode="after")
    def validate_interval_constraints(self) -> Self:
        """Validate interval based on range size, 'to' field age, and max intervals.

        - Each interval has specific range size and 'to' age limits.
        - Rejects if the number of intervals exceeds MAX_ITEMS.

        Returns:
            Self: The validated model instance.

        Raises:
            OutOfRangeError: If interval constraints are violated or number of intervals > MAX_ITEMS.
        """
        if self.from_ is not None and self.to is not None:
            # Validate range size limit for the selected interval
            range_size = self.to - self.from_
            max_range_size = self.RANGE_SIZE_LIMITS.get(self.interval)
            if max_range_size and range_size > max_range_size:
                raise OutOfRangeError(field_name="range_size")

            # Validate 'to' age limit
            current_time = datetime.now()
            max_to_age = self.TO_AGE_LIMITS.get(self.interval)
            if max_to_age:
                age_threshold = current_time - max_to_age
                if self.to < age_threshold:
                    raise OutOfRangeError(field_name="to")

            # Calculate number of intervals
            step = self.INTERVAL_TO_TIMEDELTA[self.interval]
            range_duration = self.to - self.from_
            num_intervals = int(range_duration.total_seconds() / step.total_seconds()) + 1

            # Reject if number of intervals exceeds MAX_ITEMS
            if num_intervals > self.MAX_ITEMS:
                raise OutOfRangeError(field_name="interval_count")

        return self

archipy.models.dtos.range_dtos.DatetimeIntervalRangeDTO.validate_interval_constraints()

Validate interval based on range size, 'to' field age, and max intervals.

  • Each interval has specific range size and 'to' age limits.
  • Rejects if the number of intervals exceeds MAX_ITEMS.

Returns:

Name Type Description
Self Self

The validated model instance.

Raises:

Type Description
OutOfRangeError

If interval constraints are violated or number of intervals > MAX_ITEMS.

Source code in archipy/models/dtos/range_dtos.py
@model_validator(mode="after")
def validate_interval_constraints(self) -> Self:
    """Validate interval based on range size, 'to' field age, and max intervals.

    - Each interval has specific range size and 'to' age limits.
    - Rejects if the number of intervals exceeds MAX_ITEMS.

    Returns:
        Self: The validated model instance.

    Raises:
        OutOfRangeError: If interval constraints are violated or number of intervals > MAX_ITEMS.
    """
    if self.from_ is not None and self.to is not None:
        # Validate range size limit for the selected interval
        range_size = self.to - self.from_
        max_range_size = self.RANGE_SIZE_LIMITS.get(self.interval)
        if max_range_size and range_size > max_range_size:
            raise OutOfRangeError(field_name="range_size")

        # Validate 'to' age limit
        current_time = datetime.now()
        max_to_age = self.TO_AGE_LIMITS.get(self.interval)
        if max_to_age:
            age_threshold = current_time - max_to_age
            if self.to < age_threshold:
                raise OutOfRangeError(field_name="to")

        # Calculate number of intervals
        step = self.INTERVAL_TO_TIMEDELTA[self.interval]
        range_duration = self.to - self.from_
        num_intervals = int(range_duration.total_seconds() / step.total_seconds()) + 1

        # Reject if number of intervals exceeds MAX_ITEMS
        if num_intervals > self.MAX_ITEMS:
            raise OutOfRangeError(field_name="interval_count")

    return self

options: show_root_heading: true show_source: true

Search Input DTO

Standardized search parameters.

from archipy.models.dtos.search_input_dto import SearchInputDTO

search = SearchInputDTO[str](
    query="john",
    filters={"active": True},
    pagination=pagination
)

archipy.models.dtos.search_input_dto.SearchInputDTO

Bases: BaseModel, Generic[T]

Data Transfer Object for search inputs with pagination and sorting.

This DTO encapsulates search parameters for database queries and API responses, providing a standard way to handle pagination and sorting.

Type Parameters

T: The type for sort column (usually an Enum with column names).

Source code in archipy/models/dtos/search_input_dto.py
class SearchInputDTO(BaseModel, Generic[T]):
    """Data Transfer Object for search inputs with pagination and sorting.

    This DTO encapsulates search parameters for database queries and API responses,
    providing a standard way to handle pagination and sorting.

    Type Parameters:
        T: The type for sort column (usually an Enum with column names).
    """

    pagination: PaginationDTO | None = None
    sort_info: SortDTO[T] | None = None

options: show_root_heading: true show_source: true

Sort DTO

Handles sorting parameters for queries.

from archipy.models.dtos.sort_dto import SortDTO

sort = SortDTO[str](
    field="created_at",
    order="desc"
)

archipy.models.dtos.sort_dto.SortDTO

Bases: BaseModel, Generic[T]

Data Transfer Object for sorting parameters.

This DTO encapsulates sorting information for database queries and API responses, providing a standard way to specify how results should be ordered.

Attributes:

Name Type Description
column T | str

The name or enum value of the column to sort by

order str

The sort direction - "ASC" for ascending, "DESC" for descending

Examples:

>>> from archipy.models.dtos.sort_dto import SortDTO
>>> from archipy.models.types.sort_order_type import SortOrderType
>>>
>>> # Sort by name in ascending order
>>> sort = SortDTO(column="name", order=SortOrderType.ASCENDING)
>>>
>>> # Sort by creation date in descending order (newest first)
>>> sort = SortDTO(column="created_at", order="DESCENDING")
>>>
>>> # Using with a database query
>>> def get_sorted_users(sort: SortDTO = SortDTO.default()):
...     query = select(User)
...     if sort.order == SortOrderType.ASCENDING:
...         query = query.order_by(getattr(User, sort.column).asc())
...     else:
...         query = query.order_by(getattr(User, sort.column).desc())
...     return db.execute(query).scalars().all()
>>>
>>> # Using with enum column types
>>> from enum import Enum
>>> class UserColumns(Enum):
...     ID = "id"
...     NAME = "name"
...     EMAIL = "email"
...     CREATED_AT = "created_at"
>>>
>>> # Create a sort configuration with enum
>>> sort = SortDTO[UserColumns](column=UserColumns.NAME, order=SortOrderType.ASCENDING)
Source code in archipy/models/dtos/sort_dto.py
class SortDTO(BaseModel, Generic[T]):
    """Data Transfer Object for sorting parameters.

    This DTO encapsulates sorting information for database queries and API responses,
    providing a standard way to specify how results should be ordered.

    Attributes:
        column (T | str): The name or enum value of the column to sort by
        order (str): The sort direction - "ASC" for ascending, "DESC" for descending

    Examples:
        >>> from archipy.models.dtos.sort_dto import SortDTO
        >>> from archipy.models.types.sort_order_type import SortOrderType
        >>>
        >>> # Sort by name in ascending order
        >>> sort = SortDTO(column="name", order=SortOrderType.ASCENDING)
        >>>
        >>> # Sort by creation date in descending order (newest first)
        >>> sort = SortDTO(column="created_at", order="DESCENDING")
        >>>
        >>> # Using with a database query
        >>> def get_sorted_users(sort: SortDTO = SortDTO.default()):
        ...     query = select(User)
        ...     if sort.order == SortOrderType.ASCENDING:
        ...         query = query.order_by(getattr(User, sort.column).asc())
        ...     else:
        ...         query = query.order_by(getattr(User, sort.column).desc())
        ...     return db.execute(query).scalars().all()
        >>>
        >>> # Using with enum column types
        >>> from enum import Enum
        >>> class UserColumns(Enum):
        ...     ID = "id"
        ...     NAME = "name"
        ...     EMAIL = "email"
        ...     CREATED_AT = "created_at"
        >>>
        >>> # Create a sort configuration with enum
        >>> sort = SortDTO[UserColumns](column=UserColumns.NAME, order=SortOrderType.ASCENDING)
    """

    column: T | str = Field(default="created_at", description="Column name or enum to sort by")
    order: SortOrderType = Field(default=SortOrderType.DESCENDING, description="Sort order (ASCENDING or DESCENDING)")

    @classmethod
    def default(cls) -> "SortDTO":
        """Create a default sort configuration.

        Returns a sort configuration that orders by created_at in descending order
        (newest first), which is a common default sorting behavior.

        Returns:
            SortDTO: A default sort configuration

        Examples:
            >>> default_sort = SortDTO.default()
            >>> print(f"Sort by {default_sort.column} {default_sort.order}")
            Sort by created_at DESCENDING
        """
        return cls(column="created_at", order=SortOrderType.DESCENDING)

archipy.models.dtos.sort_dto.SortDTO.default() classmethod

Create a default sort configuration.

Returns a sort configuration that orders by created_at in descending order (newest first), which is a common default sorting behavior.

Returns:

Name Type Description
SortDTO SortDTO

A default sort configuration

Examples:

>>> default_sort = SortDTO.default()
>>> print(f"Sort by {default_sort.column} {default_sort.order}")
Sort by created_at DESCENDING
Source code in archipy/models/dtos/sort_dto.py
@classmethod
def default(cls) -> "SortDTO":
    """Create a default sort configuration.

    Returns a sort configuration that orders by created_at in descending order
    (newest first), which is a common default sorting behavior.

    Returns:
        SortDTO: A default sort configuration

    Examples:
        >>> default_sort = SortDTO.default()
        >>> print(f"Sort by {default_sort.column} {default_sort.order}")
        Sort by created_at DESCENDING
    """
    return cls(column="created_at", order=SortOrderType.DESCENDING)

options: show_root_heading: true show_source: true

Entities

SQLAlchemy Base Entities

Base classes for SQLAlchemy entities with various mixins for different capabilities.

from archipy.models.entities.sqlalchemy.base_entities import (
    BaseEntity,
    UpdatableEntity,
    DeletableEntity,
    AdminEntity,
    ManagerEntity,
    UpdatableDeletableEntity,
    ArchivableEntity,
    UpdatableAdminEntity,
    UpdatableManagerEntity,
    ArchivableDeletableEntity,
    UpdatableDeletableAdminEntity,
    UpdatableDeletableManagerEntity,
    ArchivableAdminEntity,
    ArchivableManagerEntity,
    UpdatableManagerAdminEntity,
    ArchivableManagerAdminEntity,
    ArchivableDeletableAdminEntity,
    ArchivableDeletableManagerEntity,
    UpdatableDeletableManagerAdminEntity,
    ArchivableDeletableManagerAdminEntity
)
from sqlalchemy import Column, String

# Basic entity
class User(BaseEntity):
    __tablename__ = "users"
    username = Column(String(100), unique=True)
    email = Column(String(255), unique=True)

# Entity with update tracking
class Post(UpdatableEntity):
    __tablename__ = "posts"
    title = Column(String(200))
    content = Column(String)

# Entity with soft deletion
class Comment(DeletableEntity):
    __tablename__ = "comments"
    text = Column(String)

# Entity with admin tracking
class AdminLog(AdminEntity):
    __tablename__ = "admin_logs"
    action = Column(String)

# Entity with manager tracking
class ManagerLog(ManagerEntity):
    __tablename__ = "manager_logs"
    action = Column(String)

archipy.models.entities.sqlalchemy.base_entities.BaseEntity

Bases: DeclarativeBase

Base class for all SQLAlchemy models with automatic timestamps.

This class serves as the base for all entities in the application. It provides common functionality such as automatic timestamping for created_at and validation for the primary key column.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class BaseEntity(DeclarativeBase):
    """Base class for all SQLAlchemy models with automatic timestamps.

    This class serves as the base for all entities in the application. It provides
    common functionality such as automatic timestamping for `created_at` and
    validation for the primary key column.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
    """

    __abstract__ = True
    created_at: Mapped[datetime] = Column(DateTime(), server_default=text("CURRENT_TIMESTAMP"), nullable=False)

    @classmethod
    def _is_abstract(cls) -> bool:
        """Check if the class is abstract.

        Returns:
            bool: True if the class is abstract, False otherwise.
        """
        return (not hasattr(cls, "__tablename__")) and cls.__abstract__

    def __init_subclass__(cls, **kw: object) -> None:
        """Validate the subclass during initialization.

        Args:
            **kw: Additional keyword arguments passed to the subclass.

        Raises:
            AttributeError: If the subclass does not have the required primary key column.
        """
        if cls._is_abstract():
            return
        cls._validate_pk_column()
        super().__init_subclass__(**kw)

    @classmethod
    def _validate_pk_column(cls) -> None:
        """Validate that the subclass has the required primary key column.

        Raises:
            AttributeError: If the primary key column is missing or invalid.
        """
        if not hasattr(cls, PK_COLUMN_NAME):
            error_message = f"Child class {cls.__name__} must have {PK_COLUMN_NAME}"
            raise AttributeError(error_message)
        pk_column = getattr(cls, PK_COLUMN_NAME)
        if not isinstance(pk_column, Synonym):
            error_message = f"{PK_COLUMN_NAME} must be a sqlalchemy.orm.Synonym type"
            raise TypeError(error_message)

archipy.models.entities.sqlalchemy.base_entities.BaseEntity.__init_subclass__(**kw)

Validate the subclass during initialization.

Parameters:

Name Type Description Default
**kw object

Additional keyword arguments passed to the subclass.

{}

Raises:

Type Description
AttributeError

If the subclass does not have the required primary key column.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
def __init_subclass__(cls, **kw: object) -> None:
    """Validate the subclass during initialization.

    Args:
        **kw: Additional keyword arguments passed to the subclass.

    Raises:
        AttributeError: If the subclass does not have the required primary key column.
    """
    if cls._is_abstract():
        return
    cls._validate_pk_column()
    super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.EntityAttributeChecker

Utility class for validating model attributes.

This class provides functionality to ensure that at least one of the specified attributes is present in a model.

Attributes:

Name Type Description
required_any list[list[str]]

A list of lists, where each inner list contains attribute names. At least one attribute from each inner list must be present.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class EntityAttributeChecker:
    """Utility class for validating model attributes.

    This class provides functionality to ensure that at least one of the specified
    attributes is present in a model.

    Attributes:
        required_any: A list of lists, where each inner list contains
            attribute names. At least one attribute from each inner list must be present.
    """

    required_any: ClassVar[list[list[str]]] = []

    @classmethod
    def validate(cls, base_class: type) -> None:
        """Validate that at least one of the required attributes is present.

        Args:
            base_class: The class to validate.

        Raises:
            AttributeError: If none of the required attributes are present.
        """
        for attrs in cls.required_any:
            if not any(hasattr(base_class, attr) for attr in attrs):
                error_message = f"One of {attrs} must be defined in {base_class.__name__}"
                raise AttributeError(error_message)

archipy.models.entities.sqlalchemy.base_entities.EntityAttributeChecker.validate(base_class) classmethod

Validate that at least one of the required attributes is present.

Parameters:

Name Type Description Default
base_class type

The class to validate.

required

Raises:

Type Description
AttributeError

If none of the required attributes are present.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
@classmethod
def validate(cls, base_class: type) -> None:
    """Validate that at least one of the required attributes is present.

    Args:
        base_class: The class to validate.

    Raises:
        AttributeError: If none of the required attributes are present.
    """
    for attrs in cls.required_any:
        if not any(hasattr(base_class, attr) for attr in attrs):
            error_message = f"One of {attrs} must be defined in {base_class.__name__}"
            raise AttributeError(error_message)

archipy.models.entities.sqlalchemy.base_entities.DeletableMixin

Mixin to add a deletable flag to models.

This mixin adds an is_deleted column to indicate whether the entity has been soft-deleted, allowing for logical deletion without physically removing records.

Attributes:

Name Type Description
is_deleted

Flag indicating if the entity is deleted.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class DeletableMixin:
    """Mixin to add a deletable flag to models.

    This mixin adds an `is_deleted` column to indicate whether the entity has been
    soft-deleted, allowing for logical deletion without physically removing records.

    Attributes:
        is_deleted: Flag indicating if the entity is deleted.
    """

    __abstract__ = True
    is_deleted = Column(Boolean, default=False, nullable=False)

archipy.models.entities.sqlalchemy.base_entities.UpdatableMixin

Mixin to add updatable timestamp functionality.

This mixin adds an updated_at column to track the last update time of the entity, automatically maintaining a timestamp of the most recent modification.

Attributes:

Name Type Description
updated_at

Timestamp indicating when the entity was last updated.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableMixin:
    """Mixin to add updatable timestamp functionality.

    This mixin adds an `updated_at` column to track the last update time of the entity,
    automatically maintaining a timestamp of the most recent modification.

    Attributes:
        updated_at: Timestamp indicating when the entity was last updated.
    """

    __abstract__ = True

    @staticmethod
    def _make_naive(dt: datetime) -> datetime:
        """Convert a timezone-aware datetime to naive by removing timezone info."""
        return dt.replace(tzinfo=None) if dt.tzinfo else dt

    updated_at = Column(
        DateTime(),
        server_default=text("CURRENT_TIMESTAMP"),
        nullable=False,
        onupdate=lambda: UpdatableMixin._make_naive(BaseUtils.get_datetime_now()),
    )

archipy.models.entities.sqlalchemy.base_entities.ArchivableMixin

Mixin to add Archivable functionality.

This mixin adds an is_archived column to indicate whether the entity has been archived, and an origin_uuid column to reference the original entity.

Attributes:

Name Type Description
is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableMixin:
    """Mixin to add Archivable functionality.

    This mixin adds an `is_archived` column to indicate whether the entity has been
    archived, and an `origin_uuid` column to reference the original entity.

    Attributes:
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
    """

    __abstract__ = True
    is_archived = Column(Boolean, default=False, nullable=False)
    # Using Column without Mapped is acceptable since Column works with BaseEntity.__table__
    origin_uuid = Column(ForeignKey("self.pk_uuid"), nullable=True)  # type: ignore[var-annotated]

archipy.models.entities.sqlalchemy.base_entities.AdminMixin

Bases: EntityAttributeChecker

Mixin for models with admin-related attributes.

This mixin ensures that at least one of the admin-related attributes is present, providing tracking of which administrator created the entity.

Attributes:

Name Type Description
required_any list[list[str]]

Specifies the required admin-related attributes.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class AdminMixin(EntityAttributeChecker):
    """Mixin for models with admin-related attributes.

    This mixin ensures that at least one of the admin-related attributes is present,
    providing tracking of which administrator created the entity.

    Attributes:
        required_any: Specifies the required admin-related attributes.
    """

    __abstract__ = True
    required_any: ClassVar[list[list[str]]] = [["created_by_admin", "created_by_admin_uuid"]]

    def __init_subclass__(cls, **kw: object) -> None:
        """Validate the subclass during initialization.

        Args:
            **kw: Additional keyword arguments passed to the subclass.
        """
        cls.validate(cls)
        super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.AdminMixin.__init_subclass__(**kw)

Validate the subclass during initialization.

Parameters:

Name Type Description Default
**kw object

Additional keyword arguments passed to the subclass.

{}
Source code in archipy/models/entities/sqlalchemy/base_entities.py
def __init_subclass__(cls, **kw: object) -> None:
    """Validate the subclass during initialization.

    Args:
        **kw: Additional keyword arguments passed to the subclass.
    """
    cls.validate(cls)
    super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.ManagerMixin

Bases: EntityAttributeChecker

Mixin for models with manager-related attributes.

This mixin ensures that at least one of the manager-related attributes is present, providing tracking of which manager created the entity.

Attributes:

Name Type Description
required_any list[list[str]]

Specifies the required manager-related attributes.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ManagerMixin(EntityAttributeChecker):
    """Mixin for models with manager-related attributes.

    This mixin ensures that at least one of the manager-related attributes is present,
    providing tracking of which manager created the entity.

    Attributes:
        required_any: Specifies the required manager-related attributes.
    """

    __abstract__ = True
    required_any: ClassVar[list[list[str]]] = [["created_by", "created_by_uuid"]]

    def __init_subclass__(cls, **kw: object) -> None:
        """Validate the subclass during initialization.

        Args:
            **kw: Additional keyword arguments passed to the subclass.
        """
        cls.validate(cls)
        super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.ManagerMixin.__init_subclass__(**kw)

Validate the subclass during initialization.

Parameters:

Name Type Description Default
**kw object

Additional keyword arguments passed to the subclass.

{}
Source code in archipy/models/entities/sqlalchemy/base_entities.py
def __init_subclass__(cls, **kw: object) -> None:
    """Validate the subclass during initialization.

    Args:
        **kw: Additional keyword arguments passed to the subclass.
    """
    cls.validate(cls)
    super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.UpdatableAdminMixin

Bases: EntityAttributeChecker

Mixin for models updatable by admin.

This mixin ensures that at least one of the admin-related update attributes is present, providing tracking of which administrator last updated the entity.

Attributes:

Name Type Description
required_any list[list[str]]

Specifies the required admin-related update attributes.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableAdminMixin(EntityAttributeChecker):
    """Mixin for models updatable by admin.

    This mixin ensures that at least one of the admin-related update attributes is present,
    providing tracking of which administrator last updated the entity.

    Attributes:
        required_any: Specifies the required admin-related update attributes.
    """

    __abstract__ = True
    required_any: ClassVar[list[list[str]]] = [["updated_by_admin", "updated_by_admin_uuid"]]

    def __init_subclass__(cls, **kw: object) -> None:
        """Validate the subclass during initialization.

        Args:
            **kw: Additional keyword arguments passed to the subclass.
        """
        cls.validate(cls)
        super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.UpdatableAdminMixin.__init_subclass__(**kw)

Validate the subclass during initialization.

Parameters:

Name Type Description Default
**kw object

Additional keyword arguments passed to the subclass.

{}
Source code in archipy/models/entities/sqlalchemy/base_entities.py
def __init_subclass__(cls, **kw: object) -> None:
    """Validate the subclass during initialization.

    Args:
        **kw: Additional keyword arguments passed to the subclass.
    """
    cls.validate(cls)
    super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.UpdatableManagerMixin

Bases: EntityAttributeChecker

Mixin for models updatable by managers.

This mixin ensures that at least one of the manager-related update attributes is present, providing tracking of which manager last updated the entity.

Attributes:

Name Type Description
required_any list[list[str]]

Specifies the required manager-related update attributes.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableManagerMixin(EntityAttributeChecker):
    """Mixin for models updatable by managers.

    This mixin ensures that at least one of the manager-related update attributes is present,
    providing tracking of which manager last updated the entity.

    Attributes:
        required_any: Specifies the required manager-related update attributes.
    """

    __abstract__ = True
    required_any: ClassVar[list[list[str]]] = [["updated_by", "updated_by_uuid"]]

    def __init_subclass__(cls, **kw: object) -> None:
        """Validate the subclass during initialization.

        Args:
            **kw: Additional keyword arguments passed to the subclass.
        """
        cls.validate(cls)
        super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.UpdatableManagerMixin.__init_subclass__(**kw)

Validate the subclass during initialization.

Parameters:

Name Type Description Default
**kw object

Additional keyword arguments passed to the subclass.

{}
Source code in archipy/models/entities/sqlalchemy/base_entities.py
def __init_subclass__(cls, **kw: object) -> None:
    """Validate the subclass during initialization.

    Args:
        **kw: Additional keyword arguments passed to the subclass.
    """
    cls.validate(cls)
    super().__init_subclass__(**kw)

archipy.models.entities.sqlalchemy.base_entities.UpdatableEntity

Bases: BaseEntity, UpdatableMixin

Base class for entities that support updating timestamps.

This class extends BaseEntity with update tracking functionality, allowing applications to track when records were last modified.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableEntity(BaseEntity, UpdatableMixin):
    """Base class for entities that support updating timestamps.

    This class extends BaseEntity with update tracking functionality, allowing
    applications to track when records were last modified.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.DeletableEntity

Bases: BaseEntity, DeletableMixin

Base class for entities that support soft deletion.

This class extends BaseEntity with soft deletion capability, allowing applications to mark records as deleted without physically removing them.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

is_deleted

Flag indicating if the entity is deleted.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class DeletableEntity(BaseEntity, DeletableMixin):
    """Base class for entities that support soft deletion.

    This class extends BaseEntity with soft deletion capability, allowing
    applications to mark records as deleted without physically removing them.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        is_deleted: Flag indicating if the entity is deleted.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.AdminEntity

Bases: BaseEntity, AdminMixin

Base class for entities with admin-related attributes.

This class extends BaseEntity with tracking of which administrator created the entity, supporting audit and accountability requirements.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

created_by_admin/created_by_admin_uuid Mapped[datetime]

Reference to the admin who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class AdminEntity(BaseEntity, AdminMixin):
    """Base class for entities with admin-related attributes.

    This class extends BaseEntity with tracking of which administrator created
    the entity, supporting audit and accountability requirements.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ManagerEntity

Bases: BaseEntity, ManagerMixin

Base class for entities with manager-related attributes.

This class extends BaseEntity with tracking of which manager created the entity, supporting audit and accountability requirements.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

created_by/created_by_uuid Mapped[datetime]

Reference to the manager who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ManagerEntity(BaseEntity, ManagerMixin):
    """Base class for entities with manager-related attributes.

    This class extends BaseEntity with tracking of which manager created
    the entity, supporting audit and accountability requirements.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        created_by/created_by_uuid: Reference to the manager who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableDeletableEntity

Bases: BaseEntity, UpdatableMixin, DeletableMixin

Base class for entities that support updating timestamps and soft deletion.

This class combines update tracking and soft deletion capabilities, providing a complete history of when records were created, updated, and deleted.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableDeletableEntity(BaseEntity, UpdatableMixin, DeletableMixin):
    """Base class for entities that support updating timestamps and soft deletion.

    This class combines update tracking and soft deletion capabilities, providing
    a complete history of when records were created, updated, and deleted.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableEntity

Bases: UpdatableEntity, ArchivableMixin

Base class for entities that support archiving.

This class extends UpdatableEntity with archiving capability, allowing applications to mark records as archived and track the original entity.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableEntity(UpdatableEntity, ArchivableMixin):
    """Base class for entities that support archiving.

    This class extends UpdatableEntity with archiving capability, allowing
    applications to mark records as archived and track the original entity.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableAdminEntity

Bases: BaseEntity, UpdatableMixin, AdminMixin, UpdatableAdminMixin

Base class for entities updatable by admin with timestamps.

This class combines creation and update tracking for administrator actions, providing a comprehensive audit trail of administrative modifications.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

updated_by_admin/updated_by_admin_uuid

Reference to the admin who last updated the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableAdminEntity(BaseEntity, UpdatableMixin, AdminMixin, UpdatableAdminMixin):
    """Base class for entities updatable by admin with timestamps.

    This class combines creation and update tracking for administrator actions,
    providing a comprehensive audit trail of administrative modifications.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
        updated_by_admin/updated_by_admin_uuid: Reference to the admin who last updated the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableManagerEntity

Bases: BaseEntity, UpdatableMixin, ManagerMixin, UpdatableManagerMixin

Base class for entities updatable by managers with timestamps.

This class combines creation and update tracking for manager actions, providing a comprehensive audit trail of management modifications.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

created_by/created_by_uuid

Reference to the manager who created the entity.

updated_by/updated_by_uuid

Reference to the manager who last updated the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableManagerEntity(BaseEntity, UpdatableMixin, ManagerMixin, UpdatableManagerMixin):
    """Base class for entities updatable by managers with timestamps.

    This class combines creation and update tracking for manager actions,
    providing a comprehensive audit trail of management modifications.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        created_by/created_by_uuid: Reference to the manager who created the entity.
        updated_by/updated_by_uuid: Reference to the manager who last updated the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableDeletableEntity

Bases: UpdatableDeletableEntity, ArchivableMixin

Base class for entities that support both archiving and soft deletion.

This class combines archiving and soft deletion capabilities, providing a complete history of when records were created, updated, archived, and deleted.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableDeletableEntity(UpdatableDeletableEntity, ArchivableMixin):
    """Base class for entities that support both archiving and soft deletion.

    This class combines archiving and soft deletion capabilities, providing
    a complete history of when records were created, updated, archived, and deleted.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableDeletableAdminEntity

Bases: BaseEntity, UpdatableMixin, AdminMixin, UpdatableAdminMixin, DeletableMixin

Base class for entities updatable by admin with timestamps and soft deletion.

This class combines administrator creation and update tracking with soft deletion, providing a complete audit trail throughout the entity's lifecycle.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

updated_by_admin/updated_by_admin_uuid

Reference to the admin who last updated the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableDeletableAdminEntity(BaseEntity, UpdatableMixin, AdminMixin, UpdatableAdminMixin, DeletableMixin):
    """Base class for entities updatable by admin with timestamps and soft deletion.

    This class combines administrator creation and update tracking with soft deletion,
    providing a complete audit trail throughout the entity's lifecycle.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
        updated_by_admin/updated_by_admin_uuid: Reference to the admin who last updated the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableDeletableManagerEntity

Bases: BaseEntity, UpdatableMixin, ManagerMixin, UpdatableManagerMixin, DeletableMixin

Base class for entities updatable by managers with timestamps and soft deletion.

This class combines manager creation and update tracking with soft deletion, providing a complete audit trail throughout the entity's lifecycle.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

created_by/created_by_uuid

Reference to the manager who created the entity.

updated_by/updated_by_uuid

Reference to the manager who last updated the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableDeletableManagerEntity(BaseEntity, UpdatableMixin, ManagerMixin, UpdatableManagerMixin, DeletableMixin):
    """Base class for entities updatable by managers with timestamps and soft deletion.

    This class combines manager creation and update tracking with soft deletion,
    providing a complete audit trail throughout the entity's lifecycle.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        created_by/created_by_uuid: Reference to the manager who created the entity.
        updated_by/updated_by_uuid: Reference to the manager who last updated the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableAdminEntity

Bases: ArchivableEntity, AdminMixin

Base class for entities Archivable by admin.

This class extends ArchivableEntity with tracking of which administrator created the entity, supporting audit and accountability requirements.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableAdminEntity(ArchivableEntity, AdminMixin):
    """Base class for entities Archivable by admin.

    This class extends ArchivableEntity with tracking of which administrator created
    the entity, supporting audit and accountability requirements.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableManagerEntity

Bases: ArchivableEntity, ManagerMixin

Base class for entities Archivable by managers.

This class extends ArchivableEntity with tracking of which manager created the entity, supporting audit and accountability requirements.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

created_by/created_by_uuid

Reference to the manager who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableManagerEntity(ArchivableEntity, ManagerMixin):
    """Base class for entities Archivable by managers.

    This class extends ArchivableEntity with tracking of which manager created
    the entity, supporting audit and accountability requirements.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
        created_by/created_by_uuid: Reference to the manager who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableManagerAdminEntity

Bases: BaseEntity, UpdatableMixin, ManagerMixin, AdminMixin, UpdatableManagerMixin, UpdatableAdminMixin

Base class for entities updatable by both managers and admins with timestamps.

This class provides comprehensive tracking of entity creation and updates by both administrators and managers, supporting complex workflows where different user roles interact with the same data.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

created_by/created_by_uuid

Reference to the manager who created the entity.

updated_by_admin/updated_by_admin_uuid

Reference to the admin who last updated the entity.

updated_by/updated_by_uuid

Reference to the manager who last updated the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableManagerAdminEntity(
    BaseEntity,
    UpdatableMixin,
    ManagerMixin,
    AdminMixin,
    UpdatableManagerMixin,
    UpdatableAdminMixin,
):
    """Base class for entities updatable by both managers and admins with timestamps.

    This class provides comprehensive tracking of entity creation and updates
    by both administrators and managers, supporting complex workflows where
    different user roles interact with the same data.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
        created_by/created_by_uuid: Reference to the manager who created the entity.
        updated_by_admin/updated_by_admin_uuid: Reference to the admin who last updated the entity.
        updated_by/updated_by_uuid: Reference to the manager who last updated the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableManagerAdminEntity

Bases: ArchivableEntity, ManagerMixin, AdminMixin

Base class for entities Archivable by both managers and admins.

This class provides comprehensive tracking of entity creation by both administrators and managers, supporting complex workflows where different user roles interact with the same data.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

created_by/created_by_uuid

Reference to the manager who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableManagerAdminEntity(
    ArchivableEntity,
    ManagerMixin,
    AdminMixin,
):
    """Base class for entities Archivable by both managers and admins.

    This class provides comprehensive tracking of entity creation
    by both administrators and managers, supporting complex workflows where
    different user roles interact with the same data.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
        created_by/created_by_uuid: Reference to the manager who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableDeletableAdminEntity

Bases: ArchivableDeletableEntity, AdminMixin

Base class for entities Archivable and deletable by admin.

This class combines administrator creation tracking with soft deletion and archiving, providing a complete audit trail throughout the entity's lifecycle.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableDeletableAdminEntity(ArchivableDeletableEntity, AdminMixin):
    """Base class for entities Archivable and deletable by admin.

    This class combines administrator creation tracking with soft deletion and archiving,
    providing a complete audit trail throughout the entity's lifecycle.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableDeletableManagerEntity

Bases: ArchivableDeletableEntity, ManagerMixin

Base class for entities Archivable and deletable by managers.

This class combines manager creation tracking with soft deletion and archiving, providing a complete audit trail throughout the entity's lifecycle.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

created_by/created_by_uuid

Reference to the manager who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableDeletableManagerEntity(ArchivableDeletableEntity, ManagerMixin):
    """Base class for entities Archivable and deletable by managers.

    This class combines manager creation tracking with soft deletion and archiving,
    providing a complete audit trail throughout the entity's lifecycle.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
        created_by/created_by_uuid: Reference to the manager who created the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.UpdatableDeletableManagerAdminEntity

Bases: BaseEntity, UpdatableMixin, ManagerMixin, AdminMixin, UpdatableManagerMixin, UpdatableAdminMixin, DeletableMixin

Base class for entities updatable by both managers and admins with timestamps and soft deletion.

This is the most comprehensive entity class, supporting tracking of creation and updates by both administrators and managers, along with soft deletion capability. It provides complete accountability for all operations throughout the entity's lifecycle.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

created_by/created_by_uuid

Reference to the manager who created the entity.

updated_by_admin/updated_by_admin_uuid

Reference to the admin who last updated the entity.

updated_by/updated_by_uuid

Reference to the manager who last updated the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class UpdatableDeletableManagerAdminEntity(
    BaseEntity,
    UpdatableMixin,
    ManagerMixin,
    AdminMixin,
    UpdatableManagerMixin,
    UpdatableAdminMixin,
    DeletableMixin,
):
    """Base class for entities updatable by both managers and admins with timestamps and soft deletion.

    This is the most comprehensive entity class, supporting tracking of creation and
    updates by both administrators and managers, along with soft deletion capability.
    It provides complete accountability for all operations throughout the entity's lifecycle.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
        created_by/created_by_uuid: Reference to the manager who created the entity.
        updated_by_admin/updated_by_admin_uuid: Reference to the admin who last updated the entity.
        updated_by/updated_by_uuid: Reference to the manager who last updated the entity.
    """

    __abstract__ = True

archipy.models.entities.sqlalchemy.base_entities.ArchivableDeletableManagerAdminEntity

Bases: ArchivableDeletableEntity, ManagerMixin, AdminMixin

Base class for entities Archivable and deletable by both managers and admins.

This is a comprehensive entity class, supporting tracking of creation by both administrators and managers, along with soft deletion and archiving capability. It provides complete accountability for all operations throughout the entity's lifecycle.

Attributes:

Name Type Description
created_at Mapped[datetime]

Timestamp indicating when the entity was created.

updated_at

Timestamp indicating when the entity was last updated.

is_deleted

Flag indicating if the entity is deleted.

is_archived

Flag indicating if the entity is archived.

origin_uuid

Reference to the original entity.

created_by_admin/created_by_admin_uuid

Reference to the admin who created the entity.

created_by/created_by_uuid

Reference to the manager who created the entity.

Source code in archipy/models/entities/sqlalchemy/base_entities.py
class ArchivableDeletableManagerAdminEntity(
    ArchivableDeletableEntity,
    ManagerMixin,
    AdminMixin,
):
    """Base class for entities Archivable and deletable by both managers and admins.

    This is a comprehensive entity class, supporting tracking of creation
    by both administrators and managers, along with soft deletion and archiving capability.
    It provides complete accountability for all operations throughout the entity's lifecycle.

    Attributes:
        created_at: Timestamp indicating when the entity was created.
        updated_at: Timestamp indicating when the entity was last updated.
        is_deleted: Flag indicating if the entity is deleted.
        is_archived: Flag indicating if the entity is archived.
        origin_uuid: Reference to the original entity.
        created_by_admin/created_by_admin_uuid: Reference to the admin who created the entity.
        created_by/created_by_uuid: Reference to the manager who created the entity.
    """

    __abstract__ = True

options: show_root_heading: true show_source: true

Errors

The error handling system is organized into several categories, each handling specific types of errors:

Authentication Errors

Handles authentication and authorization related errors.

from archipy.models.errors import (
    UnauthenticatedError,
    InvalidCredentialsError,
    TokenExpiredError,
    InvalidTokenError,
    SessionExpiredError,
    PermissionDeniedError,
    AccountLockedError,
    AccountDisabledError,
    InvalidVerificationCodeError
)

# Example: Handle invalid credentials
try:
    authenticate_user(username, password)
except InvalidCredentialsError as e:
    logger.warning(f"Failed login attempt: {e}")

Validation Errors

Handles input validation and format errors.

from archipy.models.errors import (
    InvalidArgumentError,
    InvalidFormatError,
    InvalidEmailError,
    InvalidPhoneNumberError,
    InvalidLandlineNumberError,
    InvalidNationalCodeError,
    InvalidPasswordError,
    InvalidDateError,
    InvalidUrlError,
    InvalidIpError,
    InvalidJsonError,
    InvalidTimestampError,
    OutOfRangeError
)

# Example: Validate user input
try:
    validate_user_input(email, phone)
except InvalidEmailError as e:
    return {"error": e.to_dict()}

Resource Errors

Handles resource and data management errors.

from archipy.models.errors import (
    NotFoundError,
    AlreadyExistsError,
    ConflictError,
    ResourceLockedError,
    ResourceBusyError,
    DataLossError,
    InvalidEntityTypeError,
    FileTooLargeError,
    InvalidFileTypeError,
    QuotaExceededError
)

# Example: Handle resource not found
try:
    user = get_user(user_id)
except NotFoundError as e:
    return {"error": e.to_dict()}

Network Errors

Handles network and communication errors.

from archipy.models.errors import (
    NetworkError,
    ConnectionTimeoutError,
    ServiceUnavailableError,
    GatewayTimeoutError,
    BadGatewayError,
    RateLimitExceededError
)

# Example: Handle network issues
try:
    response = make_api_request()
except ConnectionTimeoutError as e:
    logger.error(f"Connection timeout: {e}")

Business Errors

Handles business logic and operation errors.

from archipy.models.errors import (
    InvalidStateError,
    BusinessRuleViolationError,
    InvalidOperationError,
    InsufficientFundsError,
    InsufficientBalanceError,
    MaintenanceModeError,
    FailedPreconditionError
)

# Example: Handle business rule violation
try:
    process_transaction(amount)
except InsufficientFundsError as e:
    return {"error": e.to_dict()}

Database Errors

Handles database and storage related errors.

from archipy.models.errors import (
    DatabaseConnectionError,
    DatabaseQueryError,
    DatabaseTransactionError,
    StorageError,
    CacheError,
    CacheMissError
)

# Example: Handle database errors
try:
    save_to_database(data)
except DatabaseConnectionError as e:
    logger.error(f"Database connection failed: {e}")

System Errors

Handles system and internal errors.

from archipy.models.errors import (
    InternalError,
    ConfigurationError,
    ResourceExhaustedError,
    UnavailableError,
    UnknownError,
    AbortedError,
    DeadlockDetectedError
)

# Example: Handle system errors
try:
    process_request()
except DeadlockDetectedError as e:
    logger.error(f"Deadlock detected: {e}")
    # Implement retry logic

Error handling module for the application.

This module provides a comprehensive set of custom exceptions for handling various error scenarios in the application, organized by category.

archipy.models.errors.AccountDisabledError

Bases: BaseError

Exception raised when an account is disabled.

Source code in archipy/models/errors/auth_errors.py
class AccountDisabledError(BaseError):
    """Exception raised when an account is disabled."""

    def __init__(
        self,
        username: str | None = None,
        reason: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.ACCOUNT_DISABLED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if username:
            data["username"] = username
        if reason:
            data["reason"] = reason
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.AccountLockedError

Bases: BaseError

Exception raised when an account is locked.

Source code in archipy/models/errors/auth_errors.py
class AccountLockedError(BaseError):
    """Exception raised when an account is locked."""

    def __init__(
        self,
        username: str | None = None,
        lockout_duration: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.ACCOUNT_LOCKED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if username:
            data["username"] = username
        if lockout_duration:
            data["lockout_duration"] = lockout_duration
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidCredentialsError

Bases: BaseError

Exception raised for invalid credentials.

Source code in archipy/models/errors/auth_errors.py
class InvalidCredentialsError(BaseError):
    """Exception raised for invalid credentials."""

    def __init__(
        self,
        username: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_CREDENTIALS.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"username": username} if username else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidTokenError

Bases: BaseError

Exception raised when a token is invalid.

Source code in archipy/models/errors/auth_errors.py
class InvalidTokenError(BaseError):
    """Exception raised when a token is invalid."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_TOKEN.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.InvalidVerificationCodeError

Bases: BaseError

Exception raised when a verification code is invalid.

Source code in archipy/models/errors/auth_errors.py
class InvalidVerificationCodeError(BaseError):
    """Exception raised when a verification code is invalid."""

    def __init__(
        self,
        code: str | None = None,
        remaining_attempts: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_VERIFICATION_CODE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if code:
            data["code"] = code
        if remaining_attempts is not None:
            data["remaining_attempts"] = remaining_attempts
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.PermissionDeniedError

Bases: BaseError

Exception raised when permission is denied.

Source code in archipy/models/errors/auth_errors.py
class PermissionDeniedError(BaseError):
    """Exception raised when permission is denied."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.PERMISSION_DENIED.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.SessionExpiredError

Bases: BaseError

Exception raised when a session has expired.

Source code in archipy/models/errors/auth_errors.py
class SessionExpiredError(BaseError):
    """Exception raised when a session has expired."""

    def __init__(
        self,
        session_id: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.SESSION_EXPIRED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"session_id": session_id} if session_id else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.TokenExpiredError

Bases: BaseError

Exception raised when a token has expired.

Source code in archipy/models/errors/auth_errors.py
class TokenExpiredError(BaseError):
    """Exception raised when a token has expired."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.TOKEN_EXPIRED.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.UnauthenticatedError

Bases: BaseError

Exception raised when a user is unauthenticated.

Source code in archipy/models/errors/auth_errors.py
class UnauthenticatedError(BaseError):
    """Exception raised when a user is unauthenticated."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.UNAUTHENTICATED.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.BaseError

Bases: Exception

Base exception class for all custom errors.

This class provides a standardized way to handle errors with support for: - Localization of error messages - Additional context data - Integration with HTTP and gRPC status codes

Attributes:

Name Type Description
error ErrorDetailDTO

The error details including message and status codes.

lang LanguageType

The language for the error message.

additional_data dict[str, Any] | None

Additional context data for the error.

http_status_code ClassVar[int]

HTTP status code for the error.

grpc_status_code ClassVar[int]

gRPC status code for the error.

Source code in archipy/models/errors/base_error.py
class BaseError(Exception):
    """Base exception class for all custom errors.

    This class provides a standardized way to handle errors with support for:
    - Localization of error messages
    - Additional context data
    - Integration with HTTP and gRPC status codes

    Attributes:
        error (ErrorDetailDTO): The error details including message and status codes.
        lang (LanguageType): The language for the error message.
        additional_data (dict[str, Any] | None): Additional context data for the error.
        http_status_code (ClassVar[int]): HTTP status code for the error.
        grpc_status_code (ClassVar[int]): gRPC status code for the error.
    """

    http_status_code: ClassVar[int] = 500
    grpc_status_code: ClassVar[int] = 13  # INTERNAL

    def __init__(
        self,
        error: ErrorDetailDTO | ErrorMessageType | None = None,
        lang: LanguageType = LanguageType.FA,
        additional_data: dict | None = None,
        *args: object,
    ) -> None:
        """Initialize the error with message and optional context.

        Args:
            error: The error detail or message. Can be:
                - ErrorDetail: Direct error detail object
                - ExceptionMessageType: Enum member containing error detail
                - None: Will use UNKNOWN_ERROR
            lang: Language code for the error message (defaults to Persian).
            additional_data: Additional context data for the error.
            *args: Additional arguments for the base Exception class.
        """
        if isinstance(error, ErrorMessageType):
            self.error_detail = error.value
        elif isinstance(error, ErrorDetailDTO):
            self.error_detail = error
        else:
            self.error_detail = ErrorMessageType.UNKNOWN_ERROR.value

        self.lang = lang
        self.additional_data = additional_data or {}

        # Initialize base Exception with the message
        super().__init__(self.get_message(), *args)

    def get_message(self) -> str:
        """Gets the localized error message based on the language setting.

        Returns:
            str: The error message in the current language.
        """
        return self.error_detail.message_fa if self.lang == LanguageType.FA else self.error_detail.message_en

    def to_dict(self) -> dict:
        """Converts the exception to a dictionary format for API responses.

        Returns:
            dict: A dictionary containing error details and additional data.
        """
        response = {
            "error": self.error_detail.code,
            "detail": self.error_detail.model_dump(mode="json", exclude_none=True),
        }

        # Add additional data if present
        detail = response["detail"]
        if isinstance(detail, dict) and self.additional_data:
            detail.update(self.additional_data)

        return response

    @property
    def http_status_code(self) -> int | None:
        """Gets the HTTP status code if HTTP support is available.

        Returns:
            Optional[int]: The HTTP status code or None if HTTP is not available.
        """
        return self.error_detail.http_status if HTTP_AVAILABLE else None

    @property
    def grpc_status_code(self) -> int | None:
        """Gets the gRPC status code if gRPC support is available.

        Returns:
            Optional[int]: The gRPC status code or None if gRPC is not available.
        """
        return self.error_detail.grpc_status if GRPC_AVAILABLE else None

    def __str__(self) -> str:
        """String representation of the exception.

        Returns:
            str: A formatted string containing the error code and message.
        """
        return f"[{self.error_detail.code}] {self.get_message()}"

    def __repr__(self) -> str:
        """Detailed string representation of the exception.

        Returns:
            str: A detailed string representation including all error details.
        """
        return (
            f"{self.__class__.__name__}("
            f"code='{self.error_detail.code}', "
            f"message='{self.get_message()}', "
            f"http_status={self.http_status_code}, "
            f"grpc_status={self.grpc_status_code}, "
            f"additional_data={self.additional_data}"
            f")"
        )

    @property
    def code(self) -> str:
        """Gets the error code.

        Returns:
            str: The error code.
        """
        return self.error_detail.code

    @property
    def message(self) -> str:
        """Gets the current language message.

        Returns:
            str: The error message in the current language.
        """
        return self.get_message()

    @property
    def message_en(self) -> str:
        """Gets the English message.

        Returns:
            str: The English error message.
        """
        return self.error_detail.message_en

    @property
    def message_fa(self) -> str:
        """Gets the Persian message.

        Returns:
            str: The Persian error message.
        """
        return self.error_detail.message_fa

archipy.models.errors.BaseError.http_status_code property

Gets the HTTP status code if HTTP support is available.

Returns:

Type Description
int | None

Optional[int]: The HTTP status code or None if HTTP is not available.

archipy.models.errors.BaseError.grpc_status_code property

Gets the gRPC status code if gRPC support is available.

Returns:

Type Description
int | None

Optional[int]: The gRPC status code or None if gRPC is not available.

archipy.models.errors.BaseError.code property

Gets the error code.

Returns:

Name Type Description
str str

The error code.

archipy.models.errors.BaseError.message property

Gets the current language message.

Returns:

Name Type Description
str str

The error message in the current language.

archipy.models.errors.BaseError.message_en property

Gets the English message.

Returns:

Name Type Description
str str

The English error message.

archipy.models.errors.BaseError.message_fa property

Gets the Persian message.

Returns:

Name Type Description
str str

The Persian error message.

archipy.models.errors.BaseError.__init__(error=None, lang=LanguageType.FA, additional_data=None, *args)

Initialize the error with message and optional context.

Parameters:

Name Type Description Default
error ErrorDetailDTO | ErrorMessageType | None

The error detail or message. Can be: - ErrorDetail: Direct error detail object - ExceptionMessageType: Enum member containing error detail - None: Will use UNKNOWN_ERROR

None
lang LanguageType

Language code for the error message (defaults to Persian).

FA
additional_data dict | None

Additional context data for the error.

None
*args object

Additional arguments for the base Exception class.

()
Source code in archipy/models/errors/base_error.py
def __init__(
    self,
    error: ErrorDetailDTO | ErrorMessageType | None = None,
    lang: LanguageType = LanguageType.FA,
    additional_data: dict | None = None,
    *args: object,
) -> None:
    """Initialize the error with message and optional context.

    Args:
        error: The error detail or message. Can be:
            - ErrorDetail: Direct error detail object
            - ExceptionMessageType: Enum member containing error detail
            - None: Will use UNKNOWN_ERROR
        lang: Language code for the error message (defaults to Persian).
        additional_data: Additional context data for the error.
        *args: Additional arguments for the base Exception class.
    """
    if isinstance(error, ErrorMessageType):
        self.error_detail = error.value
    elif isinstance(error, ErrorDetailDTO):
        self.error_detail = error
    else:
        self.error_detail = ErrorMessageType.UNKNOWN_ERROR.value

    self.lang = lang
    self.additional_data = additional_data or {}

    # Initialize base Exception with the message
    super().__init__(self.get_message(), *args)

archipy.models.errors.BaseError.get_message()

Gets the localized error message based on the language setting.

Returns:

Name Type Description
str str

The error message in the current language.

Source code in archipy/models/errors/base_error.py
def get_message(self) -> str:
    """Gets the localized error message based on the language setting.

    Returns:
        str: The error message in the current language.
    """
    return self.error_detail.message_fa if self.lang == LanguageType.FA else self.error_detail.message_en

archipy.models.errors.BaseError.to_dict()

Converts the exception to a dictionary format for API responses.

Returns:

Name Type Description
dict dict

A dictionary containing error details and additional data.

Source code in archipy/models/errors/base_error.py
def to_dict(self) -> dict:
    """Converts the exception to a dictionary format for API responses.

    Returns:
        dict: A dictionary containing error details and additional data.
    """
    response = {
        "error": self.error_detail.code,
        "detail": self.error_detail.model_dump(mode="json", exclude_none=True),
    }

    # Add additional data if present
    detail = response["detail"]
    if isinstance(detail, dict) and self.additional_data:
        detail.update(self.additional_data)

    return response

archipy.models.errors.BaseError.__str__()

String representation of the exception.

Returns:

Name Type Description
str str

A formatted string containing the error code and message.

Source code in archipy/models/errors/base_error.py
def __str__(self) -> str:
    """String representation of the exception.

    Returns:
        str: A formatted string containing the error code and message.
    """
    return f"[{self.error_detail.code}] {self.get_message()}"

archipy.models.errors.BaseError.__repr__()

Detailed string representation of the exception.

Returns:

Name Type Description
str str

A detailed string representation including all error details.

Source code in archipy/models/errors/base_error.py
def __repr__(self) -> str:
    """Detailed string representation of the exception.

    Returns:
        str: A detailed string representation including all error details.
    """
    return (
        f"{self.__class__.__name__}("
        f"code='{self.error_detail.code}', "
        f"message='{self.get_message()}', "
        f"http_status={self.http_status_code}, "
        f"grpc_status={self.grpc_status_code}, "
        f"additional_data={self.additional_data}"
        f")"
    )

archipy.models.errors.BusinessRuleViolationError

Bases: BaseError

Exception raised when a business rule is violated.

Source code in archipy/models/errors/business_errors.py
class BusinessRuleViolationError(BaseError):
    """Exception raised when a business rule is violated."""

    def __init__(
        self,
        rule: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.BUSINESS_RULE_VIOLATION.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if rule:
            data["rule"] = rule
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.FailedPreconditionError

Bases: BaseError

Exception raised when a precondition for an operation is not met.

Source code in archipy/models/errors/business_errors.py
class FailedPreconditionError(BaseError):
    """Exception raised when a precondition for an operation is not met."""

    def __init__(
        self,
        precondition: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.FAILED_PRECONDITION.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if precondition:
            data["precondition"] = precondition
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InsufficientBalanceError

Bases: BaseError

Exception raised when an operation fails due to insufficient account balance.

Source code in archipy/models/errors/business_errors.py
class InsufficientBalanceError(BaseError):
    """Exception raised when an operation fails due to insufficient account balance."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INSUFFICIENT_BALANCE.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.InsufficientFundsError

Bases: BaseError

Exception raised when there are insufficient funds for an operation.

Source code in archipy/models/errors/business_errors.py
class InsufficientFundsError(BaseError):
    """Exception raised when there are insufficient funds for an operation."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INSUFFICIENT_FUNDS.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.InvalidOperationError

Bases: BaseError

Exception raised when an operation is not allowed in the current context.

Source code in archipy/models/errors/business_errors.py
class InvalidOperationError(BaseError):
    """Exception raised when an operation is not allowed in the current context."""

    def __init__(
        self,
        operation: str | None = None,
        context: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_OPERATION.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if operation:
            data["operation"] = operation
        if context:
            data["context"] = context
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidStateError

Bases: BaseError

Exception raised when an operation is attempted in an invalid state.

Source code in archipy/models/errors/business_errors.py
class InvalidStateError(BaseError):
    """Exception raised when an operation is attempted in an invalid state."""

    def __init__(
        self,
        current_state: str | None = None,
        expected_state: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_STATE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if current_state:
            data["current_state"] = current_state
        if expected_state:
            data["expected_state"] = expected_state
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.MaintenanceModeError

Bases: BaseError

Exception raised when the system is in maintenance mode.

Source code in archipy/models/errors/business_errors.py
class MaintenanceModeError(BaseError):
    """Exception raised when the system is in maintenance mode."""

    def __init__(
        self,
        estimated_duration: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.MAINTENANCE_MODE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"estimated_duration": estimated_duration} if estimated_duration else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.CacheError

Bases: BaseError

Exception raised for cache access errors.

Source code in archipy/models/errors/database_errors.py
class CacheError(BaseError):
    """Exception raised for cache access errors."""

    def __init__(
        self,
        cache_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.CACHE_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if cache_type:
            data["cache_type"] = cache_type
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.CacheMissError

Bases: BaseError

Exception raised when requested data is not found in cache.

Source code in archipy/models/errors/database_errors.py
class CacheMissError(BaseError):
    """Exception raised when requested data is not found in cache."""

    def __init__(
        self,
        cache_key: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.CACHE_MISS.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"cache_key": cache_key} if cache_key else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.DatabaseConfigurationError

Bases: DatabaseError

Exception raised for database configuration errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseConfigurationError(DatabaseError):
    """Exception raised for database configuration errors."""

    def __init__(
        self,
        database: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_CONFIGURATION_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(database, lang, error, additional_data)

archipy.models.errors.DatabaseConnectionError

Bases: DatabaseError

Exception raised for database connection errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseConnectionError(DatabaseError):
    """Exception raised for database connection errors."""

    def __init__(
        self,
        database: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_CONNECTION_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(database, lang, error, additional_data)

archipy.models.errors.DatabaseConstraintError

Bases: DatabaseError

Exception raised for database constraint violations.

Source code in archipy/models/errors/database_errors.py
class DatabaseConstraintError(DatabaseError):
    """Exception raised for database constraint violations."""

    def __init__(
        self,
        database: str | None = None,
        constraint: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_CONSTRAINT_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if constraint:
            data["constraint"] = constraint
        if additional_data:
            data.update(additional_data)
        super().__init__(database, lang, error, data if data else None)

archipy.models.errors.DatabaseDeadlockError

Bases: DatabaseError

Exception raised for database deadlock errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseDeadlockError(DatabaseError):
    """Exception raised for database deadlock errors."""

    def __init__(
        self,
        database: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_DEADLOCK_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(database, lang, error, additional_data)

archipy.models.errors.DatabaseError

Bases: BaseError

Base class for all database-related errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseError(BaseError):
    """Base class for all database-related errors."""

    def __init__(
        self,
        database: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if database:
            data["database"] = database
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.DatabaseIntegrityError

Bases: DatabaseError

Exception raised for database integrity violations.

Source code in archipy/models/errors/database_errors.py
class DatabaseIntegrityError(DatabaseError):
    """Exception raised for database integrity violations."""

    def __init__(
        self,
        database: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_INTEGRITY_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(database, lang, error, additional_data)

archipy.models.errors.DatabaseQueryError

Bases: DatabaseError

Exception raised for database query errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseQueryError(DatabaseError):
    """Exception raised for database query errors."""

    def __init__(
        self,
        database: str | None = None,
        query: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_QUERY_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if query:
            data["query"] = query
        if additional_data:
            data.update(additional_data)
        super().__init__(database, lang, error, data if data else None)

archipy.models.errors.DatabaseSerializationError

Bases: DatabaseError

Exception raised for database serialization errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseSerializationError(DatabaseError):
    """Exception raised for database serialization errors."""

    def __init__(
        self,
        database: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_SERIALIZATION_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(database, lang, error, additional_data)

archipy.models.errors.DatabaseTimeoutError

Bases: DatabaseError

Exception raised for database timeout errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseTimeoutError(DatabaseError):
    """Exception raised for database timeout errors."""

    def __init__(
        self,
        database: str | None = None,
        timeout: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_TIMEOUT_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if timeout:
            data["timeout"] = timeout
        if additional_data:
            data.update(additional_data)
        super().__init__(database, lang, error, data if data else None)

archipy.models.errors.DatabaseTransactionError

Bases: DatabaseError

Exception raised for database transaction errors.

Source code in archipy/models/errors/database_errors.py
class DatabaseTransactionError(DatabaseError):
    """Exception raised for database transaction errors."""

    def __init__(
        self,
        database: str | None = None,
        transaction_id: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATABASE_TRANSACTION_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if transaction_id:
            data["transaction_id"] = transaction_id
        if additional_data:
            data.update(additional_data)
        super().__init__(database, lang, error, data if data else None)

archipy.models.errors.BadGatewayError

Bases: BaseError

Exception raised when a gateway returns an invalid response.

Source code in archipy/models/errors/network_errors.py
class BadGatewayError(BaseError):
    """Exception raised when a gateway returns an invalid response."""

    def __init__(
        self,
        gateway: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.BAD_GATEWAY.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if gateway:
            data["gateway"] = gateway
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ConnectionTimeoutError

Bases: BaseError

Exception raised when a connection times out.

Source code in archipy/models/errors/network_errors.py
class ConnectionTimeoutError(BaseError):
    """Exception raised when a connection times out."""

    def __init__(
        self,
        service: str | None = None,
        timeout: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.CONNECTION_TIMEOUT.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if service:
            data["service"] = service
        if timeout:
            data["timeout"] = timeout
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.GatewayTimeoutError

Bases: BaseError

Exception raised when a gateway times out.

Source code in archipy/models/errors/network_errors.py
class GatewayTimeoutError(BaseError):
    """Exception raised when a gateway times out."""

    def __init__(
        self,
        gateway: str | None = None,
        timeout: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.GATEWAY_TIMEOUT.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if gateway:
            data["gateway"] = gateway
        if timeout:
            data["timeout"] = timeout
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.NetworkError

Bases: BaseError

Exception raised for network-related errors.

Source code in archipy/models/errors/network_errors.py
class NetworkError(BaseError):
    """Exception raised for network-related errors."""

    def __init__(
        self,
        service: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.NETWORK_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if service:
            data["service"] = service
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.RateLimitExceededError

Bases: BaseError

Exception raised when a rate limit is exceeded.

Source code in archipy/models/errors/network_errors.py
class RateLimitExceededError(BaseError):
    """Exception raised when a rate limit is exceeded."""

    def __init__(
        self,
        rate_limit_type: str | None = None,
        retry_after: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.RATE_LIMIT_EXCEEDED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if rate_limit_type:
            data["rate_limit_type"] = rate_limit_type
        if retry_after:
            data["retry_after"] = retry_after
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ServiceUnavailableError

Bases: BaseError

Exception raised when a service is unavailable.

Source code in archipy/models/errors/network_errors.py
class ServiceUnavailableError(BaseError):
    """Exception raised when a service is unavailable."""

    def __init__(
        self,
        service: str | None = None,
        retry_after: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.SERVICE_UNAVAILABLE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if service:
            data["service"] = service
        if retry_after:
            data["retry_after"] = retry_after
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.AlreadyExistsError

Bases: BaseError

Exception raised when a resource already exists.

Source code in archipy/models/errors/resource_errors.py
class AlreadyExistsError(BaseError):
    """Exception raised when a resource already exists."""

    def __init__(
        self,
        resource_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.ALREADY_EXISTS.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"resource_type": resource_type} if resource_type else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ConflictError

Bases: BaseError

Exception raised when there is a resource conflict.

Source code in archipy/models/errors/resource_errors.py
class ConflictError(BaseError):
    """Exception raised when there is a resource conflict."""

    def __init__(
        self,
        resource_type: str | None = None,
        resource_id: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.CONFLICT.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if resource_type:
            data["resource_type"] = resource_type
        if resource_id:
            data["resource_id"] = resource_id
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.DataLossError

Bases: BaseError

Exception raised when data is lost.

Source code in archipy/models/errors/resource_errors.py
class DataLossError(BaseError):
    """Exception raised when data is lost."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DATA_LOSS.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.FileTooLargeError

Bases: BaseError

Exception raised when a file is too large.

Source code in archipy/models/errors/resource_errors.py
class FileTooLargeError(BaseError):
    """Exception raised when a file is too large."""

    def __init__(
        self,
        file_name: str | None = None,
        file_size: int | None = None,
        max_size: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.FILE_TOO_LARGE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if file_name:
            data["file_name"] = file_name
        if file_size:
            data["file_size"] = file_size
        if max_size:
            data["max_size"] = max_size
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidEntityTypeError

Bases: BaseError

Exception raised for invalid entity types.

Source code in archipy/models/errors/resource_errors.py
class InvalidEntityTypeError(BaseError):
    """Exception raised for invalid entity types."""

    def __init__(
        self,
        message: str | None = None,
        expected_type: str | None = None,
        actual_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_ENTITY_TYPE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if message:
            data["message"] = message
        if expected_type:
            data["expected_type"] = expected_type
        if actual_type:
            data["actual_type"] = actual_type
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidFileTypeError

Bases: BaseError

Exception raised for invalid file types.

Source code in archipy/models/errors/resource_errors.py
class InvalidFileTypeError(BaseError):
    """Exception raised for invalid file types."""

    def __init__(
        self,
        file_name: str | None = None,
        file_type: str | None = None,
        allowed_types: list[str] | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_FILE_TYPE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if file_name:
            data["file_name"] = file_name
        if file_type:
            data["file_type"] = file_type
        if allowed_types:
            data["allowed_types"] = allowed_types
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.NotFoundError

Bases: BaseError

Exception raised when a resource is not found.

Source code in archipy/models/errors/resource_errors.py
class NotFoundError(BaseError):
    """Exception raised when a resource is not found."""

    def __init__(
        self,
        resource_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.NOT_FOUND.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"resource_type": resource_type} if resource_type else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.QuotaExceededError

Bases: BaseError

Exception raised when a quota is exceeded.

Source code in archipy/models/errors/resource_errors.py
class QuotaExceededError(BaseError):
    """Exception raised when a quota is exceeded."""

    def __init__(
        self,
        quota_type: str | None = None,
        current_usage: int | None = None,
        quota_limit: int | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.QUOTA_EXCEEDED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if quota_type:
            data["quota_type"] = quota_type
        if current_usage:
            data["current_usage"] = current_usage
        if quota_limit:
            data["quota_limit"] = quota_limit
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ResourceBusyError

Bases: BaseError

Exception raised when a resource is busy.

Source code in archipy/models/errors/resource_errors.py
class ResourceBusyError(BaseError):
    """Exception raised when a resource is busy."""

    def __init__(
        self,
        resource_id: str | None = None,
        busy_reason: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.RESOURCE_BUSY.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if resource_id:
            data["resource_id"] = resource_id
        if busy_reason:
            data["busy_reason"] = busy_reason
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ResourceExhaustedError

Bases: BaseError

Exception raised when a resource is exhausted.

Source code in archipy/models/errors/resource_errors.py
class ResourceExhaustedError(BaseError):
    """Exception raised when a resource is exhausted."""

    def __init__(
        self,
        resource_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.RESOURCE_EXHAUSTED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"resource_type": resource_type} if resource_type else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ResourceLockedError

Bases: BaseError

Exception raised when a resource is locked.

Source code in archipy/models/errors/resource_errors.py
class ResourceLockedError(BaseError):
    """Exception raised when a resource is locked."""

    def __init__(
        self,
        resource_id: str | None = None,
        lock_owner: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.RESOURCE_LOCKED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if resource_id:
            data["resource_id"] = resource_id
        if lock_owner:
            data["lock_owner"] = lock_owner
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.StorageError

Bases: BaseError

Exception raised for storage-related errors.

Source code in archipy/models/errors/resource_errors.py
class StorageError(BaseError):
    """Exception raised for storage-related errors."""

    def __init__(
        self,
        storage_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.STORAGE_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"storage_type": storage_type} if storage_type else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.AbortedError

Bases: BaseError

Exception raised when an operation is aborted.

Source code in archipy/models/errors/system_errors.py
class AbortedError(BaseError):
    """Exception raised when an operation is aborted."""

    def __init__(
        self,
        operation: str | None = None,
        reason: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.ABORTED.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if operation:
            data["operation"] = operation
        if reason:
            data["reason"] = reason
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.ConfigurationError

Bases: BaseError

Exception raised for system configuration errors.

Source code in archipy/models/errors/system_errors.py
class ConfigurationError(BaseError):
    """Exception raised for system configuration errors."""

    def __init__(
        self,
        config_key: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.CONFIGURATION_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if config_key:
            data["config_key"] = config_key
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.DeadlockDetectedError

Bases: BaseError

Exception raised when a deadlock is detected in the system.

Source code in archipy/models/errors/system_errors.py
class DeadlockDetectedError(BaseError):
    """Exception raised when a deadlock is detected in the system."""

    def __init__(
        self,
        resource_type: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.DEADLOCK.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if resource_type:
            data["resource_type"] = resource_type
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InternalError

Bases: BaseError

Exception raised for unexpected internal errors.

Source code in archipy/models/errors/system_errors.py
class InternalError(BaseError):
    """Exception raised for unexpected internal errors."""

    def __init__(
        self,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INTERNAL_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        super().__init__(error, lang, additional_data)

archipy.models.errors.UnavailableError

Bases: BaseError

Exception raised when a requested service or feature is unavailable.

Source code in archipy/models/errors/system_errors.py
class UnavailableError(BaseError):
    """Exception raised when a requested service or feature is unavailable."""

    def __init__(
        self,
        service: str | None = None,
        reason: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.UNAVAILABLE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if service:
            data["service"] = service
        if reason:
            data["reason"] = reason
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.UnknownError

Bases: BaseError

Exception raised for unknown or unexpected error conditions.

Source code in archipy/models/errors/system_errors.py
class UnknownError(BaseError):
    """Exception raised for unknown or unexpected error conditions."""

    def __init__(
        self,
        error_code: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.UNKNOWN_ERROR.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if error_code:
            data["error_code"] = error_code
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidArgumentError

Bases: BaseError

Exception raised for invalid arguments.

Source code in archipy/models/errors/validation_errors.py
class InvalidArgumentError(BaseError):
    """Exception raised for invalid arguments."""

    def __init__(
        self,
        argument_name: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_ARGUMENT.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"argument": argument_name} if argument_name else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidDateError

Bases: BaseError

Exception raised for invalid date formats.

Source code in archipy/models/errors/validation_errors.py
class InvalidDateError(BaseError):
    """Exception raised for invalid date formats."""

    def __init__(
        self,
        date: str | None = None,
        expected_format: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_DATE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if date:
            data["date"] = date
        if expected_format:
            data["expected_format"] = expected_format
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidEmailError

Bases: BaseError

Exception raised for invalid email formats.

Source code in archipy/models/errors/validation_errors.py
class InvalidEmailError(BaseError):
    """Exception raised for invalid email formats."""

    def __init__(
        self,
        email: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_EMAIL.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"email": email} if email else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidFormatError

Bases: BaseError

Exception raised for invalid data formats.

Source code in archipy/models/errors/validation_errors.py
class InvalidFormatError(BaseError):
    """Exception raised for invalid data formats."""

    def __init__(
        self,
        format_type: str | None = None,
        expected_format: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_FORMAT.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if format_type:
            data["format_type"] = format_type
        if expected_format:
            data["expected_format"] = expected_format
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidIpError

Bases: BaseError

Exception raised for invalid IP address formats.

Source code in archipy/models/errors/validation_errors.py
class InvalidIpError(BaseError):
    """Exception raised for invalid IP address formats."""

    def __init__(
        self,
        ip: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_IP.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"ip": ip} if ip else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidJsonError

Bases: BaseError

Exception raised for invalid JSON formats.

Source code in archipy/models/errors/validation_errors.py
class InvalidJsonError(BaseError):
    """Exception raised for invalid JSON formats."""

    def __init__(
        self,
        json_data: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_JSON.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if json_data:
            data["json_data"] = json_data
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidLandlineNumberError

Bases: BaseError

Exception raised for invalid landline numbers.

Source code in archipy/models/errors/validation_errors.py
class InvalidLandlineNumberError(BaseError):
    """Exception raised for invalid landline numbers."""

    def __init__(
        self,
        landline_number: str,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_LANDLINE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"landline_number": landline_number}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data)

archipy.models.errors.InvalidNationalCodeError

Bases: BaseError

Exception raised for invalid national codes.

Source code in archipy/models/errors/validation_errors.py
class InvalidNationalCodeError(BaseError):
    """Exception raised for invalid national codes."""

    def __init__(
        self,
        national_code: str,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_NATIONAL_CODE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"national_code": national_code}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data)

archipy.models.errors.InvalidPasswordError

Bases: BaseError

Exception raised when a password does not meet the security requirements.

Source code in archipy/models/errors/validation_errors.py
class InvalidPasswordError(BaseError):
    """Exception raised when a password does not meet the security requirements."""

    def __init__(
        self,
        requirements: list[str] | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_PASSWORD.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"requirements": requirements} if requirements else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidPhoneNumberError

Bases: BaseError

Exception raised for invalid phone numbers.

Source code in archipy/models/errors/validation_errors.py
class InvalidPhoneNumberError(BaseError):
    """Exception raised for invalid phone numbers."""

    def __init__(
        self,
        phone_number: str,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_PHONE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"phone_number": phone_number}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data)

archipy.models.errors.InvalidTimestampError

Bases: BaseError

Exception raised when a timestamp format is invalid.

Source code in archipy/models/errors/validation_errors.py
class InvalidTimestampError(BaseError):
    """Exception raised when a timestamp format is invalid."""

    def __init__(
        self,
        timestamp: str | None = None,
        expected_format: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_TIMESTAMP.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {}
        if timestamp:
            data["timestamp"] = timestamp
        if expected_format:
            data["expected_format"] = expected_format
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.InvalidUrlError

Bases: BaseError

Exception raised for invalid URL formats.

Source code in archipy/models/errors/validation_errors.py
class InvalidUrlError(BaseError):
    """Exception raised for invalid URL formats."""

    def __init__(
        self,
        url: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.INVALID_URL.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"url": url} if url else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

archipy.models.errors.OutOfRangeError

Bases: BaseError

Exception raised when a value is out of range.

Source code in archipy/models/errors/validation_errors.py
class OutOfRangeError(BaseError):
    """Exception raised when a value is out of range."""

    def __init__(
        self,
        field_name: str | None = None,
        lang: LanguageType = LanguageType.FA,
        error: ErrorDetailDTO = ErrorMessageType.OUT_OF_RANGE.value,
        additional_data: dict | None = None,
    ) -> None:
        data = {"field": field_name} if field_name else {}
        if additional_data:
            data.update(additional_data)
        super().__init__(error, lang, data if data else None)

options: show_root_heading: true show_source: true

Types

Base Types

Basic type definitions used throughout the application.

archipy.models.types.base_types.BaseType

Bases: Enum

Base class for creating enumerated types with custom values.

This class extends the Enum class to allow custom values for enum members.

Source code in archipy/models/types/base_types.py
class BaseType(Enum):
    """Base class for creating enumerated types with custom values.

    This class extends the `Enum` class to allow custom values for enum members.
    """

    def __new__(cls, *args: object, **_: object) -> "BaseType":
        """Create a new instance of the enum member.

        Args:
            cls: The enum class.
            *args: Arguments passed to the enum member.
            **_: Unused keyword arguments.

        Returns:
            BaseType: A new instance of the enum member with the custom value.
        """
        obj = object.__new__(cls)
        obj._value_ = args[0]
        return obj

archipy.models.types.base_types.BaseType.__new__(*args, **_)

Create a new instance of the enum member.

Parameters:

Name Type Description Default
cls

The enum class.

required
*args object

Arguments passed to the enum member.

()
**_ object

Unused keyword arguments.

{}

Returns:

Name Type Description
BaseType BaseType

A new instance of the enum member with the custom value.

Source code in archipy/models/types/base_types.py
def __new__(cls, *args: object, **_: object) -> "BaseType":
    """Create a new instance of the enum member.

    Args:
        cls: The enum class.
        *args: Arguments passed to the enum member.
        **_: Unused keyword arguments.

    Returns:
        BaseType: A new instance of the enum member with the custom value.
    """
    obj = object.__new__(cls)
    obj._value_ = args[0]
    return obj

archipy.models.types.base_types.FilterOperationType

Bases: Enum

Enumeration of filter operations for querying or filtering data.

This enum defines the types of operations that can be used in filtering, such as equality checks, comparisons, and string matching.

Attributes:

Name Type Description
EQUAL str

Represents an equality check.

NOT_EQUAL str

Represents a non-equality check.

LESS_THAN str

Represents a less-than comparison.

LESS_THAN_OR_EQUAL str

Represents a less-than-or-equal comparison.

GREATER_THAN str

Represents a greater-than comparison.

GREATER_THAN_OR_EQUAL str

Represents a greater-than-or-equal comparison.

IN_LIST str

Represents a check for membership in a list.

NOT_IN_LIST str

Represents a check for non-membership in a list.

LIKE str

Represents a case-sensitive string pattern match.

ILIKE str

Represents a case-insensitive string pattern match.

STARTS_WITH str

Represents a check if a string starts with a given prefix.

ENDS_WITH str

Represents a check if a string ends with a given suffix.

CONTAINS str

Represents a check if a string contains a given substring.

IS_NULL str

Represents a check if a value is null.

IS_NOT_NULL str

Represents a check if a value is not null.

Source code in archipy/models/types/base_types.py
class FilterOperationType(Enum):
    """Enumeration of filter operations for querying or filtering data.

    This enum defines the types of operations that can be used in filtering,
    such as equality checks, comparisons, and string matching.

    Attributes:
        EQUAL (str): Represents an equality check.
        NOT_EQUAL (str): Represents a non-equality check.
        LESS_THAN (str): Represents a less-than comparison.
        LESS_THAN_OR_EQUAL (str): Represents a less-than-or-equal comparison.
        GREATER_THAN (str): Represents a greater-than comparison.
        GREATER_THAN_OR_EQUAL (str): Represents a greater-than-or-equal comparison.
        IN_LIST (str): Represents a check for membership in a list.
        NOT_IN_LIST (str): Represents a check for non-membership in a list.
        LIKE (str): Represents a case-sensitive string pattern match.
        ILIKE (str): Represents a case-insensitive string pattern match.
        STARTS_WITH (str): Represents a check if a string starts with a given prefix.
        ENDS_WITH (str): Represents a check if a string ends with a given suffix.
        CONTAINS (str): Represents a check if a string contains a given substring.
        IS_NULL (str): Represents a check if a value is null.
        IS_NOT_NULL (str): Represents a check if a value is not null.
    """

    EQUAL = "equal"
    NOT_EQUAL = "not_equal"
    LESS_THAN = "less_than"
    LESS_THAN_OR_EQUAL = "less_than_or_equal"
    GREATER_THAN = "greater_than"
    GREATER_THAN_OR_EQUAL = "greater_than_or_equal"
    IN_LIST = "in_list"
    NOT_IN_LIST = "not_in_list"
    LIKE = "like"
    ILIKE = "ilike"
    STARTS_WITH = "starts_with"
    ENDS_WITH = "ends_with"
    CONTAINS = "contains"
    IS_NULL = "is_null"
    IS_NOT_NULL = "is_not_null"

options: show_root_heading: true show_source: true

Email Types

Type definitions for email-related operations.

archipy.models.types.email_types.EmailAttachmentType

Bases: StrEnum

Enum representing different types of email attachments.

This enum defines the types of attachments that can be included in an email, such as files, base64-encoded data, URLs, or binary data.

Attributes:

Name Type Description
FILE str

Represents a file attachment.

BASE64 str

Represents a base64-encoded attachment.

URL str

Represents an attachment referenced by a URL.

BINARY str

Represents raw binary data as an attachment.

Source code in archipy/models/types/email_types.py
class EmailAttachmentType(StrEnum):
    """Enum representing different types of email attachments.

    This enum defines the types of attachments that can be included in an email,
    such as files, base64-encoded data, URLs, or binary data.

    Attributes:
        FILE (str): Represents a file attachment.
        BASE64 (str): Represents a base64-encoded attachment.
        URL (str): Represents an attachment referenced by a URL.
        BINARY (str): Represents raw binary data as an attachment.
    """

    FILE = "file"
    BASE64 = "base64"
    URL = "url"
    BINARY = "binary"

archipy.models.types.email_types.EmailAttachmentDispositionType

Bases: StrEnum

Enum representing attachment disposition types.

This enum defines how an email attachment should be displayed or handled, such as being treated as a downloadable attachment or displayed inline.

Attributes:

Name Type Description
ATTACHMENT str

Represents an attachment that should be downloaded.

INLINE str

Represents an attachment that should be displayed inline.

Source code in archipy/models/types/email_types.py
class EmailAttachmentDispositionType(StrEnum):
    """Enum representing attachment disposition types.

    This enum defines how an email attachment should be displayed or handled,
    such as being treated as a downloadable attachment or displayed inline.

    Attributes:
        ATTACHMENT (str): Represents an attachment that should be downloaded.
        INLINE (str): Represents an attachment that should be displayed inline.
    """

    ATTACHMENT = "attachment"
    INLINE = "inline"

options: show_root_heading: true show_source: true

Error Message Types

Standardized error message types for consistent error handling.

archipy.models.types.error_message_types.ErrorMessageType

Bases: Enum

Enumeration of exception types with associated error details.

This class defines a set of standard exception types, each with an associated error code, English and Farsi messages, and corresponding HTTP and gRPC status codes.

Attributes:

Name Type Description
UNAUTHENTICATED

Indicates that the user is not authenticated.

INVALID_PHONE

Indicates an invalid Iranian phone number.

INVALID_LANDLINE

Indicates an invalid Iranian landline number.

INVALID_NATIONAL_CODE

Indicates an invalid national code format.

TOKEN_EXPIRED

Indicates that the authentication token has expired.

INVALID_TOKEN

Indicates an invalid authentication token.

PERMISSION_DENIED

Indicates that the user does not have permission for the operation.

NOT_FOUND

Indicates that the requested resource was not found.

ALREADY_EXISTS

Indicates that the resource already exists.

INVALID_ARGUMENT

Indicates an invalid argument was provided.

OUT_OF_RANGE

Indicates that a value is out of the acceptable range.

DEADLINE_EXCEEDED

Indicates that the operation deadline was exceeded.

FAILED_PRECONDITION

Indicates that the operation preconditions were not met.

RESOURCE_EXHAUSTED

Indicates that the resource limit has been reached.

ABORTED

Indicates that the operation was aborted.

CANCELLED

Indicates that the operation was cancelled.

INVALID_ENTITY_TYPE

Indicates an invalid entity type.

INTERNAL_ERROR

Indicates an internal system error.

DATA_LOSS

Indicates critical data loss.

UNIMPLEMENTED

Indicates that the operation is not implemented.

DEPRECATION

Indicates that the operation is deprecated.

UNAVAILABLE

Indicates that the service is unavailable.

UNKNOWN_ERROR

Indicates an unknown error occurred.

DEADLOCK

Indicates a deadlock condition was detected.

Source code in archipy/models/types/error_message_types.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
class ErrorMessageType(Enum):
    """Enumeration of exception types with associated error details.

    This class defines a set of standard exception types, each with an associated error code,
    English and Farsi messages, and corresponding HTTP and gRPC status codes.

    Attributes:
        UNAUTHENTICATED: Indicates that the user is not authenticated.
        INVALID_PHONE: Indicates an invalid Iranian phone number.
        INVALID_LANDLINE: Indicates an invalid Iranian landline number.
        INVALID_NATIONAL_CODE: Indicates an invalid national code format.
        TOKEN_EXPIRED: Indicates that the authentication token has expired.
        INVALID_TOKEN: Indicates an invalid authentication token.
        PERMISSION_DENIED: Indicates that the user does not have permission for the operation.
        NOT_FOUND: Indicates that the requested resource was not found.
        ALREADY_EXISTS: Indicates that the resource already exists.
        INVALID_ARGUMENT: Indicates an invalid argument was provided.
        OUT_OF_RANGE: Indicates that a value is out of the acceptable range.
        DEADLINE_EXCEEDED: Indicates that the operation deadline was exceeded.
        FAILED_PRECONDITION: Indicates that the operation preconditions were not met.
        RESOURCE_EXHAUSTED: Indicates that the resource limit has been reached.
        ABORTED: Indicates that the operation was aborted.
        CANCELLED: Indicates that the operation was cancelled.
        INVALID_ENTITY_TYPE: Indicates an invalid entity type.
        INTERNAL_ERROR: Indicates an internal system error.
        DATA_LOSS: Indicates critical data loss.
        UNIMPLEMENTED: Indicates that the operation is not implemented.
        DEPRECATION: Indicates that the operation is deprecated.
        UNAVAILABLE: Indicates that the service is unavailable.
        UNKNOWN_ERROR: Indicates an unknown error occurred.
        DEADLOCK: Indicates a deadlock condition was detected.
    """

    # Authentication Errors (400, 401, 403)
    UNAUTHENTICATED = ErrorDetailDTO.create_error_detail(
        code="UNAUTHENTICATED",
        message_en="You are not authorized to perform this action.",
        message_fa="شما مجوز انجام این عمل را ندارید.",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )
    INVALID_PHONE = ErrorDetailDTO.create_error_detail(
        code="INVALID_PHONE",
        message_en="Invalid Iranian phone number",
        message_fa="شماره تلفن همراه ایران نامعتبر است.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_LANDLINE = ErrorDetailDTO.create_error_detail(
        code="INVALID_LANDLINE",
        message_en="Invalid Iranian landline number",
        message_fa="شماره تلفن ثابت ایران نامعتبر است.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_NATIONAL_CODE = ErrorDetailDTO.create_error_detail(
        code="INVALID_NATIONAL_CODE",
        message_en="Invalid national code format",
        message_fa="فرمت کد ملی وارد شده اشتباه است.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    TOKEN_EXPIRED = ErrorDetailDTO.create_error_detail(
        code="TOKEN_EXPIRED",
        message_en="Authentication token has expired",
        message_fa="توکن احراز هویت منقضی شده است.",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    INVALID_TOKEN = ErrorDetailDTO.create_error_detail(
        code="INVALID_TOKEN",
        message_en="Invalid authentication token",
        message_fa="توکن احراز هویت نامعتبر است.",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    PERMISSION_DENIED = ErrorDetailDTO.create_error_detail(
        code="PERMISSION_DENIED",
        message_en="Permission denied for this operation",
        message_fa="دسترسی برای انجام این عملیات وجود ندارد.",
        http_status=HTTPStatus.FORBIDDEN if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.PERMISSION_DENIED if GRPC_AVAILABLE else None,
    )

    # Resource Errors (404, 409)
    NOT_FOUND = ErrorDetailDTO.create_error_detail(
        code="NOT_FOUND",
        message_en="Requested resource not found",
        message_fa="منبع درخواستی یافت نشد.",
        http_status=HTTPStatus.NOT_FOUND if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.NOT_FOUND if GRPC_AVAILABLE else None,
    )

    ALREADY_EXISTS = ErrorDetailDTO.create_error_detail(
        code="ALREADY_EXISTS",
        message_en="Resource already exists",
        message_fa="منبع از قبل موجود است.",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ALREADY_EXISTS if GRPC_AVAILABLE else None,
    )

    # Validation Errors (400)
    INVALID_ARGUMENT = ErrorDetailDTO.create_error_detail(
        code="INVALID_ARGUMENT",
        message_en="Invalid argument provided",
        message_fa="پارامتر ورودی نامعتبر است.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_PASSWORD = ErrorDetailDTO.create_error_detail(
        code="INVALID_PASSWORD",
        message_en="Password does not meet the security requirements",
        message_fa="رمز عبور الزامات امنیتی را برآورده نمی‌کند.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    OUT_OF_RANGE = ErrorDetailDTO.create_error_detail(
        code="OUT_OF_RANGE",
        message_en="Value is out of acceptable range",
        message_fa="مقدار خارج از محدوده مجاز است.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.OUT_OF_RANGE if GRPC_AVAILABLE else None,
    )

    # Operation Errors (408, 409, 412, 429)
    DEADLINE_EXCEEDED = ErrorDetailDTO.create_error_detail(
        code="DEADLINE_EXCEEDED",
        message_en="Operation deadline exceeded",
        message_fa="مهلت انجام عملیات به پایان رسیده است.",
        http_status=HTTPStatus.REQUEST_TIMEOUT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DEADLINE_EXCEEDED if GRPC_AVAILABLE else None,
    )

    FAILED_PRECONDITION = ErrorDetailDTO.create_error_detail(
        code="FAILED_PRECONDITION",
        message_en="Operation preconditions not met",
        message_fa="پیش‌نیازهای عملیات برآورده نشده است.",
        http_status=HTTPStatus.PRECONDITION_FAILED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    RESOURCE_EXHAUSTED = ErrorDetailDTO.create_error_detail(
        code="RESOURCE_EXHAUSTED",
        message_en="Resource limit has been reached",
        message_fa="محدودیت منابع به پایان رسیده است.",
        http_status=HTTPStatus.TOO_MANY_REQUESTS if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.RESOURCE_EXHAUSTED if GRPC_AVAILABLE else None,
    )

    ABORTED = ErrorDetailDTO.create_error_detail(
        code="ABORTED",
        message_en="Operation was aborted",
        message_fa="عملیات متوقف شد.",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ABORTED if GRPC_AVAILABLE else None,
    )

    CANCELLED = ErrorDetailDTO.create_error_detail(
        code="CANCELLED",
        message_en="Operation was cancelled",
        message_fa="عملیات لغو شد.",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.CANCELLED if GRPC_AVAILABLE else None,
    )

    INSUFFICIENT_BALANCE = ErrorDetailDTO.create_error_detail(
        code="INSUFFICIENT_BALANCE",
        message_en="Insufficient balance for operation",
        message_fa="عدم موجودی کافی برای عملیات.",
        http_status=HTTPStatus.PAYMENT_REQUIRED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    # System Errors (500, 501, 503)
    INVALID_ENTITY_TYPE = ErrorDetailDTO.create_error_detail(
        code="INVALID_ENTITY",
        message_en="Invalid entity type",
        message_fa="نوع موجودیت نامعتبر است.",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )
    INTERNAL_ERROR = ErrorDetailDTO.create_error_detail(
        code="INTERNAL_ERROR",
        message_en="Internal system error occurred",
        message_fa="خطای داخلی سیستم رخ داده است.",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    DATA_LOSS = ErrorDetailDTO.create_error_detail(
        code="DATA_LOSS",
        message_en="Critical data loss detected",
        message_fa="از دست دادن اطلاعات حیاتی تشخیص داده شد.",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DATA_LOSS if GRPC_AVAILABLE else None,
    )

    UNIMPLEMENTED = ErrorDetailDTO.create_error_detail(
        code="UNIMPLEMENTED",
        message_en="Requested operation is not implemented",
        message_fa="عملیات درخواستی پیاده‌سازی نشده است.",
        http_status=HTTPStatus.NOT_IMPLEMENTED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNIMPLEMENTED if GRPC_AVAILABLE else None,
    )

    DEPRECATION = ErrorDetailDTO.create_error_detail(
        code="DEPRECATION",
        message_en="This operation is deprecated and will be removed in a future version.",
        message_fa="این عملیات منسوخ شده و در نسخه‌های آینده حذف خواهد شد.",
        http_status=HTTPStatus.GONE if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    UNAVAILABLE = ErrorDetailDTO.create_error_detail(
        code="UNAVAILABLE",
        message_en="Service is currently unavailable",
        message_fa="سرویس در حال حاضر در دسترس نیست.",
        http_status=HTTPStatus.SERVICE_UNAVAILABLE if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    UNKNOWN_ERROR = ErrorDetailDTO.create_error_detail(
        code="UNKNOWN_ERROR",
        message_en="An unknown error occurred",
        message_fa="خطای ناشناخته‌ای رخ داده است.",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNKNOWN if GRPC_AVAILABLE else None,
    )

    DEADLOCK = ErrorDetailDTO.create_error_detail(
        code="DEADLOCK",
        message_en="Deadlock detected",
        message_fa="خطای قفل‌شدگی (Deadlock) تشخیص داده شد.",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    # Authentication & Authorization
    INVALID_CREDENTIALS = ErrorDetailDTO.create_error_detail(
        code="INVALID_CREDENTIALS",
        message_en="Invalid username or password",
        message_fa="نام کاربری یا رمز عبور نامعتبر است",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    ACCOUNT_LOCKED = ErrorDetailDTO.create_error_detail(
        code="ACCOUNT_LOCKED",
        message_en="Account has been locked due to too many failed attempts",
        message_fa="حساب کاربری به دلیل تلاش‌های ناموفق متعدد قفل شده است",
        http_status=HTTPStatus.FORBIDDEN if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.PERMISSION_DENIED if GRPC_AVAILABLE else None,
    )

    ACCOUNT_DISABLED = ErrorDetailDTO.create_error_detail(
        code="ACCOUNT_DISABLED",
        message_en="Account has been disabled",
        message_fa="حساب کاربری غیرفعال شده است",
        http_status=HTTPStatus.FORBIDDEN if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.PERMISSION_DENIED if GRPC_AVAILABLE else None,
    )

    SESSION_EXPIRED = ErrorDetailDTO.create_error_detail(
        code="SESSION_EXPIRED",
        message_en="Session has expired",
        message_fa="نشست کاربری منقضی شده است",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    INVALID_REFRESH_TOKEN = ErrorDetailDTO.create_error_detail(
        code="INVALID_REFRESH_TOKEN",
        message_en="Invalid refresh token",
        message_fa="توکن تازه‌سازی نامعتبر است",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    INVALID_VERIFICATION_CODE = ErrorDetailDTO.create_error_detail(
        code="INVALID_VERIFICATION_CODE",
        message_en="Invalid verification code",
        message_fa="کد تایید نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    # Resource & Data
    CONFLICT = ErrorDetailDTO.create_error_detail(
        code="CONFLICT",
        message_en="Resource conflict detected",
        message_fa="تعارض در منابع تشخیص داده شد",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ABORTED if GRPC_AVAILABLE else None,
    )

    INVALID_FORMAT = ErrorDetailDTO.create_error_detail(
        code="INVALID_FORMAT",
        message_en="Invalid data format",
        message_fa="فرمت داده نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    FILE_TOO_LARGE = ErrorDetailDTO.create_error_detail(
        code="FILE_TOO_LARGE",
        message_en="File size exceeds the maximum allowed limit",
        message_fa="حجم فایل از حد مجاز بیشتر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_FILE_TYPE = ErrorDetailDTO.create_error_detail(
        code="INVALID_FILE_TYPE",
        message_en="File type is not supported",
        message_fa="نوع فایل پشتیبانی نمی‌شود",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    QUOTA_EXCEEDED = ErrorDetailDTO.create_error_detail(
        code="QUOTA_EXCEEDED",
        message_en="Storage quota has been exceeded",
        message_fa="سهمیه ذخیره‌سازی به پایان رسیده است",
        http_status=HTTPStatus.FORBIDDEN if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.RESOURCE_EXHAUSTED if GRPC_AVAILABLE else None,
    )

    RATE_LIMIT_EXCEEDED = ErrorDetailDTO.create_error_detail(
        code="RATE_LIMIT_EXCEEDED",
        message_en="Rate limit has been exceeded",
        message_fa="محدودیت نرخ درخواست به پایان رسیده است",
        http_status=HTTPStatus.TOO_MANY_REQUESTS if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.RESOURCE_EXHAUSTED if GRPC_AVAILABLE else None,
    )

    # Network & Communication
    CONNECTION_TIMEOUT = ErrorDetailDTO.create_error_detail(
        code="CONNECTION_TIMEOUT",
        message_en="Connection timed out",
        message_fa="اتصال با تایم‌اوت مواجه شد",
        http_status=HTTPStatus.REQUEST_TIMEOUT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DEADLINE_EXCEEDED if GRPC_AVAILABLE else None,
    )

    NETWORK_ERROR = ErrorDetailDTO.create_error_detail(
        code="NETWORK_ERROR",
        message_en="Network error occurred",
        message_fa="خطای شبکه رخ داده است",
        http_status=HTTPStatus.BAD_GATEWAY if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    SERVICE_UNAVAILABLE = ErrorDetailDTO.create_error_detail(
        code="SERVICE_UNAVAILABLE",
        message_en="Service is currently unavailable",
        message_fa="سرویس در حال حاضر در دسترس نیست",
        http_status=HTTPStatus.SERVICE_UNAVAILABLE if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    GATEWAY_TIMEOUT = ErrorDetailDTO.create_error_detail(
        code="GATEWAY_TIMEOUT",
        message_en="Gateway timeout",
        message_fa="تایم‌اوت دروازه",
        http_status=HTTPStatus.GATEWAY_TIMEOUT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DEADLINE_EXCEEDED if GRPC_AVAILABLE else None,
    )

    BAD_GATEWAY = ErrorDetailDTO.create_error_detail(
        code="BAD_GATEWAY",
        message_en="Bad gateway",
        message_fa="دروازه نامعتبر",
        http_status=HTTPStatus.BAD_GATEWAY if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    # Business Logic
    INVALID_STATE = ErrorDetailDTO.create_error_detail(
        code="INVALID_STATE",
        message_en="Invalid state for the requested operation",
        message_fa="وضعیت نامعتبر برای عملیات درخواستی",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    BUSINESS_RULE_VIOLATION = ErrorDetailDTO.create_error_detail(
        code="BUSINESS_RULE_VIOLATION",
        message_en="Business rule violation",
        message_fa="نقض قوانین کسب و کار",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    INSUFFICIENT_FUNDS = ErrorDetailDTO.create_error_detail(
        code="INSUFFICIENT_FUNDS",
        message_en="Insufficient funds for the operation",
        message_fa="موجودی ناکافی برای عملیات",
        http_status=HTTPStatus.PAYMENT_REQUIRED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    INVALID_OPERATION = ErrorDetailDTO.create_error_detail(
        code="INVALID_OPERATION",
        message_en="Operation is not allowed in the current context",
        message_fa="عملیات در وضعیت فعلی مجاز نیست",
        http_status=HTTPStatus.FORBIDDEN if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.PERMISSION_DENIED if GRPC_AVAILABLE else None,
    )

    MAINTENANCE_MODE = ErrorDetailDTO.create_error_detail(
        code="MAINTENANCE_MODE",
        message_en="System is currently in maintenance mode",
        message_fa="سیستم در حال حاضر در حالت تعمیر و نگهداری است",
        http_status=HTTPStatus.SERVICE_UNAVAILABLE if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    # Validation
    INVALID_EMAIL = ErrorDetailDTO.create_error_detail(
        code="INVALID_EMAIL",
        message_en="Invalid email format",
        message_fa="فرمت ایمیل نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_DATE = ErrorDetailDTO.create_error_detail(
        code="INVALID_DATE",
        message_en="Invalid date format",
        message_fa="فرمت تاریخ نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_URL = ErrorDetailDTO.create_error_detail(
        code="INVALID_URL",
        message_en="Invalid URL format",
        message_fa="فرمت URL نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_IP = ErrorDetailDTO.create_error_detail(
        code="INVALID_IP",
        message_en="Invalid IP address format",
        message_fa="فرمت آدرس IP نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    INVALID_JSON = ErrorDetailDTO.create_error_detail(
        code="INVALID_JSON",
        message_en="Invalid JSON format",
        message_fa="فرمت JSON نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    # Database & Storage Errors
    DATABASE_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_ERROR",
        message_en="Database error occurred",
        message_fa="خطای پایگاه داده رخ داده است",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    DATABASE_CONNECTION_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_CONNECTION_ERROR",
        message_en="Failed to connect to the database",
        message_fa="خطا در اتصال به پایگاه داده",
        http_status=HTTPStatus.SERVICE_UNAVAILABLE if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    DATABASE_QUERY_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_QUERY_ERROR",
        message_en="Error executing database query",
        message_fa="خطا در اجرای پرس و جوی پایگاه داده",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    DATABASE_TRANSACTION_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_TRANSACTION_ERROR",
        message_en="Error in database transaction",
        message_fa="خطا در تراکنش پایگاه داده",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    DATABASE_TIMEOUT_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_TIMEOUT_ERROR",
        message_en="Database operation timed out",
        message_fa="عملیات پایگاه داده با تایم‌اوت مواجه شد",
        http_status=HTTPStatus.REQUEST_TIMEOUT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DEADLINE_EXCEEDED if GRPC_AVAILABLE else None,
    )

    DATABASE_CONSTRAINT_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_CONSTRAINT_ERROR",
        message_en="Database constraint violation",
        message_fa="نقض محدودیت پایگاه داده",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    DATABASE_INTEGRITY_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_INTEGRITY_ERROR",
        message_en="Database integrity violation",
        message_fa="نقض یکپارچگی پایگاه داده",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    DATABASE_DEADLOCK_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_DEADLOCK_ERROR",
        message_en="Database deadlock detected",
        message_fa="قفل‌شدگی پایگاه داده تشخیص داده شد",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ABORTED if GRPC_AVAILABLE else None,
    )

    DATABASE_SERIALIZATION_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_SERIALIZATION_ERROR",
        message_en="Database serialization failure",
        message_fa="خطای سریال‌سازی پایگاه داده",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ABORTED if GRPC_AVAILABLE else None,
    )

    DATABASE_CONFIGURATION_ERROR = ErrorDetailDTO.create_error_detail(
        code="DATABASE_CONFIGURATION_ERROR",
        message_en="Database configuration error",
        message_fa="خطای پیکربندی پایگاه داده",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    STORAGE_ERROR = ErrorDetailDTO.create_error_detail(
        code="STORAGE_ERROR",
        message_en="Storage access error occurred",
        message_fa="خطا در دسترسی به فضای ذخیره‌سازی",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    # Cache Errors
    CACHE_ERROR = ErrorDetailDTO.create_error_detail(
        code="CACHE_ERROR",
        message_en="Error accessing cache",
        message_fa="خطا در دسترسی به حافظه نهان",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    CACHE_MISS = ErrorDetailDTO.create_error_detail(
        code="CACHE_MISS",
        message_en="Requested data not found in cache",
        message_fa="داده درخواستی در حافظه نهان یافت نشد",
        http_status=HTTPStatus.NOT_FOUND if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.NOT_FOUND if GRPC_AVAILABLE else None,
    )

    # Message Queue Errors
    QUEUE_ERROR = ErrorDetailDTO.create_error_detail(
        code="QUEUE_ERROR",
        message_en="Error in message queue operation",
        message_fa="خطا در عملیات صف پیام",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    QUEUE_FULL = ErrorDetailDTO.create_error_detail(
        code="QUEUE_FULL",
        message_en="Message queue is full",
        message_fa="صف پیام پر است",
        http_status=HTTPStatus.SERVICE_UNAVAILABLE if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.RESOURCE_EXHAUSTED if GRPC_AVAILABLE else None,
    )

    # Search Engine Errors
    SEARCH_ERROR = ErrorDetailDTO.create_error_detail(
        code="SEARCH_ERROR",
        message_en="Error performing search operation",
        message_fa="خطا در انجام عملیات جستجو",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    SEARCH_TIMEOUT = ErrorDetailDTO.create_error_detail(
        code="SEARCH_TIMEOUT",
        message_en="Search operation timed out",
        message_fa="عملیات جستجو با تایم‌اوت مواجه شد",
        http_status=HTTPStatus.REQUEST_TIMEOUT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DEADLINE_EXCEEDED if GRPC_AVAILABLE else None,
    )

    # External Service Errors
    EXTERNAL_SERVICE_ERROR = ErrorDetailDTO.create_error_detail(
        code="EXTERNAL_SERVICE_ERROR",
        message_en="Error in external service",
        message_fa="خطا در سرویس خارجی",
        http_status=HTTPStatus.BAD_GATEWAY if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAVAILABLE if GRPC_AVAILABLE else None,
    )

    EXTERNAL_SERVICE_TIMEOUT = ErrorDetailDTO.create_error_detail(
        code="EXTERNAL_SERVICE_TIMEOUT",
        message_en="External service request timed out",
        message_fa="درخواست به سرویس خارجی با تایم‌اوت مواجه شد",
        http_status=HTTPStatus.GATEWAY_TIMEOUT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.DEADLINE_EXCEEDED if GRPC_AVAILABLE else None,
    )

    # Security Errors
    SECURITY_ERROR = ErrorDetailDTO.create_error_detail(
        code="SECURITY_ERROR",
        message_en="Security violation detected",
        message_fa="نقض امنیتی تشخیص داده شد",
        http_status=HTTPStatus.FORBIDDEN if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.PERMISSION_DENIED if GRPC_AVAILABLE else None,
    )

    INVALID_SIGNATURE = ErrorDetailDTO.create_error_detail(
        code="INVALID_SIGNATURE",
        message_en="Invalid digital signature",
        message_fa="امضای دیجیتال نامعتبر است",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    INVALID_CERTIFICATE = ErrorDetailDTO.create_error_detail(
        code="INVALID_CERTIFICATE",
        message_en="Invalid security certificate",
        message_fa="گواهی امنیتی نامعتبر است",
        http_status=HTTPStatus.UNAUTHORIZED if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.UNAUTHENTICATED if GRPC_AVAILABLE else None,
    )

    # Configuration Errors
    CONFIGURATION_ERROR = ErrorDetailDTO.create_error_detail(
        code="CONFIGURATION_ERROR",
        message_en="Error in system configuration",
        message_fa="خطا در پیکربندی سیستم",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    MISSING_CONFIGURATION = ErrorDetailDTO.create_error_detail(
        code="MISSING_CONFIGURATION",
        message_en="Required configuration is missing",
        message_fa="پیکربندی مورد نیاز وجود ندارد",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    # Integration Errors
    INTEGRATION_ERROR = ErrorDetailDTO.create_error_detail(
        code="INTEGRATION_ERROR",
        message_en="Error in system integration",
        message_fa="خطا در یکپارچه‌سازی سیستم",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    INCOMPATIBLE_VERSION = ErrorDetailDTO.create_error_detail(
        code="INCOMPATIBLE_VERSION",
        message_en="Incompatible system version",
        message_fa="نسخه سیستم ناسازگار است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.FAILED_PRECONDITION if GRPC_AVAILABLE else None,
    )

    # Monitoring & Logging Errors
    MONITORING_ERROR = ErrorDetailDTO.create_error_detail(
        code="MONITORING_ERROR",
        message_en="Error in monitoring system",
        message_fa="خطا در سیستم نظارت",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    LOGGING_ERROR = ErrorDetailDTO.create_error_detail(
        code="LOGGING_ERROR",
        message_en="Error in logging system",
        message_fa="خطا در سیستم ثبت رویدادها",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    # Backup & Recovery Errors
    BACKUP_ERROR = ErrorDetailDTO.create_error_detail(
        code="BACKUP_ERROR",
        message_en="Error in backup operation",
        message_fa="خطا در عملیات پشتیبان‌گیری",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    RECOVERY_ERROR = ErrorDetailDTO.create_error_detail(
        code="RECOVERY_ERROR",
        message_en="Error in recovery operation",
        message_fa="خطا در عملیات بازیابی",
        http_status=HTTPStatus.INTERNAL_SERVER_ERROR if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INTERNAL if GRPC_AVAILABLE else None,
    )

    # Resource Management Errors
    RESOURCE_LOCKED = ErrorDetailDTO.create_error_detail(
        code="RESOURCE_LOCKED",
        message_en="Resource is currently locked",
        message_fa="منبع در حال حاضر قفل شده است",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ABORTED if GRPC_AVAILABLE else None,
    )

    RESOURCE_BUSY = ErrorDetailDTO.create_error_detail(
        code="RESOURCE_BUSY",
        message_en="Resource is currently busy",
        message_fa="منبع در حال حاضر مشغول است",
        http_status=HTTPStatus.CONFLICT if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.ABORTED if GRPC_AVAILABLE else None,
    )

    # Time-related Errors
    INVALID_TIMESTAMP = ErrorDetailDTO.create_error_detail(
        code="INVALID_TIMESTAMP",
        message_en="Invalid timestamp format",
        message_fa="فرمت زمان نامعتبر است",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

    TIMEZONE_ERROR = ErrorDetailDTO.create_error_detail(
        code="TIMEZONE_ERROR",
        message_en="Error in timezone conversion",
        message_fa="خطا در تبدیل منطقه زمانی",
        http_status=HTTPStatus.BAD_REQUEST if HTTP_AVAILABLE else None,
        grpc_status=StatusCode.INVALID_ARGUMENT if GRPC_AVAILABLE else None,
    )

options: show_root_heading: true show_source: true

Language Type

Language code type definition.

archipy.models.types.language_type.LanguageType

Bases: str, Enum

Enum representing supported languages for error messages.

This enum defines the languages that are supported for generating or displaying error messages. Each language is represented by its ISO 639-1 code.

Attributes:

Name Type Description
FA str

Represents the Persian language (ISO 639-1 code: 'fa').

EN str

Represents the English language (ISO 639-1 code: 'en').

Source code in archipy/models/types/language_type.py
class LanguageType(str, Enum):
    """Enum representing supported languages for error messages.

    This enum defines the languages that are supported for generating or displaying
    error messages. Each language is represented by its ISO 639-1 code.

    Attributes:
        FA (str): Represents the Persian language (ISO 639-1 code: 'fa').
        EN (str): Represents the English language (ISO 639-1 code: 'en').
    """

    FA = "fa"  # Persian
    EN = "en"  # English

options: show_root_heading: true show_source: true

Sort Order Type

Sort order type definition for queries.

archipy.models.types.sort_order_type.SortOrderType

Bases: Enum

Enumeration of sorting order types.

This enum defines the types of sorting orders that can be applied to data, such as ascending or descending.

Attributes:

Name Type Description
ASCENDING str

Represents sorting in ascending order.

DESCENDING str

Represents sorting in descending order.

Source code in archipy/models/types/sort_order_type.py
class SortOrderType(Enum):
    """Enumeration of sorting order types.

    This enum defines the types of sorting orders that can be applied to data,
    such as ascending or descending.

    Attributes:
        ASCENDING (str): Represents sorting in ascending order.
        DESCENDING (str): Represents sorting in descending order.
    """

    ASCENDING = "ascending"
    DESCENDING = "descending"

options: show_root_heading: true show_source: true

Key Classes

BaseDTO

Class: archipy.models.dtos.base_dtos.BaseDTO

Base class for all DTOs with features:

  • Pydantic model inheritance
  • JSON serialization
  • Validation
  • Type hints
  • Common utility methods

BaseEntity

Class: archipy.models.entities.sqlalchemy.base_entities.BaseEntity

Base class for SQLAlchemy entities with features:

  • UUID primary key
  • Timestamp fields (created_at, updated_at)
  • Common query methods
  • Relationship support
  • Type-safe column definitions
  • Mixin support for:
    • Update tracking
    • Soft deletion
    • Admin tracking
    • Manager tracking
    • Archiving
    • Combined capabilities

BaseError

Class: archipy.models.errors.BaseError

Base class for custom errors with features:

  • Standardized error format
  • Error code system
  • Detailed error messages
  • Stack trace support
  • Error context
  • Additional data support
  • Language localization
  • HTTP and gRPC status code mapping