class BaseForm(object): name_template = "%sForm" template = namedtemplate.NamedTemplate("alchemist.form") additional_form_fields = form.Fields() status = None mode = None @property def domain_model(self): return removeSecurityProxy(self.context).__class__ @property def model_interface(self): # !+ does this give the the correct interface? return tuple(interface.implementedBy(self.domain_model))[0] def get_form_fields(self): return setUpFields(self.domain_model, self.mode) def form_fields(): doc = "The prepared fields for self.mode." def fget(self): try: fields = self.__dict__["form_fields"] except KeyError: fields = self.__dict__["form_fields"] = self.get_form_fields() return fields def fset(self, form_fields): self.__dict__["form_fields"] = form_fields return locals() form_fields = property(**form_fields())
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__()
class SerializationManager(form.PageForm, browser.BungeniBrowserView): template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.FormFields(ISerializationManager) form_name = _(u"Batch Serialization") form_description = _( u"This will serialize all workflowable objects " "in Bungeni to XML. You can limit by type below or choose " "*All types* to serialize everything.") @form.action(_(u"Serialize Items"), name="serialize-objects") def handle_serialize_objects(self, action, data): item_count = batch_serialize(data.get("object_type")) self.status = _("Sent ${item_count} items for serialization", mapping={"item_count": item_count})
class Search(form.PageForm, browser.BungeniBrowserView): zope.interface.implements(interfaces.ISearchResults) action_method = "get" template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.FormFields(interfaces.ISearchRequest) 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, show_results=True): if show_results: zope.interface.declarations.alsoProvides(context, interfaces.ISearchResults) 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, ) @form.action(_(u"Search"), name="execute-search") def handle_search(self, action, data): self.show_results = True #data["role"] = \ # common.get_context_roles(self.context, self.request.principal) + \ # common.get_workspace_roles() + ["bungeni.Anonymous"] 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-css") return super(Search, self).__call__()
class MediaPath(form.EditForm): class IEditMediaPathForm(interface.Interface): web_optimised_video_path = schema.URI( title=u'Web Optimized Media URL', description=u'URL of the Media File', required=True) audio_only_path = schema.URI( title=u'Audio Only Media URL', description=u'URL of the Audio Only Media File', required=False) high_quality_video_path = schema.URI( title=u'High Quality Media URL', description=u'URL of High Quality Media File', required=False) template = namedtemplate.NamedTemplate('alchemist.form') form_fields = form.Fields(IEditMediaPathForm) def setUpWidgets(self, ignore_request=True): context = removeSecurityProxy(self.context).media_paths self.adapters = {self.IEditMediaPathForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, context, self.request, adapters=self.adapters, ignore_request=ignore_request) @form.action(_(u"Save")) def handle_save(self, action, data): trusted = removeSecurityProxy(self.context) if form.applyChanges(trusted.media_paths, self.form_fields, data, self.adapters): session = Session() session.add(trusted.media_paths) session.flush() self._next_url = absoluteURL(self.context, self.request) self.request.response.redirect(self._next_url) @form.action(_(u"Cancel")) def handle_cancel(self, action, data): self._next_url = absoluteURL(self.context, self.request) self.request.response.redirect(self._next_url)
class One2OneBase(core.DynamicFields): template = namedtemplate.NamedTemplate('alchemist.subform') def getDomainModel(self): return self.domain_model def getValue(self): value = getattr(self.context, self.property_name, None) if value is None: # create one on the fly return self.domain_model() return value @property def prefix(self): return self.property_name @property def model_schema(self): return list(interface.implementedBy(self.domain_model))[0]
class ReportingView(form.PageForm): """Reporting view base class. The context of the view is a scheduling context, which always relates to a principal group, e.g. 'Plenary'. A starting date must be specified, as well as a time span parameter, which can be one of the following: - Daily - Weekly The time span parameter is used as title and to generate canonical filenames and unique identification strings for publishing the reports, e.g. 'Daily agenda 2009/30/12' (agenda-daily-2009-30-12.pdf) It's not enforced that weeks begin on Mondays or any other particular day; a week is always 7 days. A report is a listing of sittings that take place in the defined period. For each sitting, the summary may be different depending on the type of report. The ``get_sittings`` method will fetch the relevant sittings. """ date = None display_minutes = None def __init__(self, context, request): super(ReportingView, self).__init__(context, request) if IGroupSitting.providedBy(context): self.date = datetime.date(context.start_date.year, context.start_date.month, context.start_date.day) ''' while not ISchedulingContext.providedBy(context): context = context.__parent__ if context is None: break; #raise RuntimeError( # "No scheduling context found.") if context is not None: self.scheduling_context = context''' class IReportingForm(interface.Interface): doc_type = schema.Choice( title=_(u"Document Type"), description=_(u"Type of document to be produced"), values=[ 'Order of the day', 'Proceedings of the day', 'Weekly Business', 'Questions of the week' ], required=True) date = schema.Date( title=_(u"Date"), description=_(u"Choose a starting date for this report"), required=True) item_types = schema.List( title=u'Items to include', required=False, value_type=schema.Choice(vocabulary="Available Items"), ) bill_options = schema.List( title=u'Bill options', required=False, value_type=schema.Choice(vocabulary='Bill Options'), ) agenda_options = schema.List( title=u'Agenda options', required=False, value_type=schema.Choice(vocabulary='Agenda Options'), ) motion_options = schema.List( title=u'Motion options', required=False, value_type=schema.Choice(vocabulary='Motion Options'), ) question_options = schema.List( title=u'Question options', required=False, value_type=schema.Choice(vocabulary='Question Options'), ) tabled_document_options = schema.List( title=u'Tabled Document options', required=False, value_type=schema.Choice(vocabulary='Tabled Document Options'), ) note = schema.TextLine( title=u'Note', required=False, description=u'Optional note regarding this report') draft = schema.Choice( title=_(u"Include draft sittings"), description=_( u"Whether or not to include sittings still in draft"), values=['Yes', 'No'], required=True) template = namedtemplate.NamedTemplate('alchemist.form') form_fields = form.Fields(IReportingForm) form_fields['item_types'].custom_widget = horizontalMultiCheckBoxWidget form_fields['date'].custom_widget = SelectDateWidget form_fields['bill_options'].custom_widget = verticalMultiCheckBoxWidget form_fields['agenda_options'].custom_widget = verticalMultiCheckBoxWidget form_fields['motion_options'].custom_widget = verticalMultiCheckBoxWidget form_fields['question_options'].custom_widget = verticalMultiCheckBoxWidget form_fields[ 'tabled_document_options'].custom_widget = verticalMultiCheckBoxWidget odf_filename = None class IReportingForm2(interface.Interface): item_types = schema.List( title=u'Items to include', required=False, value_type=schema.Choice(vocabulary="Available Items"), ) bill_options = schema.List( title=u'Bill options', required=False, value_type=schema.Choice(vocabulary='Bill Options'), ) agenda_options = schema.List( title=u'Agenda options', required=False, value_type=schema.Choice(vocabulary='Agenda Options'), ) motion_options = schema.List( title=u'Motion options', required=False, value_type=schema.Choice(vocabulary='Motion Options'), ) question_options = schema.List( title=u'Question options', required=False, value_type=schema.Choice(vocabulary='Question Options'), ) tabled_document_options = schema.List( title=u'Tabled Document options', required=False, value_type=schema.Choice(vocabulary='Tabled Document Options'), ) note = schema.TextLine( title=u'Note', required=False, description=u'Optional note regarding this report') template = namedtemplate.NamedTemplate('alchemist.form') form_fields2 = form.Fields(IReportingForm2) form_fields2['item_types'].custom_widget = horizontalMultiCheckBoxWidget form_fields2['bill_options'].custom_widget = verticalMultiCheckBoxWidget form_fields2['agenda_options'].custom_widget = verticalMultiCheckBoxWidget form_fields2['motion_options'].custom_widget = verticalMultiCheckBoxWidget form_fields2[ 'question_options'].custom_widget = verticalMultiCheckBoxWidget form_fields2[ 'tabled_document_options'].custom_widget = verticalMultiCheckBoxWidget def setUpWidgets(self, ignore_request=False): if IGroupSitting.providedBy(self.context): class context: item_types = 'Bills' bill_options = 'Title' agenda_options = 'Title' question_options = 'Title' motion_options = 'Title' tabled_document_options = 'Title' note = None self.adapters = {self.IReportingForm2: context} self.widgets = form.setUpEditWidgets(self.form_fields2, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) elif ISchedulingContext.providedBy(self.context): class context: date = self.date or datetime.date.today() #time_span = TIME_SPAN.daily doc_type = 'Order of the day' item_types = 'Bills' bill_options = 'Title' agenda_options = 'Title' question_options = 'Title' motion_options = 'Title' tabled_document_options = 'Title' note = None draft = 'No' self.adapters = {self.IReportingForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) else: raise NotImplementedError def update(self): self.status = self.request.get('portal_status_message', '') super(ReportingView, self).update() set_widget_errors(self.widgets, self.errors) def validate(self, action, data): errors = super(ReportingView, self).validate(action, data) time_span = TIME_SPAN.daily if 'doc_type' in data: if data['doc_type'] == "Order of the day": time_span = TIME_SPAN.daily elif data['doc_type'] == "Proceedings of the day": time_span = TIME_SPAN.daily elif data['doc_type'] == "Weekly Business": time_span = TIME_SPAN.weekly elif data['doc_type'] == "Questions of the week": time_span = TIME_SPAN.weekly if 'date' in data: start_date = data['date'] else: start_date = self.date end_date = self.get_end_date(start_date, time_span) parliament = queries.get_parliament_by_date_range( self, start_date, end_date) session = queries.get_session_by_date_range(self, start_date, end_date) if parliament is None: errors.append( interface.Invalid( _(u"A parliament must be active in the period"), "date")) #elif session is None: # errors.append(interface.Invalid( # _(u"A session must be active in the period."), # "date")) return errors def process_form(self, data): if 'date' in data: self.start_date = data['date'] else: self.start_date = self.date time_span = TIME_SPAN.daily if 'doc_type' in data: self.doc_type = data['doc_type'] else: if self.display_minutes: self.doc_type = "Proceedings of the day" else: self.doc_type = "Order of the day" if self.doc_type == "Order of the day": time_span = TIME_SPAN.daily elif self.doc_type == "Weekly Business": time_span = TIME_SPAN.weekly elif self.doc_type == "Questions of the week": time_span = TIME_SPAN.weekly elif self.doc_type == "Proceedings of the day": time_span = TIME_SPAN.daily self.end_date = self.get_end_date(self.start_date, time_span) #Hack:Check if called on scheduling page or sitting page. todo : fix this if 'date' in data: self.sitting_items = self.get_sittings_items( self.start_date, self.end_date) self.single = "False" else: session = Session() self.sitting_items = [] st = self.context.sitting_id sitting = session.query(domain.GroupSitting).get(st) self.sitting_items.append(sitting) self.single = "True" self.item_types = data['item_types'] self.bill = False self.motion = False self.agenda = False self.question = False self.tabled_document = False self.bill_options = data['bill_options'] self.agenda_options = data['agenda_options'] self.motion_options = data['motion_options'] self.question_options = data['question_options'] self.note = data['note'] self.tabled_document_options = data['tabled_document_options'] for type in self.item_types: if type == 'Bills': self.bill_title = False self.bill_summary = False self.bill_text = False self.bill_owner = False self.bill_cosignatories = False for option in self.bill_options: if option == 'Title': self.bill_title = True elif option == 'Summary': self.bill_summary = True elif option == 'Text': self.bill_text = True elif option == 'Owner': self.bill_owner = True elif option == 'Cosignatories': self.bill_cosignatories = True self.bill = True elif type == 'Motions': self.motion_title = False self.motion_number = False self.motion_text = False self.motion_owner = False for option in self.motion_options: if option == 'Title': self.motion_title = True elif option == 'Number': self.motion_number = True elif option == 'Text': self.motion_text = True elif option == 'Owner': self.motion_owner = True self.motion = True elif type == 'Agenda Items': self.agenda_title = False self.agenda_text = False self.agenda_owner = False for option in self.agenda_options: if option == 'Title': self.agenda_title = True elif option == 'Text': self.agenda_text = True elif option == 'Owner': self.agenda_owner = True self.agenda = True elif type == 'Tabled Documents': self.tabled_document_title = False self.tabled_document_text = False self.tabled_document_owner = False self.tabled_document_number = False for option in self.tabled_document_options: if option == 'Title': self.tabled_document_title = True elif option == 'Text': self.tabled_document_text = True elif option == 'Owner': self.tabled_document_owner = True elif option == 'Number': self.tabled_document_number = True self.tabled_document = True elif type == 'Questions': self.question_title = False self.question_number = False self.question_text = False self.question_owner = False #self.question_response = False self.question_type = False for option in self.question_options: if option == 'Title': self.question_title = True elif option == 'Number': self.question_number = True elif option == 'Text': self.question_text = True elif option == 'Owner': self.question_owner = True #elif option == 'Response': # self.question_response = True elif option == 'Type': self.question_type = True self.question = True #import pdb; pdb.set_trace() '''for item in self.sitting_items: if item.item_schedule.item.type in item_types: opt = item.type + '_option' for option in data[opt]: item.options[option] = True else: self.sitting_items.remove(item) ''' '''if self.display_minutes: if data['draft'] == 'No': for sitting in self.sitting_items: items = [] for item in sitting.item_schedule: if item.item_status not in ["draft"]: items.append(item) sitting.item_schedule = items''' if 'draft' in data: sitting_items = [] for sitting in self.sitting_items: if data["draft"] == 'No': if sitting.status in [ "published-agenda", "published-minutes" ]: sitting_items.append(sitting) elif data["draft"] == 'Yes': if sitting.status in [ "published-agenda", "draft-minutes", "published-minutes", "draft-agenda" ]: sitting_items.append(sitting) self.sitting_items = sitting_items if self.display_minutes: self.link = ui_url.absoluteURL( self.context, self.request) + '/votes-and-proceedings' else: self.link = ui_url.absoluteURL(self.context, self.request) + '/agenda' try: self.group = self.context.get_group() except: session = Session() self.group = session.query(domain.Group).get(self.context.group_id) if IGroupSitting.providedBy(self.context): self.back_link = ui_url.absoluteURL(self.context, self.request) + '/schedule' elif ISchedulingContext.providedBy(self.context): self.back_link = ui_url.absoluteURL(self.context, self.request) @form.action(_(u"Preview")) def handle_preview(self, action, data): self.process_form(data) #import pdb; pdb.set_trace() self.save_link = ui_url.absoluteURL(self.context, self.request) + "/save_report" self.body_text = self.result_template() #import pdb; pdb.set_trace() return self.main_result_template() def get_end_date(self, start_date, time_span): if time_span is TIME_SPAN.daily: return start_date + timedelta(days=1) elif time_span is TIME_SPAN.weekly: return start_date + timedelta(weeks=1) raise RuntimeError("Unknown time span: %s" % time_span)
class UnionWidget(BaseWidget): _field_index = None no_value_label = _('union_field_label-no_value', "Not specified") no_value_hint = _('union_field_hint-no_value', '') def loadValueFromRequest(self): field = self.context missing_value = field.missing_value value = self.request.form.get(self.name) try: value = int(value) except (TypeError, ValueError): value = missing_value else: if value >= len(field.fields): value = missing_value else: self._field_index = value # value should be an int index of the active field active = field.fields[value].bind(self.context) if zc.form.interfaces.IOptionField.providedBy(active): return active.getValue() widget = component.getMultiAdapter((active, self.request), IInputWidget) widget.required = widget.context.required = self.required widget.setPrefix(self.name) try: return widget.getInputValue() except WidgetInputError as e: # recast with our name and title self._error = WidgetInputError(self.context.__name__, self.label, e.errors) return missing_value template = namedtemplate.NamedTemplate('default') def render(self, value): # choices = ({selected, identifier, widget},) # widget may be None, name may be None. field = self.context missing_value = field.missing_value choices = [] field_index = self._field_index if field_index is not None: chosen_field = field.fields[self._field_index] elif value is not missing_value: chosen_field = field.validField(value) else: chosen_field = None for ix, inner_field in enumerate(field.fields): selected = inner_field is chosen_field inner = inner_field.bind(field.context) identifier = "%s-%02d" % (self.name, ix) if zc.form.interfaces.IOptionField.providedBy(inner): widget = CompositeOptionWidget(inner, self.request) else: widget = component.getMultiAdapter((inner, self.request), IInputWidget) if selected: widget.setRenderedValue(value) elif self._renderedValueSet(): if field.use_default_for_not_selected: widget.setRenderedValue(inner.default) else: widget.setRenderedValue(inner.missing_value) widget.setPrefix(self.name) choices.append({ 'selected': selected, 'identifier': identifier, 'widget': widget, 'value': six.text_type(ix) }) if not field.required: ix += 1 selected = chosen_field is None identifier = "%s-%02d" % (self.name, ix) widget = NotChosenWidget(self.no_value_label, self.no_value_hint) choices.append({ 'selected': selected, 'identifier': identifier, 'widget': widget, 'value': six.text_type(ix) }) return self.template(choices=choices)
class ContentViewletManager(manager.ViewletManagerBase): template = namedtemplate.NamedTemplate("alchemist.content")
class CombinationWidget(BaseWidget): widget_interface = IInputWidget @zope.cachedescriptors.property.Lazy def widgets(self): field = self.context res = [] for f in field.fields: f = f.bind(self.context) w = component.getMultiAdapter(( f, self.request, ), self.widget_interface) w.setPrefix(self.name + ".") res.append(w) return res def setPrefix(self, prefix): super(CombinationWidget, self).setPrefix(prefix) for w in self.widgets: w.setPrefix(self.name + ".") def loadValueFromRequest(self): # the lack of an API to get the input value regardless of validation # is a significant problem. The inability to clear errors is a # problem. field = self.context missing_value = field.missing_value widgets = self.widgets required_errors = [] errors = [] values = [] any = False for w in widgets: try: val = w.getInputValue() except WidgetInputError as e: if isinstance(getattr(e, 'errors'), zope.schema.interfaces.RequiredMissing): # :-( required_errors.append((w, e)) else: errors.append((w, e)) val = w.context.missing_value values.append(val) any = any or val != w.context.missing_value if field.required or any or errors: errors.extend(required_errors) else: # remove the required errors in the sub widgets for w, e in required_errors: w.error = lambda: None # :-( if errors: if len(errors) == 1: errors = errors[0][1] else: errors = [e for widget, e in errors] self._error = WidgetInputError(self.context.__name__, self.label, errors) values = missing_value elif not any: values = missing_value else: values = tuple(values) return values template = namedtemplate.NamedTemplate('default') def render(self, value): field = self.context missing_value = field.missing_value if value is not missing_value: try: len_value = len(value) except (TypeError, AttributeError): value = missing_value self._set_values_on_widgets(value) else: if len_value != len(field.fields): value = missing_value self._set_values_on_widgets(value) if value is not missing_value: self._set_values_on_widgets(value) for w in self.widgets: # XXX quick hack. if zope.schema.interfaces.IBool.providedBy(w.context): w.invert_label = True else: w.invert_label = False return self.template() def _set_values_on_widgets(self, values): hasInput = self.hasInput() for w, v in zip(self.widgets, values): if not hasInput or v != w.context.missing_value: w.setRenderedValue(v)
class SaveReportView(form.PageForm): def __init__(self, context, request): super(SaveReportView, self).__init__(context, request) class ISaveReportForm(interface.Interface): start_date = schema.Date( title=_("report_start_date", default=u"Date"), description=_(u"Choose a starting date for this report"), required=True) end_date = schema.Date( title=_("report_end_date", default=u"Date"), description=_(u"Choose an end date for this report"), required=True) note = schema.TextLine( title=u"Note", description=u"Optional note regarding this report", required=False) short_name = schema.TextLine(title=u"Report Type", description=u"Report Type", required=True) body = schema.Text(title=u"Report Text", description=u"Report Type", required=True) sittings = schema.TextLine( title=_(u"Sittings in Report"), description=_(u"List of sittings included in this report"), required=False) template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.Fields(ISaveReportForm) def setUpWidgets(self, ignore_request=False): class context: start_date = None end_date = None body = None note = None short_name = None sittings = None self.adapters = {self.ISaveReportForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) @form.action(_(u"Save Report"), name="save") def handle_save(self, action, data): report = domain.Report() session = Session() report.body = data["body"] report.start_date = data["start_date"] report.end_date = data["end_date"] report.note = data["note"] report.short_name = data["short_name"] report.owner_id = get_login_user().user_id # !+GROUP_AS_OWNER report.language = get_default_language() report.created_date = datetime.datetime.now() if not hasattr(self.context, "group_id"): report.group_id = ISchedulingContext(self.context).group_id else: report.group_id = self.context.group_id session.add(report) session.flush() notify(ObjectCreatedEvent(report)) if "sittings" in data.keys(): try: ids = data["sittings"].split(",") for id_number in ids: sit_id = int(id_number) sitting = session.query(domain.Sitting).get(sit_id) sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) notify(ObjectCreatedEvent(report)) except: #if no sittings are present in report or some other error occurs pass session.flush() if ISitting.providedBy(self.context): back_link = "./schedule" else: back_link = "./" self.request.response.redirect(back_link)
class EditMediaPath(ui.EditForm): class IEditMediaPathForm(interface.Interface): media_path = schema.URI(title=u'Media URL', description=u'URL of the Media File', required=True) template = namedtemplate.NamedTemplate('alchemist.form') form_fields = form.Fields(IEditMediaPathForm) def __init__(self, context, request): super(EditMediaPath, self).__init__(context, request) def setUpWidgets(self, ignore_request=False): class context: session = Session() trusted = removeSecurityProxy(self.context) sitting = session.query(domain.Sitting).get(trusted.sitting_id) if sitting is not None: media_path = sitting.media_path else: media_path = None self.adapters = {self.IEditMediaPathForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) def update(self): super(EditMediaPath, self).update() set_widget_errors(self.widgets, self.errors) def validate(self, action, data): errors = super(EditMediaPath, self).validate(action, data) return errors @form.action(_(u"Save")) def handle_save(self, action, data): session = Session() trusted = removeSecurityProxy(self.context) sitting = session.query(domain.Sitting).get(trusted.sitting_id) #import pdb; pdb.set_trace() if sitting is None: sitting = domain.Sitting() sitting.sitting_id = trusted.sitting_id sitting.media_path = data['media_path'] session.add(sitting) else: sitting.media_path = data['media_path'] session.commit() #import pdb; pdb.set_trace() self._next_url = absoluteURL(self.context, self.request) + "/transcripts" self.request.response.redirect(self._next_url) @form.action(_(u"Cancel")) def handle_cancel(self, action, data): self._next_url = absoluteURL(self.context, self.request) self.request.response.redirect(self._next_url)
class Assignment(PageForm): def __init__(self, context, request): super(Assignment, self).__init__(context, request) class IAssignmentForm(interface.Interface): editors = schema.List( title=u'Editors', required=False, value_type=schema.Choice(vocabulary="ActiveEditors"), ) readers = schema.List( title=u'Readers', required=False, value_type=schema.Choice(vocabulary="ActiveReaders"), ) reporters = schema.List( title=u'Reporters', required=False, value_type=schema.Choice(vocabulary="ActiveReporters"), ) form_fields = form.Fields(IAssignmentForm) template = namedtemplate.NamedTemplate('alchemist.form') form_fields['editors'].custom_widget = verticalMultiCheckBoxWidget form_fields['readers'].custom_widget = verticalMultiCheckBoxWidget form_fields['reporters'].custom_widget = verticalMultiCheckBoxWidget def setUpWidgets(self, ignore_request=False): class context: editors = get_assigned_staff(self.context, "Editor") readers = get_assigned_staff(self.context, "Reader") reporters = get_assigned_staff(self.context, "Reporter") self.adapters = {self.IAssignmentForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) #def update(self): #super(Assignment, self).update() #set_widget_errors(self.widgets, self.errors) @form.action(_(u"Assign Staff")) def handle_assignment(self, action, data): session = Session() session.query(domain.Assignment).filter( domain.Assignment.sitting_id == self.context.sitting_id).delete() for editor_id in data["editors"]: assignment = domain.Assignment() assignment.sitting_id = self.context.sitting_id assignment.staff_id = editor_id session.add(assignment) for reader_id in data["readers"]: assignment = domain.Assignment() assignment.sitting_id = self.context.sitting_id assignment.staff_id = reader_id session.add(assignment) for reporter_id in data["reporters"]: assignment = domain.Assignment() assignment.sitting_id = self.context.sitting_id assignment.staff_id = reporter_id session.add(assignment) session.commit() self.request.response.redirect('./transcripts')
class GenerateTakes(PageForm): class IGenerateTakes(interface.Interface): duration = schema.Int(title=_(u"Duration of takes"), required=True) form_fields = form.Fields(IGenerateTakes) template = namedtemplate.NamedTemplate('alchemist.form') def setUpWidgets(self, ignore_request=False): class context: duration = None self.adapters = {self.IGenerateTakes: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) def validate(self, action, data): errors = super(GenerateTakes, self).validate(action, data) if ((len(get_assigned_staff(self.context, "Reporter")) == 0) or (len(get_assigned_staff(self.context, "Reader")) == 0) or (len(get_assigned_staff(self.context, "Editor")) == 0)): print "reporters", get_assigned_staff(self.context, "Reporter") print "reader", get_assigned_staff(self.context, "Reader") print "editors", get_assigned_staff(self.context, "Editor") errors.append( interface.Invalid( _(u"Staff have not been assigned to work on this sitting yet" ), "duration")) return errors @form.action(_(u"Generate Takes")) def handle_generate_takes(self, action, data): session = Session() trusted = removeSecurityProxy(self.context) takes = session.query( domain.Take).filter(domain.Take.sitting_id == trusted.sitting_id) for t in takes: session.delete(t) #import pdb; pdb.set_trace() sitting = trusted current_start_time = sitting.start_date sitting_duration = sitting.end_date - sitting.start_date take_duration = timedelta(minutes=int(data["duration"])) assigned_reporters = get_assigned_staff(self.context, "Reporter") assigned_readers = get_assigned_staff(self.context, "Reader") assigned_editors = get_assigned_staff(self.context, "Editor") c_reporter = 0 c_reader = 0 c_editor = 0 while sitting_duration > timedelta(minutes=0): take = domain.Take() take.sitting_id = sitting.sitting_id if (sitting_duration - take_duration) > timedelta(minutes=0): sitting_duration = sitting_duration - take_duration take.start_date = current_start_time take.end_date = take.start_date + take_duration current_start_time = take.end_date else: take.start_date = current_start_time take.end_date = take.start_date + sitting_duration sitting_duration = timedelta(minutes=0) if c_reporter > len(assigned_reporters) - 1: c_reporter = 0 take.reporter_id = assigned_reporters[c_reporter] else: take.reporter_id = assigned_reporters[c_reporter] c_reporter = c_reporter + 1 if c_reader > len(assigned_readers) - 1: c_reader = 0 take.reader_id = assigned_readers[c_reader] else: take.reader_id = assigned_readers[c_reader] c_reader = c_reader + 1 if c_editor > len(assigned_editors) - 1: c_editor = 0 take.editor_id = assigned_editors[c_editor] else: take.editor_id = assigned_editors[c_editor] c_editor = c_editor + 1 session.add(take) session.commit() self.request.response.redirect('./takes')
class EditMediaPath(ui.EditForm): class IEditMediaPathForm(interface.Interface): web_optimised_video_path = schema.URI( title=u'Web Optimised File URL', description=u'URL of the Web Optimised Media File', required=True) audio_only_path = schema.URI( title=u'Audio Only File URL', description=u'URL of the Audio Only Media File', required=False) high_quality_video_path = schema.URI( title=u'High Quality Media URL', description=u'URL of the High Quality Media File', required=False) template = namedtemplate.NamedTemplate('alchemist.form') form_fields = form.Fields(IEditMediaPathForm) def setUpWidgets(self, ignore_request=False): class context: session = Session() trusted = removeSecurityProxy(self.context) sitting = session.query(domain.GroupSitting) \ .options( eagerload("hansard"), eagerload("hansard.media_paths")).get(trusted.sitting_id) if sitting.hansard.media_paths is not None: web_optimised_video_path = sitting.hansard. \ media_paths.web_optimised_video_path audio_only_path = sitting.hansard. \ media_paths.audio_only_path high_quality_video_path = sitting.hansard. \ media_paths.high_quality_video_path else: web_optimised_video_path = None audio_only_path = None high_quality_video_path = None self.adapters = {self.IEditMediaPathForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) def update(self): super(EditMediaPath, self).update() set_widget_errors(self.widgets, self.errors) def validate(self, action, data): errors = super(EditMediaPath, self).validate(action, data) return errors @form.action(_(u"Save")) def handle_save(self, action, data): session = Session() trusted = removeSecurityProxy(self.context) sitting = session.query(domain.GroupSitting).get(trusted.sitting_id) if sitting.hansard.media_paths is None: media_paths = domain.HansardMediaPaths() media_paths.web_optimised_video_path = data[ 'web_optimised_video_path'] media_paths.audio_only_path = data['audio_only_path'] media_paths.high_quality_video_path = data[ 'high_quality_video_path'] media_paths.hansard_id = sitting.hansard.hansard_id session.add(media_paths) else: sitting.hansard.media_paths.web_optimised_video_path = data[ 'web_optimised_video_path'] sitting.hansard.media_paths.audio_only_path = data[ 'audio_only_path'] sitting.hansard.media_paths.high_quality_video_path = data[ 'high_quality_video_path'] session.update(sitting) session.commit() self._next_url = absoluteURL(self.context, self.request) + "/hansard" self.request.response.redirect(self._next_url) @form.action(_(u"Cancel")) def handle_cancel(self, action, data): self._next_url = absoluteURL(self.context, self.request) self.request.response.redirect(self._next_url)
class ReportBuilder(form.Form, DateTimeFormatMixin): template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.fields(IReportBuilder) form_fields["start_date"].custom_widget = widgets.SelectDateWidget sittings = [] publication_date = datetime.datetime.today().date() publication_number = "" title = _(u"Report Title") generated_content = None show_preview = False language = None def __init__(self, context, request): self.context = context self.request = request interface.declarations.alsoProvides(removeSecurityProxy(self.context), IWorkspaceReportGeneration) super(ReportBuilder, self).__init__(context, request) def get_end_date(self, start_date, hours): end_date = start_date + datetime.timedelta(seconds=hours * 3600) return end_date def buildSittings(self, start_date, end_date): if IGroupSitting.providedBy(self.context): trusted = removeSecurityProxy(self.context) order = "real_order" trusted.item_schedule.sort(key=operator.attrgetter(order)) self.sittings.append(trusted) else: sittings = ISchedulingContext(self.context).get_sittings( start_date, end_date).values() self.sittings = map(removeSecurityProxy, sittings) self.sittings = [ExpandedSitting(sitting) for sitting in self.sittings] def generateContent(self, data): self.start_date = (data.get("start_date") or datetime.datetime.today().date()) generator = generators.ReportGeneratorXHTML(data.get("report_type")) self.language = generator.language self.title = generator.title self.language = generator.language self.publication_number = data.get("publication_number") self.end_date = self.get_end_date(self.start_date, generator.coverage) self.buildSittings(self.start_date, self.end_date) generator.context = self return generator.generateReport() @form.action(_(u"Preview")) def handle_preview(self, action, data): """Generate preview of the report """ self.show_preview = True self.generated_content = self.generateContent(data) self.status = _(u"See the preview of the report below") return self.template() @form.action(_(u"Publish")) def handle_publish(self, action, data): self.generated_content = self.generateContent(data) if not hasattr(self.context, "group_id"): context_group_id = ISchedulingContext(self.context).group_id else: context_group_id = self.context.group_id report = domain.Report(short_name=self.title, start_date=self.start_date, end_date=self.end_date, body_text=self.generated_content, owner_id=get_db_user_id(), language=self.language, group_id=context_group_id) session = Session() session.add(report) session.flush() self.status = _(u"Report has been processed and saved") return self.template()
class ReportView(form.PageForm, DateTimeFormatMixin): main_result_template = ViewPageTemplateFile("templates/main-reports.pt") result_template = ViewPageTemplateFile( "templates/default-report-sitting.pt") display_minutes = None include_text = True def __init__(self, context, request): self.site_url = url.absoluteURL(getSite(), request) super(ReportView, self).__init__(context, request) def check_option(self, doctype, option=""): opt_key = "%s_%s" % (doctype, option) if option else doctype return hasattr(self.options, opt_key) class IReportForm(interface.Interface): short_name = schema.Choice( title=_(u"Document Type"), description=_(u"Type of report to be produced"), values=[ "Order of the day", "Weekly Business", "Questions of the week" ], required=True) date = schema.Date( title=_(u"Date"), description=_(u"Choose a starting date for this report"), required=True) item_types = schema.List( title=u"Items to include", required=False, value_type=schema.Choice( vocabulary="bungeni.vocabulary.AvailableItems")) bills_options = schema.List( title=u"Bill options", required=False, value_type=schema.Choice( vocabulary="bungeni.vocabulary.BillOptions")) agenda_items_options = schema.List( title=u"Agenda options", required=False, value_type=schema.Choice( vocabulary="bungeni.vocabulary.AgendaOptions")) motions_options = schema.List( title=u"Motion options", required=False, value_type=schema.Choice( vocabulary="bungeni.vocabulary.MotionOptions")) questions_options = schema.List( title=u"Question options", required=False, value_type=schema.Choice( vocabulary="bungeni.vocabulary.QuestionOptions")) tabled_documents_options = schema.List( title=u"Tabled Document options", required=False, value_type=schema.Choice( vocabulary="bungeni.vocabulary.TabledDocumentOptions")) note = schema.TextLine( title=u"Note", required=False, description=u"Optional note regarding this report") template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.Fields(IReportForm) form_fields["item_types"].custom_widget = horizontalMultiCheckBoxWidget form_fields["bills_options"].custom_widget = verticalMultiCheckBoxWidget form_fields[ "agenda_items_options"].custom_widget = verticalMultiCheckBoxWidget form_fields["motions_options"].custom_widget = verticalMultiCheckBoxWidget form_fields[ "questions_options"].custom_widget = verticalMultiCheckBoxWidget form_fields[ "tabled_documents_options"].custom_widget = verticalMultiCheckBoxWidget form_fields["date"].custom_widget = widgets.SelectDateWidget def setUpWidgets(self, ignore_request=False): class context: item_types = "Bills" bills_options = "Title" agenda_items_options = "Title" questions_options = "Title" motions_options = "Title" tabled_documents_options = "Title" note = None date = None short_name = _(u"Order of the day") self.adapters = {self.IReportForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) def update(self): super(ReportView, self).update() forms.common.set_widget_errors(self.widgets, self.errors) def get_end_date(self, start_date, time_span): if time_span is TIME_SPAN.daily: return start_date + timedelta(days=1) elif time_span is TIME_SPAN.weekly: return start_date + timedelta(weeks=1) raise RuntimeError("Unknown time span: %s" % time_span) def time_span(self, data): if "short_name" in data: if data["short_name"] == u"Order of the day": return TIME_SPAN.daily elif data["short_name"] == u"Proceedings of the day": return TIME_SPAN.daily elif data["short_name"] == u"Weekly Business": return TIME_SPAN.weekly elif data["short_name"] == u"Questions of the week": return TIME_SPAN.weekly else: return TIME_SPAN.daily def validate(self, action, data): errors = super(ReportView, self).validate(action, data) time_span = self.time_span(data) if IGroupSitting.providedBy(self.context): if not self.context.items: errors.append( interface.Invalid( _(u"The sitting has no scheduled items"))) else: start_date = data["date"] if "date" in data else \ datetime.datetime.today().date() end_date = self.get_end_date(start_date, time_span) try: ctx = ISchedulingContext(self.context) except: errors.append( interface.Invalid( _(u"You are trying to generate a report " "outside scheduling"))) sittings = ctx.get_sittings(start_date, end_date).values() if not sittings: errors.append( interface.Invalid( _(u"The period selected has no sittings"), "date")) parliament = queries.get_parliament_by_date_range( start_date, end_date) if parliament is None: errors.append( interface.Invalid( _(u"A parliament must be active in the period"), "date")) return errors @form.action(_(u"Preview")) def handle_preview(self, action, data): self.process_form(data) self.save_link = url.absoluteURL(self.context, self.request) + "/save-report" self.body_text = self.result_template() return self.main_result_template() def process_form(self, data): class optionsobj(object): """Object that holds all the options.""" self.options = optionsobj() if not hasattr(self, "short_name"): if "short_name" in data: self.short_name = data["short_name"] self.sittings = [] if IGroupSitting.providedBy(self.context): trusted = removeSecurityProxy(self.context) order = "real_order" if self.display_minutes else "planned_order" trusted.item_schedule.sort(key=operator.attrgetter(order)) self.sittings.append(trusted) self.start_date = self.context.start_date self.end_date = self.get_end_date(self.start_date, self.time_span(data)) else: self.start_date = data["date"] if "date" in data else \ datetime.datetime.today().date() self.end_date = self.get_end_date(self.start_date, self.time_span(data)) sittings = ISchedulingContext(self.context).get_sittings( self.start_date, self.end_date).values() self.sittings = map(removeSecurityProxy, sittings) self.ids = "" for sitting in self.sittings: self.ids += str(sitting.group_sitting_id) + "," def cleanup(string): return string.lower().replace(" ", "_") for item_type in data["item_types"]: itemtype = cleanup(item_type) type_key = itemtype.rstrip("s").replace("_", "") setattr(self.options, type_key, True) setattr(self.options, itemtype, True) for option in data[itemtype + "_options"]: opt_key = "".join( (cleanup(itemtype.rstrip("s")).replace("_", ""), "_", cleanup(option))) setattr(self.options, opt_key, True) if self.display_minutes: self.link = url.absoluteURL(self.context, self.request) \ + "/votes-and-proceedings" else: self.link = url.absoluteURL(self.context, self.request) + "/agenda" try: self.group = self.context.group except: self.group = ISchedulingContext(self.context).get_group()
class ReportView(form.PageForm): main_result_template = ViewPageTemplateFile("templates/main_reports.pt") result_template = ViewPageTemplateFile("templates/reports.pt") def __init__(self, context, request): super(ReportView, self).__init__(context, request) class IReportForm(interface.Interface): doc_type = schema.Choice( title=_(u"Document Type"), description=_(u"Type of document to be produced"), values=[ "Order of the day", "Weekly Business", "Questions of the week" ], required=True) date = schema.Date( title=_(u"Date"), description=_(u"Choose a starting date for this report"), required=True) item_types = schema.List( title=u"Items to include", required=False, value_type=schema.Choice(vocabulary="Available Items"), ) bills_options = schema.List( title=u"Bill options", required=False, value_type=schema.Choice(vocabulary="Bill Options"), ) agenda_items_options = schema.List( title=u"Agenda options", required=False, value_type=schema.Choice(vocabulary="Agenda Options"), ) motions_options = schema.List( title=u"Motion options", required=False, value_type=schema.Choice(vocabulary="Motion Options"), ) questions_options = schema.List( title=u"Question options", required=False, value_type=schema.Choice(vocabulary="Question Options"), ) tabled_documents_options = schema.List( title=u"Tabled Document options", required=False, value_type=schema.Choice(vocabulary="Tabled Document Options"), ) note = schema.TextLine( title=u"Note", required=False, description=u"Optional note regarding this report") template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.Fields(IReportForm) form_fields["item_types"].custom_widget = horizontalMultiCheckBoxWidget form_fields["bills_options"].custom_widget = verticalMultiCheckBoxWidget form_fields[ "agenda_items_options"].custom_widget = verticalMultiCheckBoxWidget form_fields["motions_options"].custom_widget = verticalMultiCheckBoxWidget form_fields[ "questions_options"].custom_widget = verticalMultiCheckBoxWidget form_fields[ "tabled_documents_options"].custom_widget = verticalMultiCheckBoxWidget form_fields["date"].custom_widget = SelectDateWidget def setUpWidgets(self, ignore_request=False): class context: item_types = "Bills" bills_options = "Title" agenda_items_options = "Title" questions_options = "Title" motions_options = "Title" tabled_documents_options = "Title" note = None date = None doc_type = "Order of the day" self.adapters = {self.IReportForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) def update(self): super(ReportView, self).update() set_widget_errors(self.widgets, self.errors) def validate(self, action, data): errors = super(ReportView, self).validate(action, data) self.time_span = TIME_SPAN.daily if "doc_type" in data: if data["doc_type"] == "Order of the day": self.time_span = TIME_SPAN.daily elif data["doc_type"] == "Proceedings of the day": self.time_span = TIME_SPAN.daily elif data["doc_type"] == "Weekly Business": self.time_span = TIME_SPAN.weekly elif data["doc_type"] == "Questions of the week": self.time_span = TIME_SPAN.weekly if IGroupSitting.providedBy(self.context): self.start_date = datetime.date(self.context.start_date.year, self.context.start_date.month, self.context.start_date.day) elif ISchedulingContext.providedBy(self.context): if "date" in data: self.start_date = data["date"] else: self.start_date = datetime.today().date() self.end_date = self.get_end_date(self.start_date, self.time_span) if ISchedulingContext.providedBy(self.context): self.sittings = self.get_sittings(self.start_date, self.end_date) if len(self.sittings) == 0: errors.append( interface.Invalid( _(u"The period selected has no sittings"), "date")) parliament = queries.get_parliament_by_date_range( self, self.start_date, self.end_date) #session = queries.get_session_by_date_range(self, start_date, end_date) if parliament is None: errors.append( interface.Invalid( _(u"A parliament must be active in the period"), "date")) return errors @form.action(_(u"Preview")) def handle_preview(self, action, data): self.process_form(data) self.save_link = url.absoluteURL(self.context, self.request) + "/save-report" self.body_text = self.result_template() return self.main_result_template() def get_end_date(self, start_date, time_span): if time_span is TIME_SPAN.daily: return start_date + timedelta(days=1) elif time_span is TIME_SPAN.weekly: return start_date + timedelta(weeks=1) raise RuntimeError("Unknown time span: %s" % time_span) def get_sittings(self, start, end): """ return the sittings with scheduled items for the given daterange""" session = Session() query = session.query(domain.GroupSitting).filter( sql.and_(domain.GroupSitting.start_date.between(start, end), domain.GroupSitting.group_id == self.context.group_id)).order_by( domain.GroupSitting.start_date).options( #eagerload("sitting_type"), eagerload("item_schedule"), eagerload("item_schedule.item"), eagerload("item_schedule.discussion")) items = query.all() for item in items: if self.display_minutes: item.item_schedule.sort(key=operator.attrgetter("real_order")) else: item.item_schedule.sort( key=operator.attrgetter("planned_order")) #item.sitting_type.sitting_type = item.sitting_type.sitting_type.capitalize() return items def process_form(self, data): class optionsobj(object): """Object that holds all the options.""" pass self.options = optionsobj() if not hasattr(self, "doc_type"): if "doc_type" in data: self.doc_type = data["doc_type"] self.sittings = [] if IGroupSitting.providedBy(self.context): session = Session() st = self.context.sitting_id sitting = session.query(domain.GroupSitting).get(st) self.sittings.append(sitting) back_link = url.absoluteURL(self.context, self.request) + "/schedule" elif ISchedulingContext.providedBy(self.context): self.sittings = self.get_sittings(self.start_date, self.end_date) back_link = url.absoluteURL(self.context, self.request) else: raise NotImplementedError count = 0 self.ids = "" for s in self.sittings: self.ids = self.ids + str(s.sitting_id) + "," def cleanup(string): return string.lower().replace(" ", "_") for item_type in data["item_types"]: itemtype = cleanup(item_type) setattr(self.options, itemtype, True) for option in data[itemtype + "_options"]: setattr(self.options, cleanup(itemtype + "_" + option), True) if self.display_minutes: self.link = url.absoluteURL( self.context, self.request) + "/votes-and-proceedings" else: self.link = url.absoluteURL(self.context, self.request) + "/agenda" try: self.group = self.context.get_group() except: session = Session() self.group = session.query(domain.Group).get(self.context.group_id)
class ReportBuilder(form.Form, DateTimeFormatMixin): template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.fields(IReportBuilder) form_fields["start_date"].custom_widget = widgets.SelectDateWidget sittings = [] publication_date = datetime.datetime.today().date() publication_number = "" title = _(u"Report Title") generated_content = None show_preview = False language = None def __init__(self, context, request): self.context = context self.request = request interface.declarations.alsoProvides(removeSecurityProxy(self.context), IWorkspaceReportGeneration) if IWorkspaceUnderConsideration.providedBy(self.context): #change the vocabulary self.form_fields["report_type"].field.vocabulary=\ vocabulary.document_xhtml_template_factory super(ReportBuilder, self).__init__(context, request) def get_end_date(self, start_date, hours): end_date = start_date + datetime.timedelta(seconds=hours * 3600) return end_date def buildSittings(self): if ISitting.providedBy(self.context): trusted = removeSecurityProxy(self.context) order = "real_order" trusted.item_schedule.sort(key=operator.attrgetter(order)) self.sittings.append(trusted) else: sittings = ISchedulingContext(self.context).get_sittings( self.start_date, self.end_date).values() self.sittings = map(removeSecurityProxy, sittings) self.sittings = [ExpandedSitting(sitting) for sitting in self.sittings] def buildContext(self): if IWorkspaceScheduling.providedBy(self.request): self.buildSittings() elif IWorkspaceUnderConsideration.providedBy(self.context): default_filters = { 'sort_dir': u'asc', 'filter_status_date': u'%s->%s' % (self.start_date.isoformat(), self.end_date.isoformat()), 'sort_on': u'status_date', 'filter_type': u'', } doc_container = self.context.publishTraverse( self.request, "documents") for type_key, ti in capi.iter_type_info(): workflow = ti.workflow if workflow and workflow.has_feature("workspace"): #add generators of various doctypes container_name = naming.plural(type_key) filters = dict(default_filters) filters['filter_type'] = type_key setattr(self, container_name, doc_container.query(**filters)[0]) def generateContent(self, data): self.start_date = (data.get("start_date") or datetime.datetime.today().date()) generator = generators.ReportGeneratorXHTML(data.get("report_type")) self.language = generator.language self.title = generator.title self.language = generator.language self.publication_number = data.get("publication_number") self.end_date = self.get_end_date(self.start_date, generator.coverage) self.buildContext() generator.context = self return generator.generateReport() @form.action(_(u"Preview"), name="preview") def handle_preview(self, action, data): """Generate preview of the report """ self.show_preview = True self.generated_content = self.generateContent(data) self.status = _(u"See the preview of the report below") return self.template() @form.action(_("publish_report", default=u"Publish"), name="publish") def handle_publish(self, action, data): self.generated_content = self.generateContent(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).parliament_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() notify(ObjectCreatedEvent(report)) self.status = _(u"Report has been processed and saved") return self.template()
class SaveReportView(form.PageForm): def __init__(self, context, request): super(SaveReportView, self).__init__(context, request) class ISaveReportForm(interface.Interface): start_date = schema.Date( title=_(u"Date"), description=_(u"Choose a starting date for this report"), required=True) end_date = schema.Date( title=_(u"Date"), description=_(u"Choose an end date for this report"), required=True) note = schema.TextLine( title=u"Note", required=False, description=u"Optional note regarding this report") report_type = schema.TextLine(title=u"Report Type", required=True, description=u"Report Type") body_text = schema.Text(title=u"Report Text", required=True, description=u"Report Type") sittings = schema.TextLine( title=_(u"Sittings included in this report"), description=_(u"Sittings included in this report"), required=False) template = namedtemplate.NamedTemplate("alchemist.form") form_fields = form.Fields(ISaveReportForm) def setUpWidgets(self, ignore_request=False): class context: start_date = None end_date = None body_text = None note = None report_type = None sittings = None self.adapters = {self.ISaveReportForm: context} self.widgets = form.setUpEditWidgets(self.form_fields, self.prefix, self.context, self.request, adapters=self.adapters, ignore_request=ignore_request) @form.action(_(u"Save")) def handle_save(self, action, data): report = domain.Report() session = Session() report.body_text = data["body_text"] report.start_date = data["start_date"] report.end_date = data["end_date"] report.note = data["note"] report.report_type = data["report_type"] report.short_name = data["report_type"] owner_id = get_db_user_id() '''!+TODO(Miano, 18/08/2010) The admin user is currently not a db user thus the line above returns None when the admin publishes a report. to go around this if it returns None, just query the db for users and set the owner id to be the first result''' if owner_id is not None: report.owner_id = owner_id else: query = session.query(domain.User) results = query.all() report.owner_id = results[0].user_id report.language = "en" report.created_date = datetime.datetime.now() report.group_id = self.context.group_id session.add(report) notify(ObjectCreatedEvent(report)) # !+INVALIDATE(mr, sep-2010) container.invalidate_caches_for("Report", "add") if "sittings" in data.keys(): try: ids = data["sittings"].split(",") for id_number in ids: sit_id = int(id_number) sitting = session.query(domain.GroupSitting).get(sit_id) sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) # !+INVALIDATE(mr, sep-2010) via an event... container.invalidate_caches_for("SittingReport", "add") except: #if no sittings are present in report or some other error occurs pass session.commit() if IGroupSitting.providedBy(self.context): back_link = "./schedule" elif ISchedulingContext.providedBy(self.context): back_link = "./" else: raise NotImplementedError self.request.response.redirect(back_link)