Exemplo n.º 1
0
 def validate(self, action, data):
     # submitted data is actually updated in following call to super.validate
     # !+PASTDATAENTRY(mr, jun-2011) enhancement? see Issue 612 Comment 6:
     # unrequire, allow active_date=None,
     # get_effective_active_date -> last workflow non-None active_date
     errors = super(WorkflowActionViewlet, self).validate(action, data)
     if "date_active" in data.keys():
         min_date_active = self.get_min_date_active()
         if data.get("date_active") < min_date_active:
             errors.append(
                 zope.interface.Invalid(_("Active Date is in the past.")))
         elif data.get("date_active") > datetime.datetime.now():
             errors.append(
                 zope.interface.Invalid(_("Active Date is in the future.")))
     if "registry_number" in data.keys():
         reg_number = data.get("registry_number")
         if reg_number:
             session = Session()
             num = session.query(Doc).filter(
                 Doc.registry_number == reg_number).count()
             if num != 0:
                 errors.append(
                     zope.interface.Invalid(
                         "This registry number is already taken."))
     return errors
Exemplo n.º 2
0
    def update(self, transition_id=None):
        if IWorkspaceContainer.providedBy(self.context.__parent__):
            self._old_url = WorkspaceAbsoluteURLView(self.context,
                                                     self.request)()
        workflow = interfaces.IWorkflow(self.context)
        if transition_id:
            transition = workflow.get_transition(transition_id)
            title = translate(_(transition.title), context=self.request)
            self.status = translate(_(
                u"Confirmation required for workflow transition: '${title}'",
                mapping={"title": title}),
                                    context=self.request)
        self.setupActions(transition_id)

        if (ILegislativeContent.providedBy(self.context)
                and get_mask(self.context) == "manual"
                and not self.context.registry_number):
            self.form_fields = self.form_fields.omit("note", "date_active")
        else:
            self.form_fields = self.form_fields.omit("registry_number")

        if not self.actions:
            self.form_fields = self.form_fields.omit("note", "date_active")
        elif not IFeatureAudit.providedBy(self.context):
            self.form_fields = self.form_fields.omit("note", "date_active")
        # !+SUPERFLUOUS_ObejctModifiedEvent(mr, nov-2011) the following update()
        # is causing a ModifiedEvent to be fired, causing a modify change to be
        # logged (while this workflow change should be just that).
        super(WorkflowActionViewlet, self).update()
Exemplo n.º 3
0
 def getMessages(self):
     messages = []
     message = {"level": "info", "header": _("Signatories"), "text": u""}
     context = removeSecurityProxy(self.context)
     signatory_feature = context.signatory_feature
     if signatory_feature and signatory_feature.needs_signatures():
         if signatory_feature.valid_num_consented_signatories(context):
             message["text"] = _("signature_requirement_met",
                 default=(u"This document has the required number of "
                     u"signatories. ${signed_members} member(s) have signed"
                     u". ${required_members} signature(s) required."
                 ),
                 mapping = {
                     "signed_members": signatory_feature.num_consented_signatories(context),
                     "required_members": signatory_feature.get_param("min_signatories")
                 }
             )
         else:
             message["level"] = "warning"
             message["text"] = _("signature_requirements_not_met",
                     default=(u"This document does not have the required "
                         u"number of signatories. Requires "
                         u"${required_members} signature(s). " 
                         u"${signed_members} member(s) have signed."
                     ),
                     mapping={
                         "required_members": signatory_feature.get_param("min_signatories"),
                         "signed_members": signatory_feature.num_consented_signatories(context)
                     }
             )
         messages.append(message)
     return messages
Exemplo n.º 4
0
 def description(self):
     context = _merged(self.context)
     return "%s %s (%s %s %s)" % (
         translate(_(u"Debate record of ")),
         self.translate(context.sitting, "short_name"),
         context.sitting.start_date.strftime('%Y-%m-%d %H:%M'), _(u"to"),
         context.sitting.end_date.strftime('%H:%M'))
Exemplo n.º 5
0
    def form_name(self):
        if IVersion.providedBy(self.context):
            context = self.context.head
        else:
            context = self.context
        props = IDCDescriptiveProperties(context, None) or context

        if self.is_translation:
            language = get_language_by_name(self.context.language)["name"]
            return _(u"edit_translation_legend",
                     default=u"Editing $language translation of '$title'",
                     mapping={
                         "title": translate(props.title, context=self.request),
                         "language": language
                     })

        elif IVersion.providedBy(self.context):
            return _(u"edit_version_legend",
                     default=u'Editing "$title" (version $version)',
                     mapping={
                         "title": translate(props.title, context=self.request),
                         "version": self.context.seq
                     })
        return _(
            u"edit_item_legend",
            default=u'Editing "$title"',
            mapping={"title": translate(props.title, context=self.request)})
Exemplo n.º 6
0
 class IRestorePasswordForm(interface.Interface):
     login = schema.TextLine(title=_("label_restore_password_username",
                                     default=u"Username"),
                             required=False)
     email = schema.TextLine(title=_("label_restore_password_email",
                                     default=u"Email"),
                             required=False)
Exemplo n.º 7
0
 class IWorkflowForm(zope.interface.Interface):
     note = zope.schema.Text(title=_("Comment on workflow change"),
                             required=False)
     date_active = zope.schema.Datetime(title=_("Active Date"),
                                        required=True)
     registry_number = zope.schema.TextLine(title=_("Registry number"),
                                            required=False)
