Beispiel #1
0
        # prevent AttributeErrors on first read
        self.category = None
        self.persons = None

    def __repr__(self):
        """Custom repr to look inside the event for debugging purposes."""
        fstr = ("<{0.__class__.__name__}"
                " datetime='{0.datetime}'"
                " title={1!r},"
                " deleted={0.deleted}>")
        return fstr.format(
            self, icemac.addressbook.interfaces.ITitle(self, '<unknown>'))


event_entity = icemac.addressbook.entities.create_entity(
    _(u'event'), icemac.ab.calendar.interfaces.IEvent, Event)


@grok.adapter(icemac.ab.calendar.interfaces.IEvent)
@grok.implementer(icemac.addressbook.interfaces.ITitle)
def event_title(event):
    """Human readable title for an event."""
    if event.alternative_title:
        return event.alternative_title
    if event.category:
        return icemac.addressbook.interfaces.ITitle(event.category)
    return _('event')


@grok.adapter(icemac.ab.calendar.interfaces.IEvent)
@grok.implementer(icemac.ab.calendar.interfaces.ICalendar)
class SearchTermConcatenationSource(
        icemac.addressbook.sources.TitleMappingSource):

    _mapping = collections.OrderedDict(
        (('and', _(u'search-and',
                   default=u'and')), ('or', _(u'search-or', default=u'or'))))
Beispiel #3
0
 def _makeMissingTerm(self, value):
     term = self.terms.getTerm(value)
     term.title = _(u'Missing: ${value}', mapping=dict(value=term.title))
     return term
Beispiel #4
0
 def __init__(self, address_book):
     basic_unit, self.count = zope.size.interfaces.ISized(
         address_book).sizeForSorting()
     self.notes = zope.i18n.translate(
         _(u'The users inside this address book will not get deleted.'),
         context=zope.globalrequest.getRequest())
Beispiel #5
0
    @time_zone.setter
    def time_zone(self, value):
        self._timezone_preference_group.time_zone = value

    # private

    @property
    def _timezone_preference_group(self):
        default_prefs = zope.component.getUtility(
            zope.preference.interfaces.IDefaultPreferenceProvider)
        return default_prefs.getDefaultPreferenceGroup('ab.timeZone')


address_book_entity = icemac.addressbook.entities.create_entity(
    _(u'address book'),
    icemac.addressbook.interfaces.IAddressBook, AddressBook)


@grok.adapter(None)
@grok.implementer(icemac.addressbook.interfaces.IAddressBook)
def get_address_book(context):
    """Get the current address book from every context."""
    return zope.component.hooks.getSite()


def create_and_register(addressbook, attrib_name, class_, interface, name=''):
    """Create an object on an attribute and register it as local utility."""
    obj = getattr(addressbook, attrib_name, None)
    if obj is not None:
        return obj
Beispiel #6
0
def home_page_address_title(hp):
    """Title of a home page address."""
    title = _('none')
    if hp.url:
        title = six.text_type(hp.url)
    return title
Beispiel #7
0
def email_address_title(email):
    """Title of an e-mail address."""
    title = _('none')
    if email.email:
        title = email.email
    return title
Beispiel #8
0
def datetime_wrong_type(field, exc):
    value = exc.args[0]
    return _(
        u'${value} is no valid datetime. '
        u'Must match to format string "${format}".',
        mapping=dict(value=value, format=DATETIME_FORMAT))
Beispiel #9
0
def int_wrong_type(field, exc):
    value = exc.args[0]
    return _(u'${value} is not a valid integer number.',
             mapping=dict(value=value))
Beispiel #10
0
def country_constraint_not_satisfield(field, exc):
    value = exc.args[0]
    titles = [x.token for x in field.source.factory.getValues()]
    return _(u'Value ${value} is not allowed. Allowed values are: ${values}',
             mapping=dict(value=value, values=', '.join(titles)))
Beispiel #11
0
def date_wrong_type(field, exc):
    value = exc.args[0]
    return _(u'${value} is no valid date.', mapping=dict(value=value))
Beispiel #12
0
def choice_constraint_not_satisfield(field, exc):
    value = exc.args[0]
    allowed = [str(x) for x in field.source.factory.getValues()]
    return _(u'Value ${value} is not allowed. Allowed values are: ${values}',
             mapping=dict(value=value, values=', '.join(allowed)))
Beispiel #13
0
@zope.interface.implementer(icemac.addressbook.interfaces.IKeyword)
class Keyword(persistent.Persistent, zope.container.contained.Contained):
    """A keyword."""

    zope.schema.fieldproperty.createFieldProperties(
        icemac.addressbook.interfaces.IKeyword)

    def __init__(self, title=None):
        super(Keyword, self).__init__()
        if title is not None:
            self.title = title


keyword_entity = icemac.addressbook.entities.create_entity(
    _(u'keyword'), icemac.addressbook.interfaces.IKeyword, Keyword)


