Source code for reservation.models.resource

import datetime
import secrets

from decimal import Decimal
from dataclasses import replace
from functools import lru_cache
from libres import new_scheduler
from libres.db.models.base import ORMBase
from onegov.core.orm import ModelBase
from onegov.core.orm.mixins import (
    content_property, dict_property, meta_property)
from onegov.core.orm.mixins import ContentMixin, TimestampMixin
from onegov.file import MultiAssociatedFiles
from onegov.form.parser import ParsedForm
from onegov.form.orm_types import Formcode
from onegov.pay import InvoiceItemMeta, Price, process_payment
from onegov.reservation.observer import observes
from onegov.reservation.pricing_scheme import PRICING_SCHEMES
from sedate import align_date_to_day, utcnow
from sqlalchemy import column, func, literal_column
from sqlalchemy import CheckConstraint, Column, ForeignKey, Index, Table
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import mapped_column, relationship, Mapped
from uuid import uuid4, uuid5, UUID


from typing import Any, Literal, TYPE_CHECKING
if TYPE_CHECKING:
    # type gets shadowed by type in model
    from builtins import type as type_t
    from collections.abc import Collection, Sequence
    from libres.context.core import Context
    from libres.db.models import Allocation
    from libres.db.scheduler import Scheduler
    from onegov.form import Form
    from onegov.reservation.models import CustomReservation
    from onegov.pay import (
        InvoiceDiscountMeta, Payment, PaymentError, PaymentProvider)
    from onegov.pay.types import PaymentMethod
    from sqlalchemy.orm import Session
    from sqlalchemy.sql import ColumnElement

