Source code for agency.forms.membership
from onegov.agency import _
from onegov.agency.collections import ExtendedPersonCollection
from onegov.agency.models import ExtendedPerson
from onegov.form import Form
from onegov.form.fields import ChosenSelectField
from sqlalchemy import func
from wtforms.fields import StringField
from wtforms.validators import InputRequired
from wtforms.validators import ValidationError
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Iterable
from typing import TypeVar
[docs]
def duplicates(iterable: 'Iterable[_T]') -> set['_T']:
items = set()
duplicates = set()
for item in iterable:
if item in items:
duplicates.add(item)
items.add(item)
return duplicates
[docs]
class MembershipForm(Form):
""" Form to edit memberships of an organization. """
[docs]
person_id = ChosenSelectField(
label=_('Person'),
choices=[],
validators=[
InputRequired()
]
)
[docs]
def validate_title(self, field: StringField) -> None:
if field.data and not field.data.strip():
raise ValidationError(_('This field is required.'))
[docs]
def on_request(self) -> None:
self.request.include('common')
self.request.include('chosen')
ambiguous = duplicates(
name for name, in self.request.session.query(
func.concat(
ExtendedPerson.last_name, ' ', ExtendedPerson.first_name
)
)
)
def title(person: ExtendedPerson) -> str:
if person.title in ambiguous:
info = (
person.phone_direct
or person.phone
or person.email
or person.postal_address
)
if info:
return f'{person.title} ({info})'
memberships = person.memberships_by_agency
if memberships:
return f'{person.title} ({memberships[0].agency.title})'
return person.title
self.person_id.choices = [
(str(p.id), title(p))
for p in ExtendedPersonCollection(self.request.session).query()
]