@zope.component.adapter(icemac.addressbook.interfaces.IKeyword,
                        zope.lifecycleevent.IObjectModifiedEvent)
def changed(obj, event):
    for desc in event.descriptions:
        if (desc.interface == icemac.addressbook.interfaces.IKeyword
                and 'title' in desc.attributes):
            catalog = zope.component.getUtility(
                zope.catalog.interfaces.ICatalog)
            catalog.updateIndex(catalog.get('keywords'))
            break


uniqueTitles = icemac.addressbook.utils.unique_by_attr_factory(
Beispiel #14
0
    icemac.ab.calendar.eventview.interfaces.IEventViewContainer)
class EventViewContainer(zope.container.btree.BTreeContainer):
    """A container for event view configurations."""


@zope.interface.implementer(
    icemac.ab.calendar.eventview.interfaces.IEventViewConfiguration)
class EventViewConfiguration(persistent.Persistent,
                             zope.container.contained.Contained):
    """A configuration of an view of events."""

    zope.schema.fieldproperty.createFieldProperties(
        icemac.ab.calendar.eventview.interfaces.IEventViewConfiguration,
        omit=['categories', 'fields'])
    categories = gocept.reference.ReferenceCollection('categories',
                                                      ensure_integrity=True)
    fields = icemac.ab.calendar.property.AddressBookField('_fields',
                                                          multiple=True)

    def __init__(self, *args, **kw):
        super(EventViewConfiguration, self).__init__(*args, **kw)
        self.categories = set([])

    def __repr__(self):
        """Human readable representation of the object."""
        return u'<EventViewConfiguration title={0!r}>'.format(self.title)


unique_titles = icemac.addressbook.utils.unique_by_attr_factory(
    'title', _('This title is already used for an event view configuration.'))
Beispiel #15
0
 def getTitle(self, value):
     entity, field = untokenize(value)
     field_title = icemac.addressbook.entities.get_field_label(field)
     # The titles might be message ids so allow to translate them.
     return _(u"${prefix} -- ${title}",
              mapping=dict(prefix=entity.title, title=field_title))
Beispiel #16
0
def decimal_wrong_type(field, exc):
    value = exc.args[0]
    return _(u'${value} is not a valid decimal number.',
             mapping=dict(value=value))
Beispiel #17
0
@zope.interface.implementer(
    icemac.addressbook.interfaces.IPostalAddress,
    icemac.addressbook.interfaces.IMayHaveCustomizedPredfinedFields,
)
class PostalAddress(persistent.Persistent, zope.container.contained.Contained):
    """A postal address."""

    zope.schema.fieldproperty.createFieldProperties(
        icemac.addressbook.interfaces.IPostalAddress)


# postal address entity, default_attrib is the name of the attribute
# on IPerson which contains the default postal address.
postal_address_entity = icemac.addressbook.entities.create_entity(
    _(u'postal address'),
    icemac.addressbook.interfaces.IPostalAddress,
    PostalAddress,
    default_attrib='default_postal_address')


@zope.component.adapter(icemac.addressbook.interfaces.IPostalAddress)
@zope.interface.implementer(icemac.addressbook.interfaces.ITitle)
def postal_address_title(address):
    """Title of a postal address."""
    title = _('none')
    values = [
        icemac.addressbook.interfaces.ITitle(getattr(address, x))
        for x in ('address_prefix', 'street', 'zip', 'city', 'country')
        if getattr(address, x)
    ]
Beispiel #18
0
def bool_wrong_type(field, exc):
    value = exc.args[0]
    return _(u'Value ${value} is not allowed. Allowed values are: ${values}',
             mapping=dict(value=value,
                          values=', '.join(TRUE_VALUES + FALSE_VALUES)))
Beispiel #19
0
def phone_number_title(tel):
    """Title of a phone number."""
    title = _('none')
    if tel.number:
        title = tel.number
    return title
Beispiel #20
0
def index_error(field, exc):
    return _(u'Not enough data fields in row.')
Beispiel #21
0
 def _handle_action(self):
     icemac.addressbook.browser.base.delete_persons(self.context,
                                                    self.context.keys())
     self.status = _('Address book contents deleted.')
     self.redirect_to_next_url('object', 'person-list.html')