[docs] type DeadlineUnit = Literal['d', 'h']
# HACK: We pass a UUID as a name and have a custom uuid_generator # which directly uses it, so in order to get the correct # type checking on Scheduler.name, we have to pretend we # created a subclass class _OurScheduler(Scheduler): name: UUID # type:ignore[assignment] blocking_names: Collection[UUID] # type:ignore[assignment] @lru_cache(maxsize=1)
[docs] def extra_scheduler_arguments() -> dict[str, Any]: from onegov.reservation.models import CustomReservation from onegov.reservation.models import CustomAllocation return { 'allocation_cls': CustomAllocation, 'reservation_cls': CustomReservation }
[docs] blocking_resources_table = Table( 'blocking_resources', ORMBase.metadata, Column( 'parent_id', ForeignKey('resources.id', ondelete='CASCADE'), primary_key=True, ), Column( 'child_id', ForeignKey('resources.id', ondelete='CASCADE'), primary_key=True, ), Index( 'uq_ensure_no_diamond_cycles', func.greatest(column('parent_id'), column('child_id')), func.least(column('parent_id'), column('child_id')), unique=True ), CheckConstraint( 'parent_id != child_id', name='ck_no_self_reference' ) )
[docs] class Resource(ORMBase, ModelBase, ContentMixin, TimestampMixin, MultiAssociatedFiles): """ A resource holds a single calendar with allocations and reservations. Note that this resource is not defined on the onegov.core declarative base. Instead it is defined using the libres base. This means we can't join data outside the libres models. This should however not be a problem as this onegov module is self contained and does not link to other onegov modules, except for core. If we ever want to link to other models (say link a reservation to a user), then we have to switch to a unified base. Ideally we would find a way to merge these bases somehow. Also note that we *do* use the ModelBase class as a mixin to at least share the same methods as all the usual onegov.core.orm models. """
[docs] __tablename__ = 'resources'
#: the unique id
[docs] id: Mapped[UUID] = mapped_column( primary_key=True, default=uuid4 )
#: a nice id for the url, readable by humans # FIXME: This probably should've been nullable=False
[docs] name: Mapped[str | None] = mapped_column(unique=True)
#: the title of the resource
[docs] title: Mapped[str]
#: the timezone this resource resides in
[docs] timezone: Mapped[str]
#: the pre-parsed custom form used when creating a reservation
[docs] parsed: Mapped[ParsedForm | None] = mapped_column(Formcode)
#: the group to which this resource belongs to (may be any kind of string)
[docs] group: Mapped[str | None]
#: the subgroup to which this resource belongs to
[docs] subgroup: Mapped[str | None]
#: the type of the resource, this can be used to create custom polymorphic #: subclasses. See `<https://docs.sqlalchemy.org/en/improve_toc/ #: orm/extensions/declarative/inheritance.html>`_.
[docs] type: Mapped[str] = mapped_column(default=lambda: 'generic')
#: the payment method
[docs] payment_method: dict_property[PaymentMethod | None] = content_property()
#: the minimum price total the reservation must exceed
[docs] minimum_price_total: dict_property[float | None] = content_property()
#: the currency of the price to pay
[docs] currency: dict_property[str | None] = content_property()
#: the pricing method to use
[docs] pricing_method: dict_property[str | None] = content_property()
#: the reservations cost a given amount per hour
[docs] price_per_hour: dict_property[float | None] = content_property()
#: the reservations cost a given amount per unit (allocations * quota)
[docs] price_per_item: dict_property[float | None] = ( content_property('price_per_reservation') )
#: the custom resource pricing scheme to use
[docs] pricing_scheme: dict_property[str | None] = content_property()
#: the invoicing party for this resource
[docs] invoicing_party: dict_property[str | None] = content_property()
#: the cost center / cost unit identifier for this resource
[docs] cost_object: dict_property[str | None] = content_property()
#: extra field values to include in the occupancy view
[docs] occupancy_fields: dict_property[list[str]] = content_property(default=list)
#: extra field values to include in the ical event description
[docs] ical_fields: dict_property[list[str]] = content_property(default=list)
#: reservation deadline (e.g. None, (5, 'd'), (24, 'h'))
[docs] deadline: dict_property[tuple[int, DeadlineUnit] | None] = ( content_property() )
#: reservation lead time (in days)
[docs] lead_time: dict_property[int | None] = content_property()
#: enable reservation reminder emails
[docs] enable_reservation_reminders: dict_property[bool] = content_property( default=False )
#: the pricing method to use for extras defined in formcode
[docs] extras_pricing_method: dict_property[str] = ( content_property(default='per_item') )
#: the discount method to use
[docs] discount_method: dict_property[str] = content_property(default='resource')
#: the default view
[docs] default_view: dict_property[str | None] = content_property()
#: reservation zip code limit, contains None or something like this: #: { #: 'zipcode_field': 'PLZ', #: 'zipcode_list': [1234, 5678], #: 'zipcode_days': 3 #: } #: #: zipcode_field -> the field name in the definition containing zip codes #: zipcode_list -> zip codes exempt from the rule #: zipcode_days -> how many days before the reservation the rule is dropped #: #: Note, the zipcode_field name is in the human readable form. # FIXME: Define a TypedDict with all the zipcode_block elements
[docs] zipcode_block: dict_property[dict[str, Any] | None] = content_property()
#: secret token to get anonymous access to calendar data
[docs] access_token: dict_property[str | None] = content_property()
#: hint on how to get to the resource
[docs] pick_up: dict_property[str | None] = content_property()
#: whether users may submit a cancellation request for # accepted reservations
[docs] allow_cancellation_requests: dict_property[bool] = ( content_property(default=False) )
#: the reply_to address to supersede the global reply_to address for #: tickets created through this form
[docs] reply_to: dict_property[str | None] = meta_property()
[docs] __mapper_args__ = { 'polymorphic_on': 'type', 'polymorphic_identity': 'generic' }
[docs] __table_args__ = ( Index( 'ix_resources_virtual_id', func.uuid_generate_v5(id, literal_column("'virtual'")) ), )
# NOTE: These relationships only exist so deletion of resources cascade # and also deletes related allocations, since there is no foreign key # on the allocations table that could do that cascade for us # this also ensures we get an integrity error if we try to # delete a resource that still has reservations.
[docs] _allocations: Mapped[list[Allocation]] = relationship( cascade='all, delete-orphan', primaryjoin='Allocation.resource == Resource.id', foreign_keys='Allocation.resource', overlaps='_virtual_allocations', )
[docs] _virtual_allocations: Mapped[list[Allocation]] = relationship( cascade='all, delete-orphan', primaryjoin='Allocation.resource == Resource.virtual_id', foreign_keys='Allocation.resource', overlaps='_allocations', )
[docs] parents: Mapped[list[Resource]] = relationship( secondary=blocking_resources_table, primaryjoin=id == blocking_resources_table.c.child_id, secondaryjoin=id == blocking_resources_table.c.parent_id, back_populates='children', join_depth=1, passive_deletes=True )
[docs] children: Mapped[list[Resource]] = relationship( secondary=blocking_resources_table, primaryjoin=id == blocking_resources_table.c.parent_id, secondaryjoin=id == blocking_resources_table.c.child_id, back_populates='parents', join_depth=1, passive_deletes=True )
if TYPE_CHECKING: # NOTE: We don't want these to end up in __annotations__ # since they should not be mapped by SQLAlchemy
[docs] date: datetime.date | None
highlights_min: int | None highlights_max: int | None view: str | None #: the date to jump to in the view (if not None) -> not in the db! date = None #: a range of allocation ids to highlight in the view (if not None)
[docs] highlights_min = None
[docs] highlights_max = None
#: the view to open in the calendar (fullCalendar view name)
[docs] view = 'dayGridMonth'
@observes('parents')
[docs] def refresh_on_parents_updated(self, parents: list[Resource]) -> None: self.force_update()
@hybrid_property
[docs] def definition(self) -> str | None: """ The form as a parsable string """ return self.parsed.formcode if self.parsed is not None else None
@definition.inplace.setter def _definition_setter(self, value: str | None) -> None: if not value: self.parsed = None else: self.parsed = ParsedForm.from_formcode(value) @definition.inplace.expression @classmethod
[docs] def _definition_expression(cls) -> ColumnElement[str | None]: return cls.parsed['source_code'].astext
@deadline.inplace.setter def set_deadline(self, value: tuple[int, DeadlineUnit] | None) -> None: value = value or None if value: if len(value) != 2: raise ValueError('Deadline is not a tuple with two elements') if not isinstance(value[0], int): raise ValueError('Deadline value is not an int') if value[0] < 1: raise ValueError('Deadline value is smaller than 1') if value[1] not in ('d', 'h'): raise ValueError("Deadline unit must be 'd' or 'h'") self.content['deadline'] = value @staticmethod
[docs] def get_virtual_id(resource_id: UUID) -> UUID: assert resource_id.version != 5 return uuid5(resource_id, 'virtual')
@hybrid_property
[docs] def virtual_id(self) -> UUID: """ The resource's secondary virtual id. The virtual resource can be used as a second layer with its own allocations that can overlap allocations on the first layer while reservations on these two layers properly block one another. We generally use this to provide an internal unrestricted layer where partly-available full-day allocations get created on-demand to fit any reservations """ assert self.id, 'the id needs to be set' result = self.__dict__['virtual_id'] = self.get_virtual_id(self.id) return result
@virtual_id.inplace.expression @classmethod
[docs] def _virtual_id_expression(cls) -> ColumnElement[UUID]: return func.uuid_generate_v5(cls.id, literal_column("'virtual'"))
[docs] def highlight_allocations( self, allocations: Sequence[Allocation] ) -> None: """ The allocation to jump to in the view. """ # we can assume that allocation ids are created in a continuous # number line. It's not necessarily guaranteed, but since it *is* # only a highlighting feature we can check the highlights more # effiecently if we follow this assumption. highlights = [a.id for a in allocations] self.highlights_min = min(highlights) self.highlights_max = max(highlights) self.date = allocations[0].start.date()
[docs] def blocking_resource_ids( self, libres_context: Context | None = None ) -> set[UUID]: """ Returns a set of blocking resource ids. This excludes virtual resource ids, which will also act as blocking entities when creating reservations. """ assert self.id, 'the id needs to be set' if libres_context is None: assert hasattr( self, 'libres_context' ), 'not bound to libres context' libres_context = self.libres_context return libres_context.get_service('get_blocking_resource_ids')(self.id)
[docs] def blocking_resources(self) -> dict[UUID, Resource]: resource_ids = self.blocking_resource_ids() if not resource_ids: return {self.virtual_id: self} session: Session = self.libres_context.get_service( 'session_provider' ).session() blocking_resources = { resource.id: resource for resource in session.query(Resource).filter( Resource.id.in_(resource_ids) ) } for resource in tuple(blocking_resources.values()): resource.bind_to_libres_context(self.libres_context) # add a second mapping from the virtual id to the resource blocking_resources[resource.virtual_id] = resource blocking_resources[self.virtual_id] = self return blocking_resources
[docs] def get_scheduler( self, libres_context: Context, *, virtual: bool = False ) -> _OurScheduler: assert self.id, 'the id needs to be set' assert self.timezone, 'the timezone needs to be set' blocking_ids = { blocking_id for _blocking_id in self.blocking_resource_ids(libres_context) for blocking_id in ( _blocking_id, uuid5(_blocking_id, 'virtual') ) } if virtual: blocking_ids.add(self.id) else: blocking_ids.add(self.virtual_id) # HACK: we work around the name being a str in libres, but a # UUID in onegov return new_scheduler( # type:ignore[return-value] libres_context, self.virtual_id if virtual else self.id, # type:ignore[arg-type] self.timezone, blocking_names=blocking_ids, # type:ignore[arg-type] **extra_scheduler_arguments() )
@property
[docs] def scheduler(self) -> _OurScheduler: assert hasattr(self, 'libres_context'), 'not bound to libres context' return self.get_scheduler(self.libres_context)
@property
[docs] def virtual_scheduler(self) -> _OurScheduler: assert hasattr(self, 'libres_context'), 'not bound to libres context' return self.get_scheduler(self.libres_context, virtual=True)
[docs] def bind_to_libres_context(self, libres_context: Context) -> None: self.libres_context = libres_context
@property
[docs] def form_class(self) -> type_t[Form] | None: """ Parses the form definition and returns a form class. """ if self.parsed is None: return None return self.parsed.form_class()
[docs] def invoice_items_for_reservation( self, reservations: Sequence[CustomReservation], extras: Sequence[InvoiceItemMeta] | None = None, discounts: Sequence[InvoiceDiscountMeta] | None = None, submission_data: dict[str, Any] | None = None, *, # HACK: This isn't great, but similarly adding i18n to # the reservation module for a single translation # string is similarly not great. For now we'll # live with this, even if it's ugly. reduced_amount_label: str, ) -> list[InvoiceItemMeta]: if not reservations: return [] items: list[InvoiceItemMeta] = [] extras_quantity = Decimal('0') reservation_data = reservations[0].data or {} extras_pricing_method = reservation_data.get( 'extras_pricing_method', self.extras_pricing_method ) discount_method = reservation_data.get( 'discount_method', self.discount_method ) cost_object = reservation_data.get( 'cost_object', self.cost_object ) for reservation in reservations: # FIXME: We could speed this up by loading all of the # targeted allocations ahead of time and passing # the correct allocation here. Right now there's # a N+1 situation for loading target allocations. item = reservation.invoice_item( self, submission_data=submission_data ) if item is not None: items.append(item) if extras: match extras_pricing_method: case 'one_off': extras_quantity = Decimal('1') case 'per_hour': # FIXME: Should we assert here or instead use # reservation.timespans()? We assert in # CustomReservation.price(). if reservation.start and reservation.end: duration = reservation.end - reservation.start # compensate for the end being offset duration += datetime.timedelta(microseconds=1) else: duration = datetime.timedelta(seconds=0) extras_quantity += ( Decimal(duration.total_seconds()) / Decimal('3600') ) case 'per_item': extras_quantity += Decimal(reservation.quota) case _: # pragma: unreachable raise ValueError('unhandled extras pricing method') extras = [ replace(extra, quantity=extras_quantity) for extra in (extras or ()) ] total = InvoiceItemMeta.total(items) extras_total = InvoiceItemMeta.total(extras) match discount_method: case 'resource': discount_total = total case 'extras': discount_total = extras_total case 'everything': discount_total = total + extras_total case _: # pragma: unreachable raise ValueError('unhandled extras pricing method') if extras_total and total: total += extras_total elif extras_total: total = extras_total discount_items: list[InvoiceItemMeta] = [] if discounts: remainder = discount_total for discount in discounts: item = discount.apply_discount(discount_total, remainder) remainder += item.amount assert remainder >= Decimal('0') # update the total amount total += item.amount discount_items.append(item) items = items + discount_items + extras reservation = reservations[0] meta = (reservation.data or {}).get('ticket_tag_meta', {}) # HACK: This is not very robust, we should probably come up # with something better to handle price reductions for # specific tags try: reduced_amount = Decimal(meta.get('Price', meta.get('Preis'))) assert reduced_amount >= Decimal('0') except Exception: reduced_amount = None if reduced_amount is not None and reduced_amount < total: items.append(InvoiceItemMeta( text=reduced_amount_label, group='reduced_amount', cost_object=cost_object, unit=reduced_amount-total )) return items
[docs] def store_pricing_settings( self, data: dict[str, Any], allocation: Allocation | None ) -> None: """ Stores the resource/allocation specific pricing settings on the given reservation data, so pricing on that reservation remains stable, regardless of what changes later happen to the resource/allocation. """ allocation_data = allocation and allocation.data or {} pricing_method = allocation_data.get('pricing_method', 'inherit') if pricing_method == 'inherit': data['pricing_method'] = self.pricing_method data['price_per_hour'] = self.price_per_hour data['price_per_item'] = self.price_per_item data['pricing_scheme'] = pricing_scheme_name = self.pricing_scheme data['currency'] = self.currency if pricing_scheme_name and ( pricing_scheme := PRICING_SCHEMES.get(pricing_scheme_name) ) is not None: for name in pricing_scheme.content_names: data[name] = self.content.get(name) else: data['pricing_method'] = pricing_method data['price_per_hour'] = allocation_data.get('price_per_hour', 0.0) data['price_per_item'] = allocation_data.get('price_per_item', 0.0) data['pricing_scheme'] = None data['currency'] = allocation_data.get('currency') or self.currency data['cost_object'] = self.cost_object
[docs] def process_payment( self, price: Price | None, provider: PaymentProvider[Any] | None = None, payment_token: str | None = None ) -> Payment | PaymentError | Literal[True] | None: """ Processes the payment for the given reservation token. """ if price and price.amount > 0: assert self.payment_method is not None return process_payment( self.payment_method, price, provider, payment_token) # FIXME: Returning a boolean is a bit strange here, do we # make use of it or can we change this to None? return True
[docs] def is_before_lead_time(self, dt: datetime.datetime) -> bool: if not self.lead_time: return False if not dt.tzinfo: raise RuntimeError(f'The given date has no timezone: {dt}') if not self.timezone: raise RuntimeError('No timezone set on the resource') return ( align_date_to_day(dt, self.timezone, 'down') - datetime.timedelta(days=self.lead_time) ) > utcnow()
[docs] def is_past_deadline(self, dt: datetime.datetime) -> bool: if not self.deadline: return False if not dt.tzinfo: raise RuntimeError(f'The given date has no timezone: {dt}') if not self.timezone: raise RuntimeError('No timezone set on the resource') n, unit = self.deadline match unit: case 'h': # hours result in a simple offset deadline = dt - datetime.timedelta(hours=n) case 'd': # days require that we align the date # to the beginning of the date deadline = ( align_date_to_day(dt, self.timezone, 'down') - datetime.timedelta(days=n - 1) ) case _: # pragma: unreachable raise AssertionError('unreachable') return deadline <= utcnow()
[docs] def is_zip_blocked(self, date: datetime.date) -> bool: if not self.zipcode_block: return False today = datetime.date.today() return (date - today).days > self.zipcode_block['zipcode_days']
[docs] def is_allowed_zip_code(self, zipcode: int) -> bool: assert isinstance(zipcode, int) if not self.zipcode_block: return True return zipcode in self.zipcode_block['zipcode_list']
[docs] def renew_access_token(self) -> None: self.access_token = secrets.token_hex(16)
[docs] def __repr__(self) -> str: return f'{self.title}, {self.group}'