Exemplo n.º 8
0
    def columns(self):
        from bungeni.models import domain

        def attachment_version_uri(i):
            # !+ bungeni.models.domain.Version
            print "VersionFileListingViewlet", i
            assert isinstance(i, domain.AttachmentVersion), \
                "Not a domain.AttachmentVersion: %s"  % (i)
            # !+STRING_KEY_FILE_VERSION the "obj-%d" context below is an
            # AttachmentVersion and does NOT have a "version-log" view!
            return "obj-%d/version-log/%s" % (i.attachment_id, i.__name__)

        return [
            column.GetterColumn(
                title=_("file_version_filename", default="file"),
                getter=lambda i, f: "%s" % (i.title),
                cell_formatter=lambda g, i, f: '<a href="%s/files/%s">%s</a>' %
                (f.url, attachment_version_uri(i), g)),
            column.GetterColumn(title=_("file_version_status",
                                        default="status"),
                                getter=lambda i, f: i.status),
            column.GetterColumn(
                title=_("file_version_last_modified", default="modified"),
                getter=lambda i, f: self.date_formatter.format(i.status_date)),
        ]
Exemplo n.º 9
0
 def title(self):
     context = _merged(self.context)
     return "%s %s, %s %s %s" % (
         translate(_(u"Debate Record:")),
         self.translate(context.sitting, "short_name"),
         context.sitting.start_date.strftime('%Y-%m-%d, %H:%M'), _(u"to"),
         context.sitting.end_date.strftime('%H:%M'))
Exemplo n.º 10
0
class RestoreLogin(LoginBase):
    class IRestoreLoginForm(interface.Interface):
        email = schema.TextLine(
            title=_("label_restore_login_email", default=u"Email"))

    form_fields = form.Fields(IRestoreLoginForm)
    form_name = _(u"Restore Login")

    def __call__(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            workspace = get_application()["workspace"]
            self.request.response.redirect(absoluteURL(workspace,
                                                       self.request))
        return super(RestoreLogin, self).__call__()

    @form.action(_(u"Restore"), name="restore")
    def handle_restore(self, action, data):
        email = data.get("email", "")
        if email:
            session = Session()
            user = session.query(User).filter(User.email == email).first()
            if user:
                mailer = getUtility(IBungeniMailer)
                self.message = _(u"Your login is: ") + user.login

                text = ViewPageTemplateFile("templates/mail.pt")(self)
                message = MIMEText(text)
                message.set_charset("utf-8")
                message["Subject"] = _(u"Bungeni login restoration")
                message["To"] = email
                mailer.send(message)
                self.status = _(u"Your login was sent to you email.")
            else:
                self.status = _(u"Wrong email address.")
Exemplo n.º 11
0
 def title(self):
     context = _merged(self.context)
     return "%s %s, %s %s %s" % (translate(_(u"Debate Record:")), 
             self.translate(context.sitting, "short_name"), 
             context.sitting.start_date.strftime('%Y-%m-%d, %H:%M'), 
             _(u"to"), 
             context.sitting.end_date.strftime('%H:%M'))
Exemplo n.º 12
0
 def description(self):
     context = _merged(self.context)
     return "%s %s (%s %s %s)" % (translate(_(u"Sitting scheduled for")),
             self.translate(context.group, "short_name"),
             context.start_date.strftime('%Y-%m-%d %H:%M'), 
             _(u"to"),
             context.end_date.strftime('%H:%M'))
Exemplo n.º 13
0
 def description(self):
     context = _merged(self.context)
     return "%s %s (%s %s %s)" % (
         translate(_(u"Sitting scheduled for")),
         self.translate(context.group, "short_name"),
         context.start_date.strftime('%Y-%m-%d %H:%M'), _(u"to"),
         context.end_date.strftime('%H:%M'))
Exemplo n.º 14
0
 def description(self):
     context = _merged(self.context)
     return "%s %s (%s %s %s)" % (translate(_(u"Debate record of ")),
             self.translate(context.sitting, "short_name"),
             context.sitting.start_date.strftime('%Y-%m-%d %H:%M'), 
             _(u"to"),
             context.sitting.end_date.strftime('%H:%M'))
Exemplo n.º 15
0
 def update(self, transition_id=None):
     if IWorkspaceContainer.providedBy(self.context.__parent__):
         self._old_url = WorkspaceAbsoluteURLView(
             self.context, self.request)()
     workflow = interfaces.IWorkflow(self.context)
     if transition_id:
         transition = workflow.get_transition(transition_id)
         title = translate(_(transition.title), context=self.request)
         self.status = translate(
             _(u"Confirmation required for workflow transition: '${title}'",
                 mapping={"title": title}
             ), 
             context=self.request)
     self.setupActions(transition_id)
     
     if (ILegislativeContent.providedBy(self.context) and
             get_mask(self.context) == "manual" and 
             not self.context.registry_number
         ):
         self.form_fields = self.form_fields.omit("note", "date_active")
     else:
         self.form_fields = self.form_fields.omit("registry_number")
     
     if not self.actions: 
         self.form_fields = self.form_fields.omit("note", "date_active")
     elif not IFeatureAudit.providedBy(self.context):
         self.form_fields = self.form_fields.omit("note", "date_active")
     # !+SUPERFLUOUS_ObejctModifiedEvent(mr, nov-2011) the following update()
     # is causing a ModifiedEvent to be fired, causing a modify change to be 
     # logged (while this workflow change should be just that).
     super(WorkflowActionViewlet, self).update()
Exemplo n.º 16
0
 def action_message(self):
     if self._can_sign_document(None):
         return _("Please confirm that you wish to sign" " this document")
     elif self._can_review_signature(None):
         return _(u"You have already signed this document")
     else:
         return _(u"You may not sign this document")
Exemplo n.º 17
0
class Login(LoginBase):
    class ILoginForm(interface.Interface):
        login = schema.TextLine(
            title=_("label_login_form_username", default=u"Username"))
        password = schema.Password(
            title=_("label_login_form_password", default=u"Password"))
        camefrom = schema.TextLine(required=False)

    form_fields = form.Fields(ILoginForm)
    form_fields["camefrom"].custom_widget = widgets.HiddenTextWidget
    form_name = _("login_form_title", default=u"Login")

    def __call__(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            workspace = get_application()["workspace"]
            self.request.response.redirect(absoluteURL(workspace,
                                                       self.request))
        return super(Login, self).__call__()

    @form.action(_("label_login_form_login", default=u"Login"), name="login")
    def handle_login(self, action, data):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            self.status = _(u"Invalid account credentials")
        else:
            if data.get("camefrom", None) and data.get("camefrom").strip():
                camefrom = data["camefrom"].strip()
            else:
                camefrom = absoluteURL(get_application(), self.request)
            self.status = _("You are now logged in")
            self.request.response.redirect(camefrom)

    def update(self):
        self.form_fields["camefrom"].field.default = self.request.get(
            "camefrom")
        super(Login, self).update()
Exemplo n.º 18
0
 def action_message(self):
     if self._can_sign_document(None):
         return _("Please confirm that you wish to sign"
             " this document")
     elif self._can_review_signature(None):
         return _(u"You have already signed this document")
     else:
         return _(u"You may not sign this document")
Exemplo n.º 19
0
def login_exists(login):
    session = Session()
    users = session.query(domain.User).filter(domain.User.login == login).all()
    if len(users) == 0:
        return False
    else:
        print _(u"Error : That login exists already")
        return True
Exemplo n.º 20
0
def validate_recurring_sittings(action, data, context, container):
    """Validate recurring sittings.

    This validator determines the sittings that will be created and
    confirms the validity of them.
    """

    start = data.get("start_date")
    end = data.get("end_date")
    weekdays = data.get("weekdays")
    monthly = data.get("monthly")
    repeat = data.get("repeat")
    repeat_until = data.get("repeat_until")
    exceptions = data.get("exceptions", ())
    
    session = Session()
    group_id = container.__parent__.group_id
    group = session.query(domain.Group).get(group_id)
    
    errors = []
    if weekdays or monthly:
        # this should be an invariant, but due to formlib's requirement
        # that invariant methods pertain to a single schema, it's not
        # possible
        if repeat_until is not None and repeat_until < start.date():
            #session.close()
            return [Invalid(
                _(u"If recurrence is limited by date, it "
                  "must lie after the starting date"),
                "repeat_until")]

        # verify that dates do not violate group's end date
        for date in generate_recurring_sitting_dates(
            start.date(), repeat, repeat_until, weekdays, monthly, exceptions):
            if group.end_date is not None and date > group.end_date:
                errors.append(Invalid(
                        _(u"One or more events would be scheduled for $F, which is "
                            "after the scheduling group's end date",
                            mapping={"F":datetimedict.fromdate(date)}),
                        "repeat" if repeat else "repeat_until"))
                break
            event_data = {
                "start_date": datetime.datetime(
                    date.year, date.month, date.day, start.hour, start.minute),
                "end_date": datetime.datetime(
                    date.year, date.month, date.day, end.hour, end.minute),
                }
            errors.extend(validate_non_overlapping_sitting(
                action, event_data, context, container,
                "weekdays" if weekdays else "monthly"))
            if errors:
                break
            errors.extend(validate_venues(
                action, data, context, container))
            if errors:
                break
    return logged_errors(errors, "validate_recurring_sittings")
Exemplo n.º 21
0
 def change_password(self, action, data):
     password = data.get("password", "")
     confirm_password = data.get("confirm_password", "")
     if password:
         if password != confirm_password:
             self.status = _("Password confirmation failed")
             return
         self.user._password = password
     self.status = _("Password changed")
Exemplo n.º 22
0
def login_exists(login):
    session = Session()
    users = session.query(domain.User).filter(
                    domain.User.login==login).all()
    if len(users) == 0:
        return False
    else:
        print _(u"Error : That login exists already")
        return True
Exemplo n.º 23
0
 def change_password(self, action, data):
     password = data.get("password", "")
     confirm_password = data.get("confirm_password", "")
     if password:
         if password != confirm_password:
             self.status = _("Password confirmation failed")
             return
         self.user._password = password
     self.status = _("Password changed")
Exemplo n.º 24
0
class Search(form.PageForm, browser.BungeniBrowserView):
    action_method="get"
    template = namedtemplate.NamedTemplate("alchemist.form")
    form_fields = form.FormFields(interfaces.ISearchRequest)
    form_fields["search"].custom_widget = SearchTextWidget
    form_fields["type"].custom_widget = MultiCheckBoxWidget
    #form_fields["group"].custom_widget = MultiCheckBoxWidget
    form_name = _(u"Bungeni Search")
    form_description = _(u"Search Documents in Bungeni")
    show_results = False

    def __init__(self, context, request):
        super(Search, self).__init__(context, request)

    def setUpWidgets(self, ignore_request=False):
        self.widgets = form.setUpInputWidgets(
            self.form_fields, self.prefix, self.context, self.request,
            ignore_request=ignore_request,
            )

    def widget_groups(self):
        wdgt_groups = OrderedDict()
        wdgt_groups["search_text"] = [ self.widgets.get("search") ]
        wdgt_groups["advanced_opts"] = [ widget for widget in self.widgets if
            widget.context.getName() != "search" ]
        return wdgt_groups

    def legends(self):
        return { "advanced_opts": _("advanced options") }

    @form.action(_(u"Search"), name="execute-search")
    def handle_search(self, action, data):
        self.show_results = True
        user_roles = (
            common.get_request_context_roles(self.request) +
            common.get_workspace_roles() + ["bungeni.Anonymous"])
        data["role"] = list(set(user_roles))
        data["page"] = self.request.form.get("page", 1)
        self.search_results = execute_search(data, self.prefix, 
            self.request, self.context)
        self.status = _("Searched for '${search_string}' and found ${count} "
            "items. Searched in ${search_types}.", 
            mapping={ 
                "search_string": data.get("search") or _("everything"), 
                "count": self.search_results.get("total"),
                "search_types": get_search_types(data.get("type")),
            }
        )

    def validate(self, action, data):
        return form.getWidgetsData(self.widgets, self.prefix, data)
    
    def __call__(self):
        need("search-js")
        need("search-css")
        return super(Search, self).__call__()
Exemplo n.º 25
0
 def handle_login(self, action, data):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         self.status = _(u"Invalid account credentials")
     else:
         if data.get("camefrom", None) and data.get("camefrom").strip():
             camefrom = data["camefrom"].strip()
         else:
             camefrom = absoluteURL(get_application(), self.request)
         self.status = _("You are now logged in")
         self.request.response.redirect(camefrom)
Exemplo n.º 26
0
    class IDateRangeSchema(interface.Interface):
        range_start_date = schema.Date(
            title=_(u"From"),
            description=_(u"Leave blank or set lower limit"),
            required=False)

        range_end_date = schema.Date(
            title=_(u"To"),
            description=_(u"Leave blank or set upper limit"),
            required=False)
Exemplo n.º 27
0
 def handle_login(self, action, data):
     if IUnauthenticatedPrincipal.providedBy(self.request.principal):
         self.status = _(u"Invalid account credentials")
     else:
         if data.get("camefrom", None) and data.get("camefrom").strip():
             camefrom = data["camefrom"].strip()
         else:
             camefrom = absoluteURL(get_application(), self.request)
         self.status = _("You are now logged in")
         self.request.response.redirect(camefrom)
Exemplo n.º 28
0
class SignOpenDocumentForm(PageForm):
    """Provides a form to allow signing of a document open for signatures
    """
    form_template = NamedTemplate("alchemist.form")
    template = ViewPageTemplateFile("templates/sign-open-document.pt")
    form_fields = formlib.form.Fields()

    @property
    def unproxied(self):
        return removeSecurityProxy(self.context)

    @property
    def action_message(self):
        if self._can_sign_document(None):
            return _("Please confirm that you wish to sign" " this document")
        elif self._can_review_signature(None):
            return _(u"You have already signed this document")
        else:
            return _(u"You may not sign this document")

    def _can_sign_document(self, action):
        return self.unproxied.signatory_feature.can_sign(self.context)

    def _can_review_signature(self, action):
        return self.unproxied.signatory_feature.is_signatory(self.context)

    def redirect_to_review(self):
        self.request.response.redirect("./signatory-review")

    def nextURL(self):
        return url.absoluteURL(self.context, self.request)

    @formlib.form.action(_(u"Sign Document"),
                         name="sign_document",
                         condition=_can_sign_document)
    def handle_sign_document(self, action, data):
        self.unproxied.signatory_feature.sign_document(self.context)
        self.request.response.redirect(self.nextURL())

    @formlib.form.action(_(u"Review Signature"),
                         name="review_signature",
                         condition=_can_review_signature)
    def handle_review_signature(self, action, data):
        self.redirect_to_review()

    @formlib.form.action(_(u"Cancel"),
                         name="cancel",
                         validator=ui.null_validator)
    def handle_cancel(self, action, data):
        self.request.response.redirect(self.nextURL())

    def __call__(self):
        if self._can_review_signature(None):
            self.redirect_to_review()
        return super(SignOpenDocumentForm, self).__call__()
Exemplo n.º 29
0
def validate_chamber_dates(action, data, context, container):
    """Chambers start must be after start of the Legislature. 
    The start and end date of *chambers of same type* may not overlap.
    """
    errors = []
    start_date = data["start_date"]
    end_date = data.get("end_date")
    sub_type = data["sub_type"]
    if interfaces.IChamber.providedBy(context):
        chamber = context
    else:
        chamber = None
    
    # whether uni- or bicameral, chamber dates may NOT overlap with those of 
    # another chamber of the SAME TYPE
    
    def get_others_overlapping_date(chamber, date):
        return [ result for result in 
            queries.validate_date_in_interval(chamber, domain.Chamber, date)
            if result.sub_type == sub_type ]
    
    legislature = capi.legislature
    if start_date:
        for res in get_others_overlapping_date(chamber, start_date):
            errors.append(Invalid(
                    _("Start date overlaps with (%s)") % res.short_name, 
                    "start_date"))
        if start_date < legislature.start_date:
            errors.append(Invalid(
                    _("Start date preceeds legislature start (%s)") % (
                        legislature.start_date), 
                    "start_date"))
    
    if end_date:
        for res in get_others_overlapping_date(chamber, end_date):
            errors.append(
                Invalid(_("End date overlaps with (%s)") % res.short_name, 
                    "end_date"))
        if legislature.end_date:
            if end_date > legislature.end_date:
                errors.append(Invalid(
                        _("End date later legislature end (%s)") % (
                            legislature.end_date), 
                        "end_date"))
    
    if chamber is None:
        results = queries.validate_open_interval(chamber, domain.Chamber)
        for result in results:
            if result.sub_type == sub_type:
                errors.append(Invalid(
                        _("Another chamber is not yet dissolved (%s)") % (
                            result.short_name),
                        "end_date"))
    
    return logged_errors(errors, "validate_chamber_dates")
Exemplo n.º 30
0
    class IChangePasswordForm(interface.Interface):
        old_password = schema.Password(title=_(u"Old password"), required=True)
        password = schema.Password(title=_(u"New password"), required=True)
        confirm_password = schema.Password(title=_(u"Confirm new password"),
                                           required=True)

        @interface.invariant
        def check_old_password(self):
            if not get_login_user().checkPassword(self.old_password):
                raise interface.Invalid(_("Old password incorrect"),
                                        "old_password")
Exemplo n.º 31
0
 def generate_preview(self):
     sitting = removeSecurityProxy(self.context)
     sittings = [data.ExpandedSitting(sitting)]
     generator = generators.ReportGeneratorXHTML(
         self.get_report_template_path())
     #!+TAGS(mb, Feb-2013) Deprecate with tags. Configure as wf/feature.
     if "minutes" in sitting.status:
         title = generator.title = _(u"Sitting Votes and Proceedings")
     else:
         title = generator.title = _(u"Order of the day")
     generator.context = data.ReportContext(sittings=sittings, title=title)
     return generator.generate_report(self.request)
Exemplo n.º 32
0
def main():
    check_login = True
    while check_login:
        login = raw_input(_("Enter admin login name "))
        check_login = login_exists(login)
    check_pass = False
    while not check_pass:
        password = raw_input(_("Enter password "))
        confirm_password = raw_input(_("Confirm password "))
        check_pass = check_password(password, confirm_password)
    email_address = raw_input(_("Enter Email Address "))
    add_admin(login, password, email_address)
Exemplo n.º 33
0
def validate_email_availability(action, data, context, container):
    session = Session()
    users = session.query(domain.User
        ).filter(domain.User.email==data.get("email", ""))
    if users.count() > 1:
        return [Invalid(_(u"Email already taken!"), "email")]
    if context:
        if users.count() == 1 and users.first().user_id != context.user_id:
            return [Invalid(_(u"Email already taken!"), "email")]
    elif users.count() > 0:
        return [Invalid(_(u"Email already taken!"), "email")]
    return []
Exemplo n.º 34
0
def main():
    check_login = True
    while check_login:
        login = raw_input(_("Enter admin login name "))
        check_login = login_exists(login)
    check_pass = False
    while not check_pass:
        password = raw_input(_("Enter password "))
        confirm_password = raw_input(_("Confirm password "))
        check_pass = check_password(password, confirm_password)
    email_address = raw_input(_("Enter Email Address "))
    add_admin(login, password, email_address)
Exemplo n.º 35
0
 def verbose_title(self):
     context = _merged(self.context)
     sitting_title = _(
         "verbose_sitting_title",
         default=u"Sitting of ${group_name} @ ${sitting_venue}",
         mapping={
             "group_name":
             IDCDescriptiveProperties(context.group).title,
             "sitting_venue":
             (IDCDescriptiveProperties(context.venue).title
              if context.venue else translate(_(u"no venue")))
         })
     return translate(sitting_title)
Exemplo n.º 36
0
 def verbose_title(self):
     context = _merged(self.context)
     sitting_title = _("verbose_sitting_title", 
         default=u"Sitting of ${group_name} @ ${sitting_venue}",
         mapping = {
             "group_name": IDCDescriptiveProperties(context.group).title,
             "sitting_venue": (
                 IDCDescriptiveProperties(context.venue).title 
                 if context.venue else translate(_(u"no venue"))
             )
         }
     )
     return translate(sitting_title)
Exemplo n.º 37
0
class DateFilterWidget(form.PageForm):

    macro_template = NamedTemplate("alchemist.form")
    template = ViewPageTemplateFile("templates/date-input-search.pt")

    def __init__(self, context, request, table_id, field_id):
        self.prefix = "form_%s_%s" % (table_id, field_id)
        super(DateFilterWidget, self).__init__(context, request)

    class IDateRangeSchema(interface.Interface):
        range_start_date = schema.Date(
            title=_(u"From"),
            description=_(u"Leave blank or set lower limit"),
            required=False)

        range_end_date = schema.Date(
            title=_(u"To"),
            description=_(u"Leave blank or set upper limit"),
            required=False)

    macro_template = NamedTemplate("alchemist.form")
    template = ViewPageTemplateFile("templates/date-input-search.pt")
    form_fields = form.Fields(IDateRangeSchema, render_context=True)
    form_fields["range_start_date"].custom_widget = DateWidget
    form_fields["range_end_date"].custom_widget = DateWidget

    def setUpWidgets(self, ignore_request=False, cookie=None):
        class context:
            range_start_date = None
            range_end_date = None

        self.adapters = {
            self.IDateRangeSchema: context,
        }
        self.widgets = form.setUpWidgets(self.form_fields,
                                         self.prefix,
                                         self.context,
                                         self.request,
                                         form=self,
                                         adapters=self.adapters,
                                         ignore_request=True)

    @form.action(_(u"Ok"), name="ok")
    def handle_ok(self, action, data):
        #Handled by Javascript
        pass

    @form.action(_(u"Clear"), name="clear")
    def handle_clear(self, action, data):
        #Handled by Javascript
        pass
Exemplo n.º 38
0
class DefaultFileInputWidget(FileWidget):
    """
    This is the default FileInputWidget implementation, 
    other FileInputWidget types extend this
    """

    _missing = u""

    @property
    def update_action_name(self):
        return self.name + ".up_action"

    @property
    def upload_name(self):
        return self.name.replace(".", "_") + "_file"

    def empty_field(self):
        return self._data is None

    def _getFieldInput(self, name):
        return self.request.form.get(name, self._missing)

    def _getFormInput(self):
        """extract the input value from the submitted form """
        return (self._getFieldInput(self.update_action_name),
                self._getFieldInput(self.upload_name))

    def _toFieldValue(self, (update_action, upload)):
        """convert the input value to an value suitable for the field.
        Check the update_action if we should leave the data alone,
        delete or replace it.
        """
        if update_action == u"update":
            if upload is None or upload == "":
                if self._data is None:
                    return self.context.missing_value
                else:
                    raise ConversionError(
                        _("Form upload is not a file object"))
            try:
                seek = upload.seek
                read = upload.read
            except AttributeError, e:
                raise ConversionError(_("Form upload is not a file object"), e)
            else:
                seek(0)
                data = read()
                if data or getattr(upload, "filename", ""):
                    return data
                else:
                    return self.context.missing_value
Exemplo n.º 39
0
 def columns(self):
     return [
         column.GetterColumn(title=_("user name"), getter=lambda i, f: i.get("title")),
         column.GetterColumn(
             title=_("assigned"),
             getter=lambda i, f: i,
             cell_formatter=lambda g, i, f: '<input type="checkbox" name="%s" %s %s/>'
             % (
                 i["name"],
                 i["is_assigned"] and ' checked="checked"' or "",
                 not i["editable"] and ' disabled="disabled"' or "",
             ),
         ),
     ]
Exemplo n.º 40
0
 def columns(self):
     return [
         column.GetterColumn(
             title=_("file_column_file_link", default="file"),
             getter=lambda i,f: "%s" % (i.title),
             cell_formatter=lambda g,i,f: '<a href="%s/files/obj-%d">%s</a>' 
                 % (f.url, i.attachment_id, g)),
         column.GetterColumn(
             title=_("file_column_status", default="status"), 
             getter=lambda i,f: i.status),
         column.GetterColumn(
             title=_("file_column_last_modified", default="modified"), 
             getter=lambda i,f: self.date_formatter.format(i.status_date)),
     ]
Exemplo n.º 41
0
 def columns(self):
     return [
         column.GetterColumn(title=_("file_column_file_link",
                                     default="file"),
                             getter=lambda i, f: "%s" % (i.title),
                             cell_formatter=lambda g, i, f:
                             '<a href="%s/files/obj-%d">%s</a>' %
                             (f.url, i.attachment_id, g)),
         column.GetterColumn(title=_("file_column_status",
                                     default="status"),
                             getter=lambda i, f: i.status),
         column.GetterColumn(
             title=_("file_column_last_modified", default="modified"),
             getter=lambda i, f: self.date_formatter.format(i.status_date)),
     ]
Exemplo n.º 42
0
 def handle_reset(self, action, data):
     password = data.get("password", "")
     confirm_password = data.get("confirm_password", "")
     
     if password.__class__ is not object:
         if password != confirm_password:
             self.status = _(u"Password confirmation failed!")
             return
         
     if password and password == confirm_password and self.link:
         if not self.link.expired():
             user = self.link.user
             user._password = password
             self.link.expiration_date = datetime.datetime.now()
             self.status = _(u"Password successfully reset!")
Exemplo n.º 43
0
def transitions():
    return [
        workflow.Transition(
            title="Create",
            source=None,
            destination="new",
            trigger=iworkflow.AUTOMATIC,
        ),
        workflow.Transition(title=_(u"Submit to Clerk"),
                            source="new",
                            destination="pending"),
        workflow.Transition(title=_(u"Schedule"),
                            source="pending",
                            destination="scheduled")
    ]
Exemplo n.º 44
0
    def handle_reset(self, action, data):
        password = data.get("password", "")
        confirm_password = data.get("confirm_password", "")

        if password.__class__ is not object:
            if password != confirm_password:
                self.status = _(u"Password confirmation failed!")
                return

        if password and password == confirm_password and self.link:
            if not self.link.expired():
                user = self.link.user
                user._password = password
                self.link.expiration_date = datetime.datetime.now()
                self.status = _(u"Password successfully reset!")
Exemplo n.º 45
0
 def get_js(self):
     pagedate = datetime.date.today()
     if self.maxDate < pagedate:
         pagedate = self.maxDate
     if ((type(self._data) == datetime.date) or
         (type(self._data) == datetime.datetime)
     ):
         pagedate = self._data
     calendar = self.request.locale.dates.calendars["gregorian"]
     month = _(u"Choose Month")
     year = _(u"Enter Year")
     submit = _("OK")
     cancel = _(u"Cancel")
     invalidYear = _(u"Please enter a valid year")
     months_short = self.jstr(calendar.getMonthAbbreviations())
     months_long = self.jstr(calendar.getMonthNames())
     w_day_1char = self.jstr(
         [dn[:1] for dn in calendar.getDayAbbreviations()])
     w_day_short = self.jstr(
         [dn[:2] for dn in calendar.getDayAbbreviations()])
     w_day_medium = self.jstr(calendar.getDayAbbreviations())
     w_day_long = self.jstr(calendar.getDayNames())
     return self.js_template % {
         "name": self.field_name,
         "sel_day": self._day_name,
         "sel_month": self._month_name,
         "sel_year": self._year_name,
         "txt_date": self.date_name,
         "mindate": self.minDate.strftime("%m/%d/%Y"),
         "maxdate": self.maxDate.strftime("%m/%d/%Y"),
         "pagedate": pagedate.strftime("%m/%Y"),
         "months_short": months_short,
         "months_long": months_long,
         "w_day_1char": w_day_1char,
         "w_day_short": w_day_short,
         "w_day_medium": w_day_medium,
         "w_day_long": w_day_long,
         "month": translate(
             str(month), domain="bungeni", context=self.request),
         "year": translate(
             str(year), domain="bungeni", context=self.request),
         "submit": translate(
             str(submit), domain="bungeni", context=self.request),
         "cancel": translate(
             str(cancel), domain="bungeni", context=self.request),
         "invalidYear": translate(
             str(invalidYear), domain="bungeni", context=self.request)
     }
Exemplo n.º 46
0
 def load_configuration(self):
     """Process report template for configuration
     """
     if os.path.exists(self.report_template_path):
         template_file = open(self.report_template_path)
         file_string = template_file.read()
         self.report_template = etree.fromstring(file_string)
         template_file.close()
         
         self.title = get_config(self.report_template, "title", self.title)
         self.language = get_config(self.report_template, "language",
             get_default_language()
         )
         coverage_text = get_config(self.report_template, "length")
         if coverage_text is not None:
             self.coverage = report_tools.compute_hours(coverage_text)
         drop_element(
             self.report_template.find("{%s}config" % BUNGENI_REPORTS_NS)
         )
     else:
         raise ReportException(
             _(u"report-template-missing",
                 default=u"Report template file does not exist at ${path}",
                 mapping={"path": self.report_template_path}
             )
         )
Exemplo n.º 47
0
 def handle_publish(self, action, data):
     self.generated_content = self.generate_content(data)
     if IWorkspaceScheduling.providedBy(self.request):
         if not hasattr(self.context, "group_id"):
             context_group_id = ISchedulingContext(self.context).group_id
         else:
             context_group_id = self.context.group_id
     else:
         # get the chamber id
         context_group_id = get_chamber_for_context(self.context).group_id
     report = domain.Report(
         title=self.title,
         start_date=self.start_date,
         end_date=self.end_date,
         body=self.generated_content,
         owner_id=get_login_user().user_id, # !+GROUP_AS_OWNER
         language=self.language,
         group_id=context_group_id
     )
     session = Session()
     session.add(report)
     session.flush()
     # requires self db id to have been updated
     report.on_create() 
     notify(ObjectCreatedEvent(report))
     self.status = _(u"Report has been processed and saved")
     return self.template()
Exemplo n.º 48
0
 def form_description(self):
     if self.is_translation:
         # !+HEAD_DOCUMENT_ITEM(mr, sep-2011)
         language = get_language_by_name(self.context.head.language)["name"]
         return _(u"edit_translation_help",
                  default=u"The original $language version is shown on the left",
                  mapping={"language": language})
Exemplo n.º 49
0
 def update(self):
     context = proxy.removeSecurityProxy(self.context)
     columns = bungeni.alchemist.ui.setUpColumns(context.domain_model)
     columns.append(
         column.GetterColumn(title=_(u"Actions"), getter=viewEditLinks))
     self.columns = columns
     super(ContainerListing, self).update()
Exemplo n.º 50
0
def add_empty_listing_node(listing_node):
    """add an empty node to template output
    """
    no_items_tag = "p"
    no_items_node = etree.Element(no_items_tag)
    no_items_node.text = translate(_(u"No items found"))

    # add to previous element of listing node - then drop it
    prev_element = listing_node.getprevious()
    add_after = None
    if prev_element:
        drop_element(listing_node)
        add_after = prev_element
    else:
        if listing_node.tag in ["tr", "tbody"]:
            parent_table = None
            for prn in listing_node.iterancestors("table"):
                parent_table = prn
                break
            if parent_table is not None:
                # assumption: there's a title element
                add_after = parent_table.getprevious()
                drop_element(parent_table)
    if add_after is not None:
        add_after.addnext(no_items_node)
Exemplo n.º 51
0
    def validate_unique(self, action, data):
        """Validate unique.
        
        Since this class always adds a single object, we can safely
        return an empty list of errors.
        """
        errors = []
        dm = removeSecurityProxy(self.domain_model)

        # find unique columns in data model.. TODO do this statically
        mapper = sa.orm.class_mapper(dm)
        ucols = list(unique_columns(mapper))

        # query out any existing values with the same unique values,
        session = Session()
        # find data matching unique columns
        ctx = removeSecurityProxy(self.context)
        ctx_is_dm_instance = isinstance(ctx, dm)  # !+when is this not true?
        for key, col in ucols:
            if key in data:
                # on edit ignore new value if its the same as the previous value
                if ctx_is_dm_instance and data[key] == getattr(ctx, key, None):
                    continue
                value = session.query(dm).filter(col == data[key]).count()
                if not value:
                    continue
                errors.append(
                    self.set_widget_error(
                        key, _(u"A record with this value already exists")))
        return errors
Exemplo n.º 52
0
 def validate_unique(self, action, data):
     """Validate unique.
     
     Since this class always adds a single object, we can safely
     return an empty list of errors.
     """
     errors = []
     dm = removeSecurityProxy(self.domain_model)
     
     # find unique columns in data model.. TODO do this statically
     mapper = sa.orm.class_mapper(dm)
     ucols = list(unique_columns(mapper))
     
     # query out any existing values with the same unique values,
     session = Session()
     # find data matching unique columns
     ctx = removeSecurityProxy(self.context)
     ctx_is_dm_instance = isinstance(ctx, dm) # !+when is this not true?
     for key, col in ucols:
         if key in data:
             # on edit ignore new value if its the same as the previous value
             if ctx_is_dm_instance and data[key] == getattr(ctx, key, None):
                 continue
             value = session.query(dm).filter(col == data[key]).count()
             if not value:
                 continue
             errors.append(self.set_widget_error(key,
                     _(u"A record with this value already exists")))
     return errors
Exemplo n.º 53
0
 def handle_preview(self, action, data):
     """Generate preview of the report
     """
     self.show_preview = True
     self.generated_content = self.generate_content(data)
     self.status = _(u"See the preview of the report below")
     return self.template()
Exemplo n.º 54
0
class CalendarSubMenuItem(BrowserSubMenuItem):
    title = _(u"label_calendar_context", default=u"Calendar:")
    submenuId = "context_calendar"
    order = 10

    def __new__(cls, context, request):
        if context.get_group() is not None:
            return object.__new__(cls, context, request)

    def __init__(self, context, request):
        BrowserSubMenuItem.__init__(self, context, request)
        self.context = context
        self.url = url.absoluteURL(context, request)

    @property
    def extra(self):
        return {"id": self.id, "stateTitle": self.context.label}

    @property
    def description(self):
        return u""

    @property
    def action(self):
        return self.url

    def selected(self):
        return False
Exemplo n.º 55
0
 def title_member(self):
     context = _merged(self.context)
     mp_user = None # !+ generalize to all group_member types
     try:
         mp_user = Session().query(domain.Member).filter(
             domain.Member.user_id == context.user_id
         ).one()
     except NoResultFound:
         #this user has no associated MP record
         pass
     except MultipleResultsFound:
         # this should not happen
         log.error("Multiple MP objects found for : %s", context.__str__())
     finally:
         if mp_user is None:
             return self.title
     if mp_user.representation_geo or mp_user.representation_sig:
         return _("member_title_with_representation",
             default=u"Member of Parliament for ${representation}"
             " (${member})",
             mapping={"representation": ", ".join([
                     mp_user.representation_geo, mp_user.representation_sig]),
                 "member": self.title
             }
         )
     return self.title
Exemplo n.º 56
0
def text_snippet(text, length):
    """Generates a text snippet no longer than `length` from `text`
    
    >>> from bungeni.ui.utils.misc import text_snippet
    >>> text_snippet("", 10)
    u'No Text'
    >>> text_snippet("Some Text", 10)
    u'Some Text'
    >>> text_snippet("Some Text", 5)
    u'Some'
    >>> text_snippet("SomeText", 5)
    u'SomeT'
    >>> text_snippet("non ascii and spaces ĆýĊĔ", 30)
    u'non ascii and spaces \xc4\x86\xc3\xbd\xc4\x8a\xc4\x94'
    >>> text_snippet("non ascii and spaces ĆýĊĔ", 20)
    u'non ascii and spaces'
    >>> text_snippet("<div>HTML</div> Content", 10)
    u'HTML'
    >>> text_snippet("<div>HTML</div> Content", 20)
    u'HTML Content'

    """
    if not len(text):
        return _(u"No Text")
    html_body = html.fromstring(text)
    html_text = html.tostring(html_body, method="text", encoding=unicode)
    title = html_text[0:length]
    if len(title) == length:
        if (html_text[length] not in (string.whitespace + string.punctuation)):
            parts = title.split()
            if len(parts) > 1:
                parts.pop()
                title = u" ".join(parts).strip()
    return title.strip()
Exemplo n.º 57
0
 def handle_diff_version(self, action, data):
     self.status = _("Displaying differences")
     selected_audit_ids = sorted(ui.getSelected(self.selection_column, self.request))
     if len(selected_audit_ids) not in (1, 2):
         self.status = _("Select one or two items to show differences")
         return
     source = self.get_version_change(selected_audit_ids[0])
     try:
         target = self.get_version_change(selected_audit_ids[1])
     except IndexError:
         target = removeSecurityProxy(self.context)
     diff_view = DiffView(source, target, self.request)
     self.diff_view = diff_view(
         *filter(IIModelInterface.providedBy, interface.providedBy(self.context)))
     log.debug("handle_diff_version: source=%s target=%s \n%s",
                     source, target, self.diff_view)
Exemplo n.º 58
0
 def title(self):
     context = _merged(self.context)
     return "%s %s, %s %s" % ( 
             self.translate(context.group, "short_name"), 
             context.start_date.strftime('%Y-%m-%d, %H:%M'), 
             _(u"to"), 
             context.end_date.strftime('%H:%M'))
Exemplo n.º 59
0
 def handle_new_version(self, action, data):
     # !+ change_data not yet initialized for version requests
     change_data = IAnnotations(self.request)["change_data"] = {}
     change_data["note"] = data["commit_message"]
     change_data["procedure"] = "m"
     version.create_version(self.context)
     self.status = _("New Version Created")