Beispiel #22
0
class MapFields(z3c.form.group.GroupForm,
                icemac.ab.importer.browser.wizard.base.FileSessionStorageStep):
    "Map the fields in the import file to fields in the addressbook."

    title = label = _(u'Map fields')

    def __init__(self, *args, **kw):
        super(MapFields, self).__init__(*args, **kw)
        session = self.getContent()
        request = self.request
        self.groups = []
        entities = zope.component.getUtility(
            icemac.addressbook.interfaces.IEntities)
        for entity in entities.getMainEntities():
            if entity.class_name == 'icemac.addressbook.person.Person':
                entries_number = 1
                main_prefix = ''
            else:
                entries_number = session.get('entries_number', 0)
                main_prefix = _(u'main')
            for index in range(entries_number):
                if index == 0:
                    row_title_prefix = main_prefix
                else:
                    row_title_prefix = _(u'other')
                title = _('${prefix} ${title}',
                          mapping=dict(prefix=row_title_prefix,
                                       title=entity.title))
                prefix = '%s-%s' % (entity.name, index)
                self.groups.append(
                    FieldsGroup(session, request, self, entity, title, prefix))

    @property
    def fields(self):
        return z3c.form.field.Fields()

    def update(self):
        super(MapFields, self).update()
        icemac.ab.importer.browser.wizard.base.FileSessionStorageStep.update(
            self)
        if not self.nextURL:
            # no redirect to next step, make sure no imported data exists
            icemac.ab.importer.browser.wizard.base.delete_imported_data(self)

    def applyChanges(self, data):
        super(MapFields, self).applyChanges(data)
        import_object_builder = ImportObjectBuilder(
            data, icemac.addressbook.interfaces.IAddressBook(self.context),
            self.getContent()['entries_number'])
        keyword_builder = KeywordBuilder(data)
        session = self.getContent()
        reader = get_reader(session)
        imported = session['imported'] = []
        imported_keywords = session['imported_keywords'] = []
        import_errors = session['import_errors'] = {}
        session['found_errors'] = False
        for data_row in reader:
            imported_keywords.extend(x.__name__
                                     for x in keyword_builder.create(data_row))
            obj, errors = import_object_builder.create(data_row)
            imported.append(obj.__name__)
            import_errors[obj.__name__] = errors
            if errors:
                session['found_errors'] = True
Beispiel #23
0
 def setUpColumns(self):
     return [z3c.table.column.addColumn(
         self, icemac.addressbook.browser.table.TitleLinkColumn, 'title',
         header=_(u'event category'))]
Beispiel #24
0
class IDocument(IDocumentBase):
    """Document storing binary data."""

    title = zope.schema.TextLine(
        title=_(u'document title'),
        description=_(u'Name which is shown in the list view.'))
Beispiel #25
0
        omit=['read_only', 'read_write'])

    read_only = gocept.reference.ReferenceCollection(
        'read_only', ensure_integrity=True)

    read_write = gocept.reference.ReferenceCollection(
        'read_write', ensure_integrity=True)

    def __init__(self, *args, **kw):
        super(Folder, self).__init__(*args, **kw)
        self.read_only = set()
        self.read_write = set()


folder_entity = icemac.addressbook.entities.create_entity(
    _(u'folder'), icemac.ab.document.interfaces.IFolder, Folder)


@zope.interface.implementer(
    icemac.ab.document.interfaces.IDocument,
    icemac.addressbook.interfaces.IMayHaveCustomizedPredfinedFields)
class Document(icemac.addressbook.file.file.BaseFile):
    """Container containing documents and/or other folders."""

    zope.schema.fieldproperty.createFieldProperties(
        icemac.ab.document.interfaces.IDocument,
        omit=['data', 'size'])


document_entity = icemac.addressbook.entities.create_entity(
    _(u'document'), icemac.ab.document.interfaces.IDocument, Document)
Beispiel #26
0
class MoveUp(MoveBase):
    """Move entity up in entity order."""

    direction = 'up'
    message = _('Moved ${entity} up.')
Beispiel #27
0
class SourceFactoryMissingCollectionTermsSource(
        z3c.form.term.MissingCollectionTermsSource):
    """MissingCollectionTermsSource adapted to zc.sourcefactory.

    We need a zc.sourcefactory as base creating the `ITerms` adapter to
    be able to `_makeMissingTerm()` properly.
    """
    def _makeMissingTerm(self, value):
        term = self.terms.getTerm(value)
        term.title = _(u'Missing: ${value}', mapping=dict(value=term.title))
        return term


NoLongerAllowedPerson = z3c.form.error.ErrorViewMessage(
    _('Please deselect the persons prefixed with "Missing:" They are no '
      'longer in the list of available persons. (Maybe reconsider the '
      'following setting: Master Data > Calendar > Settings > '
      'Person keyword)'),
    error=zope.schema.interfaces.WrongContainedType,
    field=icemac.ab.calendar.interfaces.IBaseEvent['persons'])


class EventFields(object):
    """Form fields to add or edit an event."""

    interface = None

    @property
    def fields(self):
        fields = icemac.addressbook.interfaces.IEntity(self.interface)
        field_values = []
        for name, field in fields.getFields():
Beispiel #28
0
class MoveDown(MoveBase):
    """Move entity down in entity order."""

    direction = 'down'
    message = _('Moved ${entity} down.')
Beispiel #29
0
class Field(SessionStorageStep):
    """Step where the user choosed the field he likes to update."""

    interface = IFieldChooser
    title = label = _(u'Choose field')
Beispiel #30
0
 def choice_type_needs_values(field):
     if field.type == u'Choice' and not field.values:
         raise zope.interface.Invalid(
             _(u'type "choice" requires at least one field value.'))