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
def set_sitting_parent_ids(ob, event): """We add the group ID/sesssion id if adding a sitting in contexts not bound to groups in traversal hierarchy """ scheduling_context = ISchedulingContext(ob.__parent__, None) if ob.group_id is None: if scheduling_context is not None: ob.group_id = removeSecurityProxy(scheduling_context).group_id if ob.session_id is None or IObjectModifiedEvent.providedBy(event): if scheduling_context is not None: group = scheduling_context.get_group() if interfaces.IParliament.providedBy(group): container = removeSecurityProxy(group).sessions else: return else: try: container = ob.group.sessions except AttributeError: return try: session_id = container._query.filter( sql.and_( domain.Session.start_date < ob.start_date, domain.Session.end_date > ob.end_date ) ).one().session_id ob.session_id = session_id except (orm.exc.NoResultFound, orm.exc.MultipleResultsFound): log.error("Could not determine session for sitting %s", ob)
def set_sitting_parent_ids(ob, event): """We add the group ID/sesssion id if adding a sitting in contexts not bound to groups in traversal hierarchy """ scheduling_context = ISchedulingContext(ob.__parent__, None) if ob.group_id is None: if scheduling_context is not None: ob.group_id = removeSecurityProxy(scheduling_context).group_id if ob.session_id is None or IObjectModifiedEvent.providedBy(event): if scheduling_context is not None: group = scheduling_context.get_group() if interfaces.IChamber.providedBy(group): container = removeSecurityProxy(group).sessions else: return else: try: container = ob.group.sessions except AttributeError: return try: session_id = container._query.filter( sql.and_( domain.Session.start_date < ob.start_date, domain.Session.end_date > ob.end_date)).one().session_id ob.session_id = session_id except (orm.exc.NoResultFound, orm.exc.MultipleResultsFound): log.error("Could not determine session for sitting %s", ob)
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
def __init__(self, context, request, view, manager): while not ISchedulingContext.providedBy(context): context = ISchedulingContext(context, context.__parent__) if context is None: raise RuntimeError("Unable to locate a scheduling context.") super(SchedulablesViewlet, self).__init__(context, request, view, manager)
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()
def handle_delete(self, action, data): self.template_data = [] if ISchedulingContext.providedBy(self.context): container = removeSecurityProxy(self.context.__parent__).sittings else: container = self.context.publishTraverse(self.request, "sittings") sitting = (container.get(get_real_id(data["ids"])) or container.get(get_real_id(self.request.form["event_pid"]))) self.template_data = [] if sitting is not None: self.request.form["headless"] = "true" delete_form = DeleteForm(sitting, self.request) delete_form.update() if not delete_form.errors: self.template_data.append({ "sitting_id": sitting.sitting_id, "action": "deleted", "ids": data["ids"], }) else: return self.delete_sitting_failure_handler(action, data, delete_form.errors ) self.request.response.setHeader("Content-type", "text/xml") return self.xml_template()
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) 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
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()
def __init__(self, context, request, view, manager): while not ISchedulingContext.providedBy(context): context = ISchedulingContext(context, context.__parent__) if context is None: raise RuntimeError("Unable to locate a scheduling context.") super(SchedulablesViewlet, self).__init__( context, request, view, manager)
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) 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
def __call__(self, timestamp=None): trusted = removeSecurityProxy(self.context) trusted.__name__ = self.__name__ interface.alsoProvides(trusted, ILocation) self.url = url.absoluteURL(trusted.__parent__, self.request) self.title = ISchedulingContext(self.context).label return self.render()
def __init__(self, context, request): super(DhtmlxCalendarSittings, self).__init__(ISchedulingContext(context), request) self.context.__name__ = self.__name__ interface.alsoProvides(self.context, ILocation) interface.alsoProvides(self.context, IDCDescriptiveProperties) self.__parent__ = context
def handle_insert(self, action, data): session = Session() sitting = domain.GroupSitting() trusted = removeSecurityProxy(ISchedulingContext(self.context)) group = session.query(domain.Group).get(trusted.group_id) if ("rec_type" not in data.keys()) or (data["rec_type"] == ""): sitting.start_date = datetime.datetime.strptime(data["start_date"], '%Y-%m-%d %H:%M') sitting.end_date = datetime.datetime.strptime(data["end_date"], '%Y-%m-%d %H:%M') sitting.group_id = trusted.group_id if "language" in data.keys(): sitting.language = data["language"] if "venue" in data.keys(): sitting.venue_id = data["venue"] session.add(sitting) notify(ObjectCreatedEvent(sitting)) session.commit() self.request.response.setHeader('Content-type', 'text/xml') return '<data><action type="inserted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" /></data>' else: try: recurrence_start_date = datetime.datetime.strptime(data["start_date"], '%Y-%m-%d %H:%M') recurrence_end_date = datetime.datetime.strptime(data["end_date"], '%Y-%m-%d %H:%M') except: print "Date is not in the correct format" year = timedelta(days=365) #max end date is one year from now or end_date of the group whichever is sooner if (group is not None) and (group.end_date is not None): if (datetime.datetime.now() + year) < group.end_date: end = datetime.datetime.now() + year else: end = group.end_date if recurrence_end_date > end: recurrence_end_date = end else: if recurrence_end_date > (datetime.datetime.now() + year): recurrence_end_date = datetime.datetime.now() + year recurrence_type = data["rec_type"] length = data["event_length"] sitting_length = timedelta(seconds=int(length)) dates = self.generate_recurrence_dates(recurrence_start_date, recurrence_end_date, recurrence_type) output = '<data>' for date in dates: sitting = domain.GroupSitting() sitting.group_id = trusted.group_id sitting.start_date = date sitting.end_date = date + sitting_length sitting.status = None if "language" in data.keys(): sitting.language = data["language"] if "venue" in data.keys(): sitting.venue_id = data["venue"] session.add(sitting) notify(ObjectCreatedEvent(sitting)) output = output+'<action type="inserted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" />' session.commit() output = output + '</data>' self.request.response.setHeader('Content-type', 'text/xml') return output
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 set_schedule_text_group(context, event): """Sets the current group id of schedule meta Headings and Notes """ if hasattr(context, "group_id") and context.group_id is None: request_context = common.get_traversed_context() scheduling_context = ISchedulingContext( request_context.context.__parent__, None) if scheduling_context is not None: context.group_id = scheduling_context.group_id
def __init__(self, context, request): log.debug("CalendarView.__init__: %s" % (context)) super(CalendarView, self).__init__(ISchedulingContext(context), request) self.context.__name__ = self.__name__ self.context.title = self.short_name interface.alsoProvides(self.context, ILocation) interface.alsoProvides(self.context, IDCDescriptiveProperties) self.__parent__ = context log.debug(debug.interfaces(self)) log.debug(debug.location_stack(self))
def __call__(self, timestamp=None): trusted = removeSecurityProxy(self.context) trusted.__name__ = self.__name__ interface.alsoProvides(trusted, ILocation) if (IBusinessSectionLayer.providedBy(self.request) and isinstance(trusted, SittingContainerSchedulingContext)): self.url = url.absoluteURL(trusted.__parent__.__parent__, self.request) else: self.url = url.absoluteURL(trusted.__parent__, self.request) self.title = ISchedulingContext(self.context).label return self.render()
def calendar_js_globals(self): limit_start = ISchedulingContext(self.context).start_date limit_end = ISchedulingContext(self.context).end_date cal_globals = dict( limit_start=limit_start.isoformat() if limit_start else None, limit_end=limit_end.isoformat() if limit_end else None, ical_url=self.ical_url, required_fields=[ field.field.getName() for field in self.partial_event_form.form_fields if field.field.required ], view_url=self.url, venues_view_title=translate_i18n(TITLE_VENUES_VIEW), text_group=translate_i18n(FIELD_GROUP), text_start_date=translate_i18n(FIELD_START_DATE), text_end_date=translate_i18n(FIELD_END_DATE), text_venue=translate_i18n(FIELD_VENUE), text_activity_type=translate_i18n(_(u"Activity Type")), text_meeting_type=translate_i18n(_(u"Meeting Type")), text_convocation_type=translate_i18n(_(u"Convocation Type")), text_sitting=translate_i18n(TITLE_SITTING), text_view=translate_i18n(ACTION_VIEW_SITTING), error_messages=dict( default=_(u"Please check the highlighted sittings. " "Failed to apply changes"), updated=_(u"Please review the highlighted sittings." " Could not apply changes."), deleted=_(u"Please review the highlighted events." " Could not be deleted."))) return """var cal_globals = %s; var timeline_data = { venues: %s, combined: %s }; var group_urls= %s;""" % ( json.dumps(cal_globals), json.dumps(self.venues_data), json.dumps(self.groups_data), json.dumps(self.calendar_urls()))
def calendar_js_globals(self): limit_start = ISchedulingContext(self.context).start_date limit_end = ISchedulingContext(self.context).end_date cal_globals = dict( limit_start=limit_start.isoformat() if limit_start else None, limit_end=limit_end.isoformat() if limit_end else None, ical_url=self.ical_url, required_fields=[field.field.getName() for field in self.partial_event_form.form_fields if field.field.required ], view_url=self.url, venues_view_title=translate_i18n(TITLE_VENUES_VIEW), text_group=translate_i18n(FIELD_GROUP), text_start_date=translate_i18n(FIELD_START_DATE), text_end_date=translate_i18n(FIELD_END_DATE), text_venue=translate_i18n(FIELD_VENUE), text_activity_type=translate_i18n(_(u"Activity Type")), text_meeting_type=translate_i18n(_(u"Meeting Type")), text_convocation_type=translate_i18n(_(u"Convocation Type")), text_sitting=translate_i18n(TITLE_SITTING), text_view=translate_i18n(ACTION_VIEW_SITTING), error_messages=dict( default=_(u"Please check the highlighted sittings. " "Failed to apply changes"), updated=_(u"Please review the highlighted sittings." " Could not apply changes."), deleted=_(u"Please review the highlighted events." " Could not be deleted.") ) ) return """var cal_globals = %s; var timeline_data = { venues: %s, combined: %s }; var group_urls= %s;""" %( json.dumps(cal_globals), json.dumps(self.venues_data), json.dumps(self.groups_data), json.dumps(self.calendar_urls()) )
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.short_name = report.short_name = data["short_name"] 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 # TODO get language from config 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)
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)
def build_context(self): if ISitting.providedBy(self.context): sittings = [removeSecurityProxy(self.context)] else: sittings = map( removeSecurityProxy, ISchedulingContext(self.context).get_sittings( self.start_date, self.end_date).values()) # sort sittings chronologically sittings.sort(key=operator.attrgetter("start_date")) # ensure item_schedule is sorted via "real_order" within each sitting for sitting in sittings: sitting.item_schedule.sort(key=operator.attrgetter("real_order")) self.sittings = [ExpandedSitting(s) for s in sittings]
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 = ui_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 = ui_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 = 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)
def process_form(self, data): class optionsobj(object): """Object that holds all the options.""" pass 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) 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 self.ids = "" for s in self.sittings: self.ids = self.ids + str(s.group_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)
def __init__(self, context, request): log.debug("CalendarView.__init__: %s" % (context)) super(CalendarView, self).__init__(ISchedulingContext(context), request) trusted = removeSecurityProxy(self.context) trusted.__name__ = self.__name__ trusted.title = self.short_name interface.alsoProvides(trusted, ILocation) interface.alsoProvides(trusted, IDCDescriptiveProperties) if (IBusinessSectionLayer.providedBy(request) and isinstance(trusted, SittingContainerSchedulingContext)): self.url = url.absoluteURL(trusted.__parent__.__parent__, request) else: self.url = url.absoluteURL(trusted.__parent__, request) self.__parent__ = context log.debug(debug.interfaces(self)) log.debug(debug.location_stack(self))
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)) ids = data["sittings"].split(",") for id in ids: try: sit_id = int(id) except: continue sitting = session.query(domain.GroupSitting).get(sit_id) sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) 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)
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 = ui_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 = ui_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 = 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)
def process_form(self, data): class optionsobj(object): """Object that holds all the options.""" pass 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) 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 self.ids = "" for s in self.sittings: self.ids = self.ids + str(s.group_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)
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 generate_dates(self, data): trusted = removeSecurityProxy(ISchedulingContext(self.context)) recurrence_start_date = data["start_date"].replace(tzinfo=None) recurrence_end_date = data["rec_end_date"].replace(tzinfo=None) group = trusted.get_group() # If group is none then there is a big problem assert group is not None year = timedelta(days=365) now = datetime.datetime.now() if (((group.end_date is not None) and ((now + year) < group.end_date)) or (group.end_date is None)): end = now + year else: end = group.end_date if recurrence_end_date > end: recurrence_end_date = end return utils.generate_recurrence_dates(recurrence_start_date, recurrence_end_date, data["rec_type"])
def __call__(self): body_text = self.request.form['body_text'] session = Session() report = domain.Report() start_date = self.request.form['start_date'] end_date = self.request.form['end_date'] report.start_date = start_date report.end_date = end_date report.created_date = datetime.datetime.now() report.note = self.request.form['note'] report.report_type = self.request.form['report_type'] report.body_text = body_text report.user_id = get_principal_id() report.group_id = self.context.group_id report.language = "en" session.add(report) if self.request.form['single'] == "False": self.sitting_items = self.get_sittings_items(start_date, end_date) else: self.sitting_items = [] st = self.context.sitting_id sitting = session.query(domain.GroupSitting).get(st) self.sitting_items.append(sitting) for sitting in self.sitting_items: sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) session.flush() rpm = zope.securitypolicy.interfaces.IRolePermissionMap(report) rpm.grantPermissionToRole(u'zope.View', 'bungeni.Anybody') if IGroupSitting.providedBy(self.context): back_link = './schedule' elif ISchedulingContext.providedBy(self.context): back_link = './' else: raise NotImplementedError self.request.response.redirect(back_link)
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()
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)
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.short_name = data["short_name"] report.owner_id = get_db_user_id() report.language = get_default_language() report.created_date = datetime.datetime.now() 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.GroupSitting).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.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)
def get_sittings_path(self): """get the url to the context sittings container""" scheduling_context = None context = self.context while scheduling_context is None: scheduling_context = ISchedulingContext(context, None) if not scheduling_context: context = context.__parent__ if scheduling_context: try: ctx = scheduling_context.__parent__ if hasattr(ctx, "sittings"): sittings_container = ctx.sittings else: sittings_container = removeSecurityProxy(ctx).publishTraverse( self.request, "sittings" ) return url.absoluteURL(sittings_container, self.request) except NotFound: log.error("Could not determine sittings path for context %s", self.context ) return "../sittings"
def handle_delete(self, action, data): self.template_data = [] if ISchedulingContext.providedBy(self.context): container = removeSecurityProxy(self.context.__parent__).sittings else: container = self.context.publishTraverse(self.request, "sittings") sitting = (container.get(get_real_id(data["ids"])) or container.get( get_real_id(self.request.form["event_pid"]))) self.template_data = [] if sitting is not None: self.request.form["headless"] = "true" delete_form = DeleteForm(sitting, self.request) delete_form.update() if not delete_form.errors: self.template_data.append({ "sitting_id": sitting.sitting_id, "action": "deleted", "ids": data["ids"], }) else: return self.delete_sitting_failure_handler( action, data, delete_form.errors) self.request.response.setHeader("Content-type", "text/xml") return self.xml_template()
def handle_update(self, action, data): session = Session() self.template_data = [] venue_id = unicode(data["venue"]) if data['venue'] else None data["rec_end_date"] = data["end_date"] data["headless"] = 'true' self.request.form["venue_id"] = data["venue_id"] = venue_id self.request.form["headless"] = "true" if ISchedulingContext.providedBy(self.context): container = removeSecurityProxy(self.context.__parent__).sittings else: container = self.context.publishTraverse(self.request, "sittings") if ("rec_type" in data.keys()) and (data["rec_type"] is not None): # updating recurring events - we assume existing events fall # at the beginning of the sequence and offer in place update. parent_sitting_id = get_real_id(data["ids"] or data["event_pid"]) length = data["event_length"] sitting_length = timedelta(seconds=length) base_sitting_length = sitting_length + timedelta(hours=1) siblings_filter = or_( domain.Sitting.recurring_id==parent_sitting_id, domain.Sitting.sitting_id==parent_sitting_id ) siblings = [ sitting for sitting in container.batch(order_by=(domain.Sitting.sitting_id), limit=None, filter=siblings_filter ) ] dates = self.generate_dates(data) current_count = len(siblings) for count, date in enumerate(dates): is_new = not count < current_count sitting_data = copy(data) sitting_data["start_date"] = date.strftime(DT_FORMAT) sitting_data["end_date"] = (date + sitting_length).strftime(DT_FORMAT) request_copy = copy(self.request) request_copy.form = sitting_data if is_new: add_form = AddForm(container, request_copy) add_form.update() if add_form.errors: log.error("Could not add sitting in sequence: %s", sitting_data ) continue else: sitting = add_form.created_object sitting.recurring_id = parent_sitting_id else: sitting = siblings[count] if not count: sitting.recurring_end_date = dates[len(dates)-1] + base_sitting_length sitting.recurring_type = data.get("rec_type") sitting.recurring_id = 0 sitting.sitting_length = length else: sitting.sitting_length = int(time.mktime(date.timetuple())) sitting.recurring_type = None if not is_new: edit_form = EditForm(sitting, request_copy) edit_form.update() if edit_form.errors: continue else: session.merge(edit_form.context) else: session.merge(sitting) self.template_data.append({ "sitting_id": sitting.sitting_id, "action": (is_new and "inserted" or "updated"), "ids": create_id(sitting) }) #delete any sittings outside recurring bounds for del_sibling in siblings[len(dates):]: delete_form = DeleteForm(del_sibling, self.request) delete_form.update() if delete_form.errors: continue else: self.template_data.append({ "sitting_id": del_sibling.sitting_id, "action": "deleted", "ids": create_id(del_sibling) }) else: sitting_id = get_real_id(data["ids"]) parent_id = get_real_id(data["event_pid"]) sitting = container.get(sitting_id) if sitting is None: sitting = container.get(int(parent_id)) edit_form = EditForm(sitting, self.request) edit_form.update() if edit_form.errors: return self.update_sitting_failure_handler(action, data, edit_form.errors ) else: sitting.sitting_length = data.get("event_length") session.merge(sitting) self.template_data.append({ "sitting_id": sitting.sitting_id, "action": "updated", "ids": data["ids"], }) self.request.response.setHeader("Content-type", "text/xml") return self.xml_template()
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)
def __call__(self): date = datetime.datetime.strptime(self.request.form['date'], '%Y-%m-%d').date() self.display_minutes = (self.request.form['display_minutes'] == "True") time_span = self.request.form['time_span'] if time_span == TIME_SPAN.daily: time_span = TIME_SPAN.daily elif time_span == TIME_SPAN.weekly: time_span = TIME_SPAN.weekly end = self.get_end_date(date, time_span) body_text = super(StoreReportView, self).__call__() sitting_items = [] for sitting in self.sitting_items: if self.display_minutes: if sitting.status in ["published-minutes"]: sitting_items.append(sitting) else: if sitting.status in [ "published-agenda", "draft-minutes", "published-minutes" ]: sitting_items.append(sitting) if len(sitting_items) == 0: referer = self.request.getHeader('HTTP_REFERER') if referer: referer = referer.split('?')[0] else: referer = "" self.request.response.redirect( referer + "?portal_status_message=No data found") return self.sitting_items = sitting_items session = Session() report = domain.Report() report.start_date = date report.end_date = end report.created_date = datetime.datetime.now() if self.display_minutes: report.report_type = 'minutes' else: report.report_type = 'agenda' report.body_text = body_text report.user_id = get_principal_id() report.group_id = self.group.group_id session.add(report) for sitting in self.sitting_items: sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) session.flush() rpm = zope.securitypolicy.interfaces.IRolePermissionMap(report) rpm.grantPermissionToRole(u'zope.View', 'bungeni.Anybody') if IGroupSitting.providedBy(self.context): back_link = ui_url.absoluteURL(self.context, self.request) + '/schedule' elif ISchedulingContext.providedBy(self.context): back_link = ui_url.absoluteURL(self.context, self.request) else: raise NotImplementedError self.request.response.redirect(back_link) session.close()
def __init__(self, context, request): log.debug("CalendarView.__init__: %s" % (context)) super(CalendarView, self).__init__(ISchedulingContext(context), request)