Beispiel #1
0
    def action_move(self, action):
        '''
        Book this resource
        '''
        data, errors = self.extractData()

        data['tipology'] = self.context.getTipologia_prenotazione()
        conflict_manager = self.prenotazioni_view.conflict_manager
        current_data = self.context.getData_prenotazione()
        current = {'booking_date': current_data, 'tipology': data['tipology']}
        current_slot = conflict_manager.get_choosen_slot(current)
        current_gate = self.context.getGate()
        exclude = {current_gate: [current_slot]}

        if conflict_manager.conflicts(data, exclude=exclude):
            msg = _(u'Sorry, this slot is not available or does not fit your '
                    u'booking.')
            api.portal.show_message(msg, self.request, type="error")
            raise ActionExecutionError(Invalid(msg))
        if self.exceedes_date_limit(data):
            msg = _(u'Sorry, you can not book this slot for now.')
            api.portal.show_message(msg, self.request, type="error")
            raise ActionExecutionError(Invalid(msg))

        obj = self.do_move(data)
        obj  # pyflakes
        msg = _('booking_moved')
        IStatusMessage(self.request).add(msg, 'info')
        booking_date = data['booking_date'].strftime('%d/%m/%Y')
        target = urlify(self.prenotazioni_folder.absolute_url(),
                        paths=['prenotazioni_week_view'],
                        params={'data': booking_date})
        return self.request.response.redirect(target)
Beispiel #2
0
    def validateAction(self, data):
        # ActionExecutionError ... form wide error
        # WidgetActionExecutionError ... widget specific
        # TODO: validate all sort of extra info- new object does not exist yet
        # data contains already field values
        datasets = data.get('environmental_datasets', {}).keys()
        if not datasets:
            # FIXME: Make this a widget error, currently shown as form wide error
            raise ActionExecutionError(Invalid('No environmental dataset selected.'))

        # TODO: we should make sure only user picks only one option, otherwise pseudo absence
        #       will be preferred (maybe we can do both?, select absence points, and fill up mith pseudo absences?)
        # we need an absence dataset or a a number of pseudo absence points
        if not data.get('species_pseudo_absence_points'):
            if not data.get('species_absence_dataset'):
                raise ActionExecutionError(RequiredMissing('No absence points selected.'))
        else:
            numabspoints = data.get('species_number_pseudo_absence_points')
            if not numabspoints:
                raise ActionExecutionError(RequiredMissing('No absence points selected'))
            elif numabspoints <= 0:
                raise ActionExecutionError(Invalid('Number of absence points must be greater than 0.'))
        # Determine lowest resolution
        # FIXME: this is slow and needs improvements
        #        and accessing _terms is not ideal
        res_vocab = getUtility(IVocabularyFactory, 'resolution_source')(self.context)
        resolution_idx = -1
        for dsbrain in (uuidToCatalogBrain(d) for d in datasets):
            idx = res_vocab._terms.index(res_vocab.getTerm(dsbrain.BCCResolution))
            if idx > resolution_idx:
                resolution_idx = idx
        data['resolution'] = res_vocab._terms[resolution_idx].value
Beispiel #3
0
    def validateAction(self, data):
        """
        Get resolution from SDM and use it to find future datasets

        TODO: if required layers are not available in future datasets, use current layers from SDM
        """
        # ActionExecutionError ... form wide error
        # WidgetActionExecutionError ... widget specific

        # TODO: match result layers with sdm layers and get missing layers from SDM?
        #       -> only environmental? or missing climate layers as well?
        #       do matching here? or in job submit?

        datasets = data.get('future_climate_datasets', [])
        if not datasets:
            # FIXME: Make this a widget error, currently shown as form wide error
            raise ActionExecutionError(Invalid('No future climate dataset selected.'))
        models = data.get('species_distribution_models', {})
        if not tuple(chain.from_iterable(x for x in models.values())):
            raise ActionExecutionError(Invalid('No source dataset selected.'))   

        # Determine lowest resolution
        # FIXME: this is slow and needs improvements
        #        and accessing _terms is not ideal
        res_vocab = getUtility(IVocabularyFactory, 'resolution_source')(self.context)
        resolution_idx = -1
        for dsbrain in (uuidToCatalogBrain(d) for d in datasets):
            idx = res_vocab._terms.index(res_vocab.getTerm(dsbrain.BCCResolution))
            if idx > resolution_idx:
                resolution_idx = idx
        data['resolution'] = res_vocab._terms[resolution_idx].value
Beispiel #4
0
    def handleApply(self, action):
        print "doing handle apply"
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        principal_id = data['principal_id']
        role = PLONE_ROLES[data['role_id']]

        try:
            principal = self._search_principal(principal_id)
        except NoResultsException:
            msg = u'No results found.'
            self.status = msg
            print self.status
            raise ActionExecutionError(Invalid(msg))
        except MultipleResultsException:
            msg = 'The user/group id is not precise enough.'
            self.status = msg
            print self.status
            raise ActionExecutionError(Invalid(msg))

        self.status = u"Saved."

        self.share_with_principal(principal['id'], role)
Beispiel #5
0
    def handleRegister(self, action):
        print "handle registrer"
        data, errors = self.extractData()
        if errors:
            print "all errors views names", map(lambda err: err.widget.name, errors)
            print self.formErrorsMessage
            print "self.widgets.errors", self.widgets.errors
            self.status = self.formErrorsMessage
            return

        administrator = data['IAdministrator.administrator']
        if api.user.get(username=administrator.username):
            raise ActionExecutionError(Invalid(u"Uživatelské jméno u správce producenta je již použito. Vyplňte jiné."))   
        # check administrator passwords
        if administrator.password_ctl != administrator.password:
            raise ActionExecutionError(Invalid(u"U správce producenta se neshodují zadaná hesla. Vyplňte hesla znovu."))

        editorFields = ['fullname','email','phone','username','password','password_ctl']
        editorValues = map(lambda key: data.get('IEditor.'+key,None), editorFields)

        if filter(lambda value: value, editorValues):
            if False in map(lambda value: bool(value), editorValues):
                raise ActionExecutionError(Invalid(u"Některé položky u editora nejsou vyplněny. Buď vyplňte editorovi všechny položky, nebo je všechny smažte."))
                
            editorData = dict(zip(editorFields, editorValues))
            if editorData['password'] != editorData['password_ctl']:
                raise ActionExecutionError(Invalid(u"U editora se neshodují zadaná hesla. Vyplňte hesla znovu."))
            if api.user.get(username=editorData['username']):
                raise ActionExecutionError(Invalid(u"Uživatelské jméno u editora je již obsazené. Vyplňte jiné."))

        producentsFolder = self.getProducentsFolder()
        # hack for title and description
        data['title'] = data.get('IBasic.title','')
        data['description'] = data.get('IBasic.description','')

        producent = createContentInContainer(producentsFolder, "edeposit.user.producent", **data)

        if filter(lambda value: value, editorValues):
            editorsFolder = producent['producent-editors']
            editorData['title'] = editorData['fullname']
            editor = createContentInContainer(editorsFolder, "edeposit.user.producenteditor", **editorData)


        administratorsFolder = producent['producent-administrators']
        

        administrator.title = getattr(administrator,'fullname',None)
        addContentToContainer(administratorsFolder, administrator, False)

        if producent is not None:
            wft = api.portal.get_tool('portal_workflow')
            wft.doActionFor(producent,'submit')
            # mark only as finished if we get the new object
            self._finishedAdd = True
            IStatusMessage(self.request).addStatusMessage(_(u"Item created"), "info")
            url = "%s/%s" % (api.portal.getSite().absolute_url(), 'register-with-producent-successed')
            self.request.response.redirect(url)
Beispiel #6
0
 def add(self, object):
     if api.user.get(username=object.username):
         raise ActionExecutionError(
             Invalid(
                 u"Uživatelské jméno již existuje. Na záložce Přihlášení použijte jiné."
             ))
     if object.password != object.password_ctl:
         raise ActionExecutionError(
             Invalid(
                 u"Hesla se neshodují. Na záložce Přihlášení zadejte hesla znovu."
             ))
     return super(ProducentAdministratorAddForm, self).add(object)
 def handle_error(self, error, data):
     # Current api v3 documentation only lists errors in the 400 and 500
     # range.  The 400 code can mean a lot of things...
     if error.code == 400:
         error_msg = _(
             u"mailchimp_error_msg_already_subscribed",
             default=u"Could not subscribe to newsletter. "
             u"Either the email '${email}' is already subscribed "
             u"or something else is wrong. Try again later.",
             mapping={u"email": data['email']},
         )
         translated_error_msg = self.context.translate(error_msg)
         raise WidgetActionExecutionError('email',
                                          Invalid(translated_error_msg))
     elif error.code == 220:
         error_msg = _(
             u"mailchimp_error_msg_banned",
             default=u"Could not subscribe to newsletter. "
             u"The email '${email}' has been banned.",
             mapping={u"email": data['email']},
         )
         translated_error_msg = self.context.translate(error_msg)
         raise WidgetActionExecutionError('email',
                                          Invalid(translated_error_msg))
     else:
         error_msg = _(
             u"mailchimp_error_msg",
             default=u"Could not subscribe to newsletter. "
             u"Please contact the site administrator: "
             u"'${error}'",
             mapping={u"error": error},
         )
         translated_error_msg = self.context.translate(error_msg)
         raise ActionExecutionError(Invalid(translated_error_msg))
Beispiel #8
0
    def validateAction(self, data):
        # ActionExecutionError ... form wide error
        # WidgetActionExecutionError ... widget specific
        # TODO: validate all sort of extra info- new object does not exist yet
        # data contains already field values
        datasets = data.get('environmental_datasets', {}).keys()
        if not datasets:
            # FIXME: Make this a widget error, currently shown as form wide
            # error
            raise ActionExecutionError(
                Invalid('No environmental dataset selected.'))

        # Determine highest resolution
        # FIXME: this is slow and needs improvements
        #        and accessing _terms is not ideal
        res_vocab = getUtility(IVocabularyFactory,
                               'resolution_source')(self.context)
        if data.get('scale_down', False):
            # ... find highest resolution
            resolution_idx = 99  # Arbitrary choice of upper index limit
            for dsbrain in (uuidToCatalogBrain(d) for d in datasets):
                idx = res_vocab._terms.index(
                    res_vocab.getTerm(dsbrain.BCCResolution))
                if idx < resolution_idx:
                    resolution_idx = idx
            data['resolution'] = res_vocab._terms[resolution_idx].value
        else:
            # ... find lowest resolution
            resolution_idx = -1
            for dsbrain in (uuidToCatalogBrain(d) for d in datasets):
                idx = res_vocab._terms.index(
                    res_vocab.getTerm(dsbrain.BCCResolution))
                if idx > resolution_idx:
                    resolution_idx = idx
            data['resolution'] = res_vocab._terms[resolution_idx].value
Beispiel #9
0
    def handleProceed(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        cart = Cart.from_request(self.request)
        order = cart.data

        # save shipping address to order
        ship_to = cart.ship_to
        ship_to.update(data)

        # calculate shipping using selected method, and update order
        method_id = self.request.form['shipping_method']
        method = self.all_shipping_methods[method_id]
        charge = calculate_shipping(cart, method, ship_to)
        if charge is None:
            raise ActionExecutionError(
                Invalid(u'Please select a valid shipping method.'))
        order['ship_method'] = method['name']
        order['ship_charge'] = Decimal(charge).quantize(Decimal('0.01'))

        # This is where we could save the shipping address
        # for use in future orders.

        return self.request.response.redirect(
            self.context.absolute_url() + '/checkout')
Beispiel #10
0
    def validateAction(self, data):
        datasets = list(chain.from_iterable(data.get('datasets', {}).values()))
        if not datasets:
            # FIXME: Make this a widget error, currently shown as form wide
            # error
            raise ActionExecutionError(Invalid('No dataset selected.'))

        # all selected datasets are combined into one ensemble analysis
        # get resolution for ensembling
        # Determine lowest resolution
        # FIXME: An experiment should store the resolution metadata on the dataset
        # e.g. an SDM current projection needs to store resolution on tif file
        res_vocab = getUtility(IVocabularyFactory,
                               'resolution_source')(self.context)
        resolution_idx = -1
        for dsbrain in (uuidToCatalogBrain(d) for d in datasets):
            try:
                idx = res_vocab._terms.index(
                    res_vocab.getTerm(dsbrain.BCCResolution))
            except:
                # FIXME: need faster way to order resolutions
                idx = res_vocab._terms.index(
                    res_vocab.getTerm(dsbrain.getObject().__parent__.
                                      job_params['resolution']))
            if idx > resolution_idx:
                resolution_idx = idx
        data['resolution'] = res_vocab._terms[resolution_idx].value
Beispiel #11
0
    def handleApply(self, action):
        data, errors = self.extractData()
        if errors:
            return

        agenda_items_to_include = []
        for agenda_item in self.get_agenda_items():
            if agenda_item.name in self.request:
                agenda_items_to_include.append(agenda_item)

        if not agenda_items_to_include:
            raise (ActionExecutionError(
                Invalid(_(u"Please select at least one agenda item."))))

        operations = ManualExcerptOperations(
            agenda_items_to_include,
            data['title'],
            include_initial_position=data['include_initial_position'],
            include_legal_basis=data['include_legal_basis'],
            include_considerations=data['include_considerations'],
            include_proposed_action=data['include_proposed_action'],
            include_discussion=data['include_discussion'],
            include_decision=data['include_decision'],
            include_publish_in=data['include_publish_in'],
            include_disclose_to=data['include_disclose_to'],
            include_copy_for_attention=data['include_copy_for_attention'])
        command = CreateGeneratedDocumentCommand(data['dossier'], self.model,
                                                 operations)
        command.execute()
        command.show_message()
        return self.redirect_to_meeting()
Beispiel #12
0
 def handle_error(self, error, data):
     if error.code == 400:
         error_msg = _(u"mailinglijst_error_msg_already_subscribed",
                       default=u"Could not subscribe to newsletter. "
                       u"Either the email '${email}' is already subscribed "
                       u"or something else is wrong. Try again later.",
                       mapping={u"email": data['email']})
         translated_error_msg = self.context.translate(error_msg)
         raise WidgetActionExecutionError('email',
                                          Invalid(translated_error_msg))
     elif error.code == 220:
         error_msg = _(u"mailinglijst_error_msg_banned",
                       default=u"Could not subscribe to newsletter. "
                       u"The email '${email}' has been banned.",
                       mapping={u"email": data['email']})
         translated_error_msg = self.context.translate(error_msg)
         raise WidgetActionExecutionError('email',
                                          Invalid(translated_error_msg))
     else:
         error_msg = _(u"mailinglijst_error_msg",
                       default=u"Could not subscribe to newsletter. "
                       u"Please contact the site administrator: "
                       u"'${error}'",
                       mapping={u"error": error})
         translated_error_msg = self.context.translate(error_msg)
         raise ActionExecutionError(Invalid(translated_error_msg))
Beispiel #13
0
    def render(self):
        parent = aq_parent(self.context)
        if api.content.get_state(parent).startswith('phase1-'):
            conclusion = parent.get_conclusion()
            if not conclusion:
                api.content.transition(
                    obj=parent,
                    transition='phase1-draft-conclusions'
                )
                url = '%s/++add++Conclusion' % parent.absolute_url()
            else:
                url = '%s/edit' % conclusion.absolute_url()

        elif api.content.get_state(parent).startswith('phase2-'):
            conclusionsphase2 = parent.get_conclusion_phase2()
            if not conclusionsphase2:
                api.content.transition(
                    obj=parent,
                    transition='phase2-draft-conclusions'
                )

                cp2 = parent.invokeFactory(
                    id=int(time()),
                    type_name='ConclusionsPhase2'
                )
                conclusionsphase2 = parent.get(cp2)

            url = '%s/edit' % conclusionsphase2.absolute_url()
        else:
            raise ActionExecutionError(Invalid(u"Invalid context"))

        return self.request.response.redirect(url)
    def handleApply(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        raise ActionExecutionError(Invalid(u"Please see that data stays intact over postback"))
Beispiel #15
0
 def _check_provider_constraints(self, data):
     # Tried this with an invariant, but
     # did not get the right data in the param
     # of the invariant.
     provider_fields_map = dict(
         ((u'Twilio', TWILIO_FIELDS), (u'Messagebird', MESSAGEBIRD_FIELDS)))
     for field_name in provider_fields_map[data['provider']]:
         if not data[field_name]:
             field_title = ISMSAuthenticatorSettings.get(field_name).title
             raise ActionExecutionError(
                 Invalid(_(u'Field {0} is required.').format(field_title)))
         if field_name == 'message_bird_sender':
             if not (2 < len(data[field_name]) < 12):
                 raise ActionExecutionError(
                     Invalid(
                         _(u'Field Messagebird sender has to be between 3 and 11 chars.'
                           )))
Beispiel #16
0
    def validate(self, data):
        self._participant = data.get('contact')
        query = self.model_class.query.by_participant(
            self._participant).by_dossier(self.context)

        if query.count():
            raise ActionExecutionError(Invalid(
                _(u'msg_participation_already_exists',
                  u"There already exists a participation for this contact.")))
Beispiel #17
0
 def handleApply(self, action):
     data, errors = self.extractData()
     if errors:
         return
     folder = self._getFolder(data['folder'])
     if folder is None:
         error = interface.Invalid(_(u'Unknown folder.'))
         raise ActionExecutionError(error)
     try:
         self._createUrl(folder, data)
     except Unauthorized:
         error = interface.Invalid(_(u'Permission denied.'))
         raise ActionExecutionError(error)
     except ValueError:
         error = interface.Invalid(_(u'Could not add to folder.'))
         raise ActionExecutionError(error)
     else:
         self.request.response.redirect('@@collective_readitlater_urladded')
Beispiel #18
0
    def action_book(self, action):
        '''
        Book this resource
        '''
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        if not data.get('booking_date'):
            raise WidgetActionExecutionError(
                'booking_date',
                Invalid(_(u"Please provide a booking date"))
            )

        conflict_manager = self.prenotazioni.conflict_manager
        if conflict_manager.conflicts(data):
            msg = _(u'Sorry, this slot is not available anymore.')
            raise WidgetActionExecutionError(
                'booking_date',
                Invalid(msg)
            )
        if self.exceedes_date_limit(data):
            msg = _(u'Sorry, you can not book this slot for now.')
            raise WidgetActionExecutionError(
                'booking_date',
                Invalid(msg)
            )

        captcha = getMultiAdapter(
            (aq_inner(self.context), self.request),
            name='recaptcha'
        )

        if 'captcha' in data and not captcha.verify():
            msg=_(u"Please check the captcha")
            raise ActionExecutionError(Invalid(msg))

        obj = self.do_book(data)
        if not obj:
            msg = _(u'Sorry, this slot is not available anymore.')
            api.portal.show_message(
                message=msg,
                type='warning',
                request=self.request)
            target = self.back_to_booking_url
            return self.request.response.redirect(target)
        msg = _('booking_created')
        api.portal.show_message(message=msg, type='info', request=self.request)
        booking_date = data['booking_date'].strftime('%d/%m/%Y')
        params = {'data': booking_date,
                  'uid': obj.UID()}
        target = urlify(self.context.absolute_url(),
                        paths=["@@prenotazione_print"],
                        params=params)
        return self.request.response.redirect(target)
Beispiel #19
0
 def validateAction(self, data):
     # ActionExecutionError ... form wide error
     # WidgetActionExecutionError ... widget specific
     # TODO: validate all sort of extra info- new object does not exist yet
     # data contains already field values
     datasets = data.get('datasubsets', [])
     if not datasets:
         # FIXME: Make this a widget error, currently shown as form wide
         # error
         raise ActionExecutionError(
             Invalid('No environmental dataset selected.'))
Beispiel #20
0
    def validate(self, data):
        overlapping = Membership.query.fetch_overlapping(
            data['date_from'], data['date_to'], data['member'],
            data['committee'])

        if overlapping:
            msg = _(
                "Can't add membership, it overlaps an existing membership "
                "from ${date_from} to ${date_to}.",
                mapping=dict(date_from=overlapping.format_date_from(),
                             date_to=overlapping.format_date_to()))

            raise (ActionExecutionError(Invalid(msg)))
    def action_book(self, action):
        '''
        Book this resource
        '''
        data, errors = self.extractData()
        parsed_data = self.get_parsed_data(data)

        start_date = data['start_date']
        if self.has_slot_conflicts(parsed_data):
            msg = _(
                'slot_conflict_error',
                u'This gate has some booking schedule in this time '
                u'period.')
            raise ActionExecutionError(Invalid(msg))

        elif not self.prenotazioni.is_valid_day(start_date):
            msg = _('day_error', u'This day is not valid.')
            raise ActionExecutionError(Invalid(msg))

        self.do_book(parsed_data)
        qs = {'data': data['start_date'].strftime('%d/%m/%Y')}
        target = urlify(self.context.absolute_url(), params=qs)
        return self.request.response.redirect(target)
Beispiel #22
0
    def _validate_recurrence_options(self, data):
        """Validate that when recurrence is configured and the resource is
        partly available the separately option must be enabled as well.

        This validation has been moved here from a form invariant since
        invariants do not seem to work with groups.

        """
        if 'recurrence' in data and data['recurrence']:
            if data['partly_available'] and not data['separately']:
                raise ActionExecutionError(
                    Invalid(
                        _(u'Partly available allocations can only be reserved '
                          u'separately')))
Beispiel #23
0
    def render(self):
        if api.content.get_state(self.context).startswith('phase1-'):
            api.content.transition(
                obj=self.context,
                transition='phase1-reopen')
        elif api.content.get_state(self.context).startswith('phase2-'):
            api.content.transition(
                obj=self.context,
                transition='phase2-reopen')
        else:
            raise ActionExecutionError(Invalid(u"Invalid context"))

        url = '%s/++add++Comment' % self.context.absolute_url()
        return self.request.response.redirect(url)
Beispiel #24
0
 def handleSave(self, action):
     data, errors = self.extractData()
     if not self.get_subscribers(data=data):
         raise ActionExecutionError(
             Invalid(
                 _(
                     "empty_subscribers",
                     default=u"You need to provide at least one email address or channel.",  # noqa
                 )
             )
         )
     if errors:
         self.status = self.formErrorsMessage
         return
     return self.sendMessage(data=data)
    def action_move(self, action):
        """
        Book this resource
        """
        data, errors = self.extractData()
        data["tipology"] = self.context.getTipologia_prenotazione()
        conflict_manager = self.prenotazioni_view.conflict_manager
        current_data = self.context.getData_prenotazione()
        current = {"booking_date": current_data, "tipology": data["tipology"]}
        current_slot = conflict_manager.get_choosen_slot(current)
        current_gate = getattr(self.context, "gate", "")
        exclude = {current_gate: [current_slot]}

        if conflict_manager.conflicts(data, exclude=exclude):
            msg = _(
                u"Sorry, this slot is not available or does not fit your "
                u"booking."
            )
            api.portal.show_message(msg, self.request, type="error")
            raise ActionExecutionError(Invalid(msg))
        if self.exceedes_date_limit(data):
            msg = _(u"Sorry, you can not book this slot for now.")
            api.portal.show_message(msg, self.request, type="error")
            raise ActionExecutionError(Invalid(msg))

        obj = self.do_move(data)
        obj  # pyflakes
        msg = _("booking_moved")
        IStatusMessage(self.request).add(msg, "info")
        booking_date = data["booking_date"].strftime("%d/%m/%Y")
        target = urlify(
            self.prenotazioni_folder.absolute_url(),
            paths=["prenotazioni_week_view"],
            params={"data": booking_date},
        )
        return self.request.response.redirect(target)
    def action_book(self, action):
        """
        Book this resource
        """
        data, errors = self.extractData()
        parsed_data = self.get_parsed_data(data)

        start_date = data["start_date"]
        if self.has_slot_conflicts(parsed_data):
            msg = _(
                "slot_conflict_error",
                u"This gate has some booking schedule in this time "
                u"period.",
            )
            raise ActionExecutionError(Invalid(msg))

        elif not self.prenotazioni.is_valid_day(start_date):
            msg = _("day_error", u"This day is not valid.")
            raise ActionExecutionError(Invalid(msg))

        self.do_book(parsed_data)
        qs = {"data": data["start_date"].strftime("%d/%m/%Y")}
        target = urlify(self.context.absolute_url(), params=qs)
        return self.request.response.redirect(target)
Beispiel #27
0
    def create_question(self, action):
        context = aq_inner(self.context)
        text = self.request.form.get('form.widgets.text', '')
        if not text.strip():
            raise ActionExecutionError(Invalid(u"Answer text is empty"))

        id = str(int(time()))
        item_id = context.invokeFactory(
            type_name='CommentAnswer',
            id=id,
        )
        comment = context.get(item_id)
        comment.text = text

        return self.request.response.redirect(context.absolute_url())
Beispiel #28
0
    def validate(self, data):
        overlapping = Membership.query.fetch_overlapping(
            data.get('date_from'),
            data.get('date_to'),
            data.get('member'),
            self.model.committee,
            ignore_id=self.model.membership_id)

        if overlapping:
            msg = _(
                "Can't change membership, it overlaps an existing membership "
                "from ${date_from} to ${date_to}.",
                mapping=dict(date_from=overlapping.format_date_from(),
                             date_to=overlapping.format_date_to()))

            raise (ActionExecutionError(Invalid(msg)))
Beispiel #29
0
    def handle_delete(self, action):
        data, errors = self.extractData()
        if errors:
            return

        lfa = LandFileApi(self.context.landfiles)
        orig = lfa.get_by_shortname(data['shortname'])
        title = orig.title
        try:
            lfa.delete(title)
        except KeyError as err:
            raise ActionExecutionError(Invalid(err.message))

        messages = IStatusMessage(self.request)
        messages.add(u'Deleted landfile: {}'.format(title))

        self.redirect_to_listing()
Beispiel #30
0
    def render(self):
        # Execute the transition
        if api.content.get_state(self.context).startswith('phase1-'):
            api.content.transition(
                obj=self.context,
                transition='phase1-ask-answer-approval'
            )
        elif api.content.get_state(self.context).startswith('phase2-'):
            api.content.transition(
                obj=self.context,
                transition='phase2-ask-answer-aproval'
            )
        else:
            raise ActionExecutionError(Invalid(u"Invalid context"))

        url = '%s/%s/edit' % (self.context.absolute_url(), self.comment)
        return self.request.response.redirect(url)