from onegov.core.orm import Base, observes
from onegov.core.orm.mixins import ContentMixin, TimestampMixin
from onegov.core.orm.types import UUID
from onegov.core.utils import normalize_for_url
from sqlalchemy import Column, Enum, Text
from uuid import uuid4
from typing import Literal, TYPE_CHECKING
if TYPE_CHECKING:
import uuid
from typing import TypeAlias
[docs]
Medium: TypeAlias = Literal['phone', 'email', 'http']
[docs]
class GenericRecipient(Base, ContentMixin, TimestampMixin):
""" A generic recipient class with polymorphic support. """
[docs]
__tablename__ = 'generic_recipients'
#: the internal id of the recipient
[docs]
id: 'Column[uuid.UUID]' = Column(
UUID, # type:ignore[arg-type]
primary_key=True,
default=uuid4
)
#: the recipient name
[docs]
name: 'Column[str]' = Column(Text, nullable=False)
#: the order of the records (set to the normalized name + medium)
[docs]
order: 'Column[str]' = Column(Text, nullable=False, index=True)
#: the medium over which notifications are sent
[docs]
medium: 'Column[Medium]' = Column(Enum( # type:ignore[arg-type]
'phone',
'email',
'http',
name='recipient_medium'
), nullable=False)
#: the phone number, e-mail, url, etc. of the recipient (matches medium)
[docs]
address: 'Column[str]' = Column(Text, nullable=False)
#: extra information associated with the address (say POST/GET for http)
#: the polymorphic recipient type
[docs]
type: 'Column[str]' = Column(
Text,
nullable=False,
default=lambda: 'generic'
)
[docs]
__mapper_args__ = {
'polymorphic_on': 'type',
'polymorphic_identity': 'generic'
}
@observes('name')
[docs]
def name_observer(self, name: str) -> None:
self.order = normalize_for_url(name)