class CountryStatistics(form.SchemaForm, StatisticsMixin): """ Country managers can access statistics for their countries and tools inside their respective countries, but nowhere else.. """ grok.context(ICountry) grok.name('show-statistics') grok.require('cmf.ModifyPortalContent') grok.layer(IOSHAContentSkinLayer) schema = StatisticsSchema ignoreContext = True label = _('title_statistics', default='Statistics Reporting') label_detail = _('label_country', default=u'Country') template = None form_template = ViewPageTemplateFile("templates/statistics.pt") @button.buttonAndHandler(_(u"Submit"), condition=lambda form: form._is_tool_available()) def handleSubmit(self, action): return self._handleSubmit() def render(self): if not self._is_tool_available(): IStatusMessage(self.request).add( "No statistics are available as no tools have been " "published yet", type=u'warning') if self.pdf_data is not None: return self.pdf_data else: self.template = self.form_template return self.template()
class IReportPeriod(interface.Interface): year = schema.Choice( title=_(u'label_year', default=u'Year'), vocabulary='osha.oira.report_year', required=True, ) period = schema.Choice(title=_(u'label_period', default=u'Period'), vocabulary='osha.oira.report_period')
def __call__(self, context): t = lambda txt: translate(txt, context=api.portal.get().REQUEST) types = {t(_("OiRA Tool")).encode("utf-8"): "tool"} if ISectorContainer.providedBy(context): types.update({t(_("EU-OSHA Overview")).encode("utf-8"): "overview", t(_("Country")): "country"}) elif ICountry.providedBy(context): types.update({t(_("Country")).encode("utf-8"): "country"}) return SimpleVocabulary.fromItems(types.items())
def enable_custom_risks_on_all_modules(context): """ """ if not api.portal.get_registry_record("euphorie.allow_user_defined_risks"): log.warning( "Custom risks are not enabled. Set 'allow_user_defined_risks' to " "true in euphorie.ini for enabling them." ) return portal = api.portal.get() client = portal.client count = 0 for country in client.objectValues(): if IClientCountry.providedBy(country): for sector in country.objectValues(): if IClientSector.providedBy(sector): for survey in sector.objectValues(): try: is_new = EnableCustomRisks(survey) count += 1 custom = getattr(survey, "custom-risks", None) if custom: custom.title = _( "title_other_risks", default="Added risks (by you)", ) custom.description = _( "description_other_risks", default="In case you have identified risks not included in " # noqa: E501 "the tool, you are able to add them now:", ) custom.question = _( "question_other_risks", default="<p>Would you now like to add your own defined risks " # noqa: E501 "to this tool?</p><p><strong>Important:</strong> In " # noqa: E501 "order to avoid duplicating risks, we strongly recommend you " # noqa: E501 "to go first through all the previous modules, if you have not " # noqa: E501 "done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>", # noqa: E501 ) if is_new: survey.published = ( survey.id, survey.title, datetime.datetime.now(), ) except Exception as e: log.error( "Could not enable custom risks for module. %s" % e ) log.info("All %d published surveys can now have custom risks." % count) session = Session() if TableExists(session, "tree"): session.execute( "UPDATE tree SET title = 'title_other_risks' WHERE zodb_path ='custom-risks'" # noqa: E501 ) model.metadata.create_all(session.bind, checkfirst=True) datamanager.mark_changed(session) transaction.get().commit() log.info("Set correct title on all exisiting sessions for custom risks module.")
def addConsultationBox(self, section, document): """ Add the consultation box that needs to be signed by the employer and workers. """ ss = document.StyleSheet styles = document.StyleSheet.ParagraphStyles thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) table = Table(9500) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) no_edge = BorderPropertySet(width=0, colour=ss.Colours.White) p = Paragraph( styles.Heading3, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), t(_("header_oira_report_consultation", default="Consultation of workers")) ) c = Cell(p, FramePropertySet(thin_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t(_("paragraph_oira_consultation_of_workers", default="The undersigned hereby declare that the workers " "have been consulted on the content of this " "document.")), LINE ) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), ) employer = t(_("oira_consultation_employer", default="On behalf of the employer:")) workers = t(_("oira_consultation_workers", default="On behalf of the workers:")) p.append(employer, TAB, TAB, TAB, TAB, workers, LINE, LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t(_("oira_survey_date", default="Date:")), LINE, LINE ) c = Cell(p, FramePropertySet(no_edge, thin_edge, thin_edge, thin_edge)) table.AddRow(c) section.append(table)
def addConsultationBox(self, section, document): """ Add the consultation box that needs to be signed by the employer and workers. """ ss = document.StyleSheet styles = document.StyleSheet.ParagraphStyles thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) table = Table(9500) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) no_edge = BorderPropertySet(width=0, colour=ss.Colours.White) p = Paragraph( styles.Heading3, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), t( _("header_oira_report_consultation", default="Consultation of workers"))) c = Cell(p, FramePropertySet(thin_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t( _("paragraph_oira_consultation_of_workers", default="The undersigned hereby declare that the workers " "have been consulted on the content of this " "document.")), LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), ) employer = t( _("oira_consultation_employer", default="On behalf of the employer:")) workers = t( _("oira_consultation_workers", default="On behalf of the workers:")) p.append(employer, TAB, TAB, TAB, TAB, workers, LINE, LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t(_("oira_survey_date", default="Date:")), LINE, LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, thin_edge, thin_edge)) table.AddRow(c) section.append(table)
def __call__(self, context): t = lambda txt: translate(txt, context=api.portal.get().REQUEST) types = {t(_('OiRA Tool')).encode('utf-8'): 'tool'} if ISectorContainer.providedBy(context): types.update({ t(_('EU-OSHA Overview')).encode('utf-8'): 'overview', t(_('Country')): 'country' }) elif ICountry.providedBy(context): types.update({t(_('Country')).encode('utf-8'): 'country'}) return SimpleVocabulary.fromItems(types.items())
def __call__(self, context): t = lambda txt: translate(txt, context=api.portal.get().REQUEST) types = {t(_('Survey')).encode('utf-8'): 'tool'} if ISectorContainer.providedBy(context): types.update({ t(_('EU-OSHA Overview')).encode('utf-8'): 'overview', t(_('Country')): 'country' }) elif ICountry.providedBy(context): types.update({t(_('Country')).encode('utf-8'): 'country'}) return SimpleVocabulary.fromItems(types.items())
def __call__(self, context): t = lambda txt: translate(txt, context=site.REQUEST) site = api.portal.get() cal = site.REQUEST.locale.dates.calendars["gregorian"] items = [(t(_(u"Whole year")), 0)] items += [(m.encode("utf-8"), i + 1) for i, m in enumerate(cal.getMonthNames())] items += [(t(_(u"1st Quarter")).encode("utf-8"), i + 2)] items += [(t(_(u"2nd Quarter")).encode("utf-8"), i + 3)] items += [(t(_(u"3rd Quarter")).encode("utf-8"), i + 4)] items += [(t(_(u"4th Quarter")).encode("utf-8"), i + 5)] terms = [SimpleVocabulary.createTerm(value, value, token) for (token, value) in items] return SimpleVocabulary(terms)
def statistics(self): context = aq_inner(self.context) request = self.request try: # We do a permission check by trying to render the view getMultiAdapter((context, request), name="show-statistics") except ComponentLookupError: return menu = {"title": _("menu_admin", default=u"Admin")} menu["children"] = [{ "title": _("menu_statistics", default=u"Statistics"), "url": "%s/@@show-statistics" % context.absolute_url() }] return menu
def addMeasure(self, document, heading, section, measure): """ Requirements for how the measure section should be displayed are in #2611 """ t = lambda txt: "".join(["\u%s?" % str(ord(e)) for e in translate(txt, context=self.request)]) ss = document.StyleSheet styles = ss.ParagraphStyles table = Table(9500) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) no_edge = BorderPropertySet(width=0, colour=ss.Colours.White) p = Paragraph( styles.MeasureHeading, ParagraphPropertySet(left_indent=300, right_indent=300), t(_("header_measure_single", default=u"Measure")), ) c = Cell(p, FramePropertySet(thin_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) ss = document.StyleSheet styles = document.StyleSheet.ParagraphStyles headings = [ t(_("label_measure_action_plan", default=u"General approach (to " u"eliminate or reduce the risk)")), t( _( "label_measure_prevention_plan", default=u"Specific action(s) " u"required to implement this approach", ) ), t(_("label_measure_requirements", default=u"Level of expertise " u"and/or requirements needed")), t(_("label_action_plan_responsible", default=u"Who is " u"responsible?")), t(_("label_action_plan_budget", default=u"Budget")), t(_("label_action_plan_start", default=u"Planning start")), t(_("label_action_plan_end", default=u"Planning end")), ] m = measure values = [ m.action_plan, m.prevention_plan, m.requirements, m.responsible, m.budget and str(m.budget) or "", m.planning_start and formatDate(self.request, m.planning_start) or "", m.planning_end and formatDate(self.request, m.planning_end) or "", ] for heading, value in zip(headings, values): p = Paragraph(styles.MeasureField, heading) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) if headings.index(heading) == len(headings) - 1: frame = FramePropertySet(no_edge, thin_edge, thin_edge, thin_edge) else: frame = FramePropertySet(no_edge, thin_edge, no_edge, thin_edge) p = Paragraph(styles.Normal, ParagraphPropertySet(left_indent=600, right_indent=600), value) c = Cell(p, frame) table.AddRow(c) section.append(table)
def createSection(document, survey, request): t = lambda txt: "".join(["\u%s?" % str(ord(e)) for e in translate(txt, context=request)]) section = Section(break_type=Section.PAGE, first_page_number=1) footer_txt = t( _( "report_survey_revision", default=u"This report was based on the OiRA Tool '${title}' " u"of revision date ${date}.", mapping={"title": survey.published[1], "date": formatDate(request, survey.published[2])}, ) ) header = Table(4750, 4750) c1 = Cell(Paragraph(document.StyleSheet.ParagraphStyles.Footer, survey.published[1])) pp = ParagraphPropertySet header_props = pp(alignment=pp.RIGHT) c2 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, header_props, formatDate(request, datetime.today())) ) header.AddRow(c1, c2) section.Header.append(header) footer = Table(9000, 500) # rtfng does not like unicode footers c1 = Cell(Paragraph(document.StyleSheet.ParagraphStyles.Footer, pp(alignment=pp.LEFT), footer_txt)) c2 = Cell(Paragraph(pp(alignment=pp.RIGHT), PAGE_NUMBER)) footer.AddRow(c1, c2) section.Footer.append(footer) document.Sections.append(section) return section
def __call__(self, context): t = lambda txt: translate(txt, context=site.REQUEST) site = api.portal.get() cal = site.REQUEST.locale.dates.calendars['gregorian'] items = [(t(_(u'Whole year')), 0)] items += [(m.encode('utf-8'), i + 1) for i, m in enumerate(cal.getMonthNames())] items += [(t(_(u'1st Quarter')).encode('utf-8'), i + 2)] items += [(t(_(u'2nd Quarter')).encode('utf-8'), i + 3)] items += [(t(_(u'3rd Quarter')).encode('utf-8'), i + 4)] items += [(t(_(u'4th Quarter')).encode('utf-8'), i + 5)] terms = [ SimpleVocabulary.createTerm(value, value, token) for (token, value) in items ] return SimpleVocabulary(terms)
class CountryStatistics(StatisticsMixin): """Country managers can access statistics for their countries and tools inside their respective countries, but nowhere else.. """ label = _("title_statistics", default="Statistics Reporting") label_detail = _("label_country", default="Country") def __call__(self): if not self._is_tool_available(): IStatusMessage(self.request).add( "No statistics are available as no tools have been published yet", type="warning", ) return self.index()
class SectorStatistics(StatisticsMixin): """Sector accounts/managers can access statistics for tools in their sector, but nowhere else. """ label = _("title_statistics", default="Statistics Reporting") label_detail = _("Sector", default="Sector") def __call__(self): if not self._is_tool_available(): IStatusMessage(self.request).add( "No statistics are available as no tools have been published yet", type="warning", ) return self.index()
def createIdentificationReportSection(document, survey, request): t = lambda txt: "".join(["\u%s?" % str(ord(e)) for e in translate(txt, context=request)]) section = Section() footer_txt = t( _( "report_identification_revision", default=u"This document was based on the OiRA Tool '${title}' of " u"revision date ${date}.", mapping={"title": survey.published[1], "date": formatDate(request, survey.published[2])}, ) ) header = Table(4750, 4750) c1 = Cell(Paragraph(document.StyleSheet.ParagraphStyles.Footer, SessionManager.session.title)) pp = ParagraphPropertySet header_props = pp(alignment=pp.RIGHT) c2 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, header_props, formatDate(request, datetime.today())) ) header.AddRow(c1, c2) section.Header.append(header) footer = Table(9000, 500) c1 = Cell(Paragraph(document.StyleSheet.ParagraphStyles.Footer, pp(alignment=pp.LEFT), footer_txt)) c2 = Cell(Paragraph(pp(alignment=pp.RIGHT), PAGE_NUMBER)) footer.AddRow(c1, c2) section.Footer.append(footer) section.SetBreakType(section.PAGE) document.Sections.append(section) return section
def enable_custom_risks_on_all_modules(context): """ """ appconfig = zope.component.getUtility(IAppConfig) if not asBool(appconfig["euphorie"].get("allow_user_defined_risks")): log.warning( "Custom risks are not enabled. Set 'allow_user_defined_risks' to " "true in euphorie.ini for enabling them.") return portal = api.portal.get() client = portal.client count = 0 for country in client.objectValues(): if IClientCountry.providedBy(country): for sector in country.objectValues(): if IClientSector.providedBy(sector): for survey in sector.objectValues(): try: is_new = EnableCustomRisks(survey) count += 1 custom = getattr(survey, 'custom-risks', None) if custom: custom.title = _( u'title_other_risks', default=u"Added risks (by you)") custom.description = _( u"description_other_risks", default= u"In case you have identified risks not included in " u"the tool, you are able to add them now:") custom.question = _( u"question_other_risks", default= u"<p>Would you now like to add your own defined risks " u"to this tool?</p><p><strong>Important:</strong> In " u"order to avoid duplicating risks, we strongly recommend you " u"to go first through all the previous modules, if you have not " u"done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>" ) if is_new: survey.published = (survey.id, survey.title, datetime.datetime.now()) except Exception, e: log.error( "Could not enable custom risks for module. %s" % e)
class StatisticsSchema(form.Schema): report_type = schema.Choice( title=_(u'label_report_type', default=u'Report Type'), vocabulary='osha.oira.report_type', required=True, ) countries = schema.Choice( title=_(u'label_report_countries', default=u'Country'), vocabulary='osha.oira.countries', required=True, ) form.widget(countries=SelectFieldWidget) tools = schema.Choice( title=_(u'label_report_tools', default=u'Tool'), vocabulary='osha.oira.publishedtools', required=True, ) form.widget(tools=SelectFieldWidget) report_period = schema.Object( title=_(u'label_report_period', default=u"Report Period"), schema=IReportPeriod, ) file_format = schema.Choice( title=_(u'label_report_file_format', default=u'File Format'), vocabulary='osha.oira.report_file_format', required=True, ) form.widget(file_format=SelectFieldWidget) test_sessions = schema.Choice( title=u"How to treat test sessions", vocabulary=SimpleVocabulary([ SimpleTerm(0, title=u"Exclude test sessions from statistics"), SimpleTerm( 1, title=u"Create statistics exclusively for test sessions"), ]), required=True, default=0, )
def create_workbook(self): """Create an Excel workbook containing the all risks and measures. """ t = lambda txt: translate(txt, context=self.request) book = Workbook() sheet = book.worksheets[0] sheet.title = t(_("report_timeline_title", default=u"Timeline")) sheet.default_column_dimension.auto_size = True for (column, (type, key, title)) in enumerate(self.columns): if key in self.combine_keys: continue cell = sheet.cell(row=0, column=column) cell.value = t(title) cell.style.font.bold = True cell.style.alignment.wrap_text = True letter = get_column_letter(column + 1) if title == "report_timeline_measure": sheet.column_dimensions[letter].width = len(cell.value) + 50 else: sheet.column_dimensions[letter].width = len(cell.value) + 5 for (row, (module, risk, measure)) in enumerate(self.get_measures(), 1): column = 0 zodb_node = self.request.survey.restrictedTraverse(risk.zodb_path.split("/")) for (type, key, title) in self.columns + self.extra_cols: value = None if type == "measure": value = getattr(measure, key, None) elif type == "risk": value = getattr(risk, key, None) if key == "priority": value = self.priority_name(value) elif key == "title": if zodb_node.problem_description and zodb_node.problem_description.strip(): value = zodb_node.problem_description elif type == "module": value = getattr(module, key, None) sheet.cell(row=row, column=column).style.alignment.wrap_text = True # style if key in self.combine_keys and value is not None: # osha wants to combine action_plan (col 3), # prevention_plan and requirements in one cell if not sheet.cell(row=row, column=2).value: sheet.cell(row=row, column=2).value = u"" sheet.cell(row=row, column=2).value += "\r\n" + value continue if value is not None: sheet.cell(row=row, column=column).value = value column += 1 return book
def setDynamicDescriptions(self): """Set the evaluation_method description depending on the evaluation algorithm (Kinney or French) """ evalgroup = self.groups[self.order.index("header_evaluation")] evalfield = evalgroup.fields.get("evaluation_method") if self.evaluation_algorithm == "kinney": evalfield.field.description = _( "help_evaluation_method_kinney", default="Choose between ESTIMATED (rough estimation) or " "CALCULATED (combination of probability, frequency " "and severity) method.", ) elif self.evaluation_algorithm == "french": evalfield.field.description = _( "help_evaluation_method_french", default="Choose between ESTIMATED (rough estimation) or " "CALCULATED (combination of frequency " "and severity) method.", )
def update(self): """ Fetches the different kinds of risks we are interested in. Actioned Nodes -------------- Title: "Risks that have been identified, evaluated and have an Action Plan" Unactioned Nodes ---------------- Title: "Risks that have been identified but do NOT have an Action Plan" Unanswered Nodes ---------------- Title: "Hazards/problems that have been "parked" and are still to be dealt with" Risk not present nodes ---------------------- Title: "Hazards/problems that have been managed or are not present in your organisation" """ if survey.redirectOnSurveyUpdate(self.request): return super(OSHAActionPlanReportDownload, self).update() # Returns all identified nodes, with or without action plans self.nodes = self.getNodes() # Get the extra attributes as per #1517, #1518: self.actioned_nodes = utils.get_actioned_nodes(self.nodes) self.unactioned_nodes = utils.get_unactioned_nodes(self.nodes) self.unanswered_nodes = utils.get_unanswered_nodes(self.session) risk_not_present_nodes = utils.get_risk_not_present_nodes(self.session) # From the non-present risks, filter out risks from the (un-)/actioned # categories. A "priority" risk will always appear in the action plan, # even if it has been answered with "Yes" self.risk_not_present_nodes = [ n for n in risk_not_present_nodes if n not in self.actioned_nodes and n not in self.unactioned_nodes ] lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) self.title_custom_risks = translate(_( 'title_other_risks', default=u'Added risks (by you)'), target_language=lang)
def update(self): """ Fetches the different kinds of risks we are interested in. Actioned Nodes -------------- Title: "Risks that have been identified, evaluated and have an Action Plan" Unactioned Nodes ---------------- Title: "Risks that have been identified but do NOT have an Action Plan" Unanswered Nodes ---------------- Title: "Hazards/problems that have been "parked" and are still to be dealt with" Risk not present nodes ---------------------- Title: "Hazards/problems that have been managed or are not present in your organisation" """ if survey.redirectOnSurveyUpdate(self.request): return super(OSHAActionPlanReportDownload, self).update() # Returns all identified nodes, with or without action plans self.nodes = self.getNodes() # Get the extra attributes as per #1517, #1518: self.actioned_nodes = utils.get_actioned_nodes(self.nodes) self.unactioned_nodes = utils.get_unactioned_nodes(self.nodes) self.unanswered_nodes = utils.get_unanswered_nodes(self.session) risk_not_present_nodes = utils.get_risk_not_present_nodes(self.session) # From the non-present risks, filter out risks from the (un-)/actioned # categories. A "priority" risk will always appear in the action plan, # even if it has been answered with "Yes" self.risk_not_present_nodes = [ n for n in risk_not_present_nodes if n not in self.actioned_nodes and n not in self.unactioned_nodes ] lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) self.title_custom_risks = translate(_('title_other_risks', default=u'Added risks (by you)'), target_language=lang)
class SectorStatistics(form.SchemaForm, StatisticsMixin): """ Sector accounts/managers can access statistics for tools in their sector, but nowhere else. """ grok.context(ISector) grok.name('show-statistics') grok.require('cmf.ModifyPortalContent') grok.layer(IOSHAContentSkinLayer) schema = StatisticsSchema ignoreContext = True label = _('title_statistics', default='Statistics Reporting') label_detail = _('Sector', default=u'Sector') template = None form_template = ViewPageTemplateFile("templates/statistics.pt") @button.buttonAndHandler(_(u"Submit"), condition=lambda form: form._is_tool_available()) def handleSubmit(self, action): return self._handleSubmit() def updateWidgets(self): super(SectorStatistics, self).updateWidgets() report_type = self.widgets.get('report_type') report_type.mode = 'hidden' report_type.field.default = 'tool' def render(self): if not self._is_tool_available(): IStatusMessage(self.request).add( "No statistics are available as no tools have been " "published yet", type=u'warning') if self.pdf_data is not None: return self.pdf_data else: self.template = self.form_template return self.template()
def enable_custom_risks_on_all_modules(context): """ """ appconfig = zope.component.getUtility(IAppConfig) if not asBool(appconfig["euphorie"].get("allow_user_defined_risks")): log.warning( "Custom risks are not enabled. Set 'allow_user_defined_risks' to " "true in euphorie.ini for enabling them.") return portal = api.portal.get() client = portal.client count = 0 for country in client.objectValues(): if IClientCountry.providedBy(country): for sector in country.objectValues(): if IClientSector.providedBy(sector): for survey in sector.objectValues(): try: is_new = EnableCustomRisks(survey) count += 1 custom = getattr(survey, 'custom-risks', None) if custom: custom.title = _(u'title_other_risks', default=u"Added risks (by you)") custom.description = _( u"description_other_risks", default=u"In case you have identified risks not included in " u"the tool, you are able to add them now:") custom.question = _( u"question_other_risks", default=u"<p>Would you now like to add your own defined risks " u"to this tool?</p><p><strong>Important:</strong> In " u"order to avoid duplicating risks, we strongly recommend you " u"to go first through all the previous modules, if you have not " u"done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>") if is_new: survey.published = ( survey.id, survey.title, datetime.datetime.now()) except Exception, e: log.error("Could not enable custom risks for module. %s" % e)
class GlobalStatistics(form.SchemaForm, StatisticsMixin): """ Site managers can access statistics for the whole site. """ grok.context(ISectorContainer) grok.name('show-statistics') grok.require('cmf.ModifyPortalContent') grok.layer(IOSHAContentSkinLayer) schema = StatisticsSchema ignoreContext = True label = _('title_statistics', default='Statistics Reporting') label_detail = _('label_global', default=u'Global') template = None form_template = ViewPageTemplateFile("templates/statistics.pt") @button.buttonAndHandler(_(u"Submit")) def handleSubmit(self, action): return self._handleSubmit() def render(self): if self.pdf_data is not None: return self.pdf_data else: self.template = self.form_template return self.template()
def createSection(document, survey, request, first_page_number=1): t = lambda txt: "".join( ["\u%s?" % str(ord(e)) for e in translate(txt, context=request)]) section = Section(break_type=Section.PAGE, first_page_number=first_page_number) footer_txt = t( _("report_survey_revision", default=u"This report was based on the OiRA Tool '${title}' "\ u"of revision date ${date}.", mapping={"title": survey.published[1], "date": formatDate(request, survey.published[2])})) header = Table(4750, 4750) c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, survey.published[1])) pp = ParagraphPropertySet header_props = pp(alignment=pp.RIGHT) c2 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, header_props, formatDate(request, datetime.today()))) header.AddRow(c1, c2) section.Header.append(header) footer = Table(9000, 500) # rtfng does not like unicode footers c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, pp(alignment=pp.LEFT), footer_txt)) c2 = Cell(Paragraph(pp(alignment=pp.RIGHT), PAGE_NUMBER)) footer.AddRow(c1, c2) section.Footer.append(footer) document.Sections.append(section) return section
def createIdentificationReportSection(document, survey, request): t = lambda txt: "".join( ["\u%s?" % str(ord(e)) for e in translate(txt, context=request)]) section = Section() footer_txt = t( _("report_identification_revision", default=u"This document was based on the OiRA Tool '${title}' of " u"revision date ${date}.", mapping={ "title": survey.published[1], "date": formatDate(request, survey.published[2]) })) header = Table(4750, 4750) c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, SessionManager.session.title)) pp = ParagraphPropertySet header_props = pp(alignment=pp.RIGHT) c2 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, header_props, formatDate(request, datetime.today()))) header.AddRow(c1, c2) section.Header.append(header) footer = Table(9000, 500) c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, pp(alignment=pp.LEFT), footer_txt)) c2 = Cell(Paragraph(pp(alignment=pp.RIGHT), PAGE_NUMBER)) footer.AddRow(c1, c2) section.Footer.append(footer) section.SetBreakType(section.PAGE) document.Sections.append(section) return section
def addReportNodes(self, document, nodes, heading, toc, body): """ """ t = lambda txt: "".join(["\u%s?" % str(ord(e)) for e in translate(txt, context=self.request)]) ss = document.StyleSheet toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) p.append(character.Text(heading, TextPropertySet(italic=True))) toc.append(p) body.append(Paragraph(ss.ParagraphStyles.Heading1, heading)) survey = self.request.survey styles = ss.ParagraphStyles header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in nodes: zodb_node = survey.restrictedTraverse(node.zodb_path.split("/")) title = node_title(node, zodb_node) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) if node.depth == 1: p = Paragraph( header_styles.get(node.depth, styles.Heading6), FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge), u"%s %s" % (node.number, title), ) else: p = Paragraph(header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, title)) body.append(p) if node.type != "risk": continue if node.priority: if node.priority == "low": level = _("risk_priority_low", default=u"low") elif node.priority == "medium": level = _("risk_priority_medium", default=u"medium") elif node.priority == "high": level = _("risk_priority_high", default=u"high") msg = _( "risk_priority", default="This is a ${priority_value} priority risk.", mapping={"priority_value": level}, ) body.append(Paragraph(styles.RiskPriority, t(msg))) if getattr(node, "identification", None) == "no": body.append( Paragraph( styles.Normal, ParagraphPropertySet(left_indent=300, right_indent=300), t(_(utils.html_unescape(htmllaundry.StripMarkup(zodb_node.description)))), ) ) body.append(Paragraph("")) if node.comment and node.comment.strip(): body.append(Paragraph(styles.Comment, node.comment)) for (idx, measure) in enumerate(node.action_plans): if not measure.action_plan: continue if len(node.action_plans) == 1: heading = t(_("header_measure_single", default=u"Measure")) else: heading = t(_("header_measure", default=u"Measure ${index}", mapping={"index": idx + 1})) self.addMeasure(document, heading, body, measure)
def updateFields(self): super(EditForm, self).updateFields() self.buttons["save"].title = _("button_save_changes", default="Save changes") self.buttons["cancel"].title = _("button_cancel", default="Cancel")
def create_workbook(self): """Create an Excel workbook containing the all risks and measures.""" t = lambda txt: translate(txt, context=self.request) # noqa: E731 survey = self.webhelpers._survey book = Workbook() ws1 = book.active ws1.title = t(_("report_timeline_title", default="Timeline")) header_text = "{title}{extra} - {action_plan}".format( title=survey.title, extra=self.title_extra.strip(), action_plan=t(_("label_action_plan", default="Action Plan")), ) ws1["A1"] = header_text font_basic = ws1["A1"].font font_large = copy(font_basic) font_large.size = 18 ws1["A1"].font = font_large image_filename = resource_filename("osha.oira.client", "resources/oira-logo-colour.png") logo = Image(image_filename) ws1.add_image(logo, "K1") ws1.row_dimensions[1].height = 70 ws1.merge_cells("A1:K1") font_bold = copy(font_basic) font_bold.bold = True alignment_basic = ws1["A1"].alignment.copy() alignment_basic.wrap_text = True alignment_basic.vertical = "center" alignment_basic.horizontal = "left" alignment_header = copy(alignment_basic) alignment_header.horizontal = "center" ws1.cell(row=1, column=1).alignment = alignment_basic b_thin = Side(border_style="thin", color="000000") b_double = Side(border_style="medium", color="000000") ws1["A2"] = t(_("label_title", default="Title")) ws1["A2"].font = font_bold ws1["B2"] = self.session.title ws1["B2"].fill = PatternFill("solid", fgColor="DDDDDD") ws1.merge_cells("B2:C2") ws1["E2"] = t(_("label_report_date", default="Date of editing")) ws1["E2"].font = font_bold ws1["F2"] = formatDate(self.request, self.session.modified) ws1["F2"].fill = PatternFill("solid", fgColor="DDDDDD") for cell in tuple(ws1.iter_rows(2, 2))[0]: cell.alignment = alignment_basic ws1.row_dimensions[2].height = 30 for (column, (type, key, title)) in enumerate(self.columns, 1): if key in self.combine_keys: continue cell = ws1.cell(row=3, column=column) cell.value = t(title) cell.font = font_bold cell.alignment = alignment_header # Light baby blue background color cell.fill = PatternFill("solid", fgColor="97CDDD") cell.border = Border(top=b_double, left=b_double, right=b_double, bottom=b_double) letter = get_column_letter(column) if title in ("report_timeline_measure", "report_timeline_risk_title"): ws1.column_dimensions[letter].width = len(cell.value) + 50 elif title in ("label_risk_number", ): ws1.column_dimensions[letter].width = len(cell.value) else: ws1.column_dimensions[letter].width = len(cell.value) + 5 ws1.row_dimensions[3].height = 60 for (row, (module, risk, measure)) in enumerate(self.get_measures(), 4): column = 1 if not getattr(risk, "is_custom_risk", None): zodb_node = self.context.restrictedTraverse( risk.zodb_path.split("/")) else: zodb_node = None for (type, key, title) in self.columns + self.extra_cols: value = None if type == "measure": value = getattr(measure, key, None) elif type == "risk": value = getattr(risk, key, None) if key == "priority": value = self.priority_name(value) elif key == "title": if zodb_node is None: value = getattr(risk, key, None) elif (zodb_node.problem_description and zodb_node.problem_description.strip()): value = zodb_node.problem_description elif key == "number": if risk.is_custom_risk: num_elems = value.split(".") value = ".".join(["Ω"] + num_elems[1:]) elif type == "module": if key == "title" and module.depth > 1: titles = [] m = module while m: title = getattr(m, "title", None) if title: titles.append(m.title) m = m.parent titles.reverse() value = ", ".join(titles) else: if module.zodb_path == "custom-risks": lang = getattr(self.request, "LANGUAGE", "en") if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format( elems[0], elems[1].upper()) value = translate( _("Custom risks", default="Custom risks"), target_language=lang, ) else: value = getattr(module, key, None) if key in self.combine_keys: if value is not None: # osha wants to combine action_plan (col 5 / E), # and requirements in one cell if not ws1.cell(row=row, column=5).value: ws1.cell(row=row, column=5).value = "" ws1.cell(row=row, column=5).value += "\r\n" + value else: cell = ws1.cell(row=row, column=column) if value is not None: if key == "number": # force string cell.set_explicit_value(value) else: cell.value = value if key == "budget": cell.style = "Comma" cell.alignment = alignment_basic cell.border = Border(top=b_thin, left=b_thin, right=b_thin, bottom=b_thin) column += 1 ws1.freeze_panes = "A4" ws1.set_printer_settings(paper_size=ws1.PAPERSIZE_A4, orientation="landscape") return book
class ActionPlanTimeline(report.ActionPlanTimeline): title_extra = "" combine_keys = ["requirements"] extra_cols = [ ( "measure", "requirements", _( "label_measure_requirements", default="Level of expertise and/or requirements needed", ), ), ] columns = [ ("module", "title", _("label_section", default="Section")), ( "risk", "title", _("report_timeline_risk_title", default="Description of the risk"), ), ("risk", "number", _("label_risk_number", default="Risk number")), ("risk", "priority", _("report_timeline_priority", default="Priority")), ( "measure", "action", _( "report_timeline_measure", default="Measure", ), ), ( "measure", "planning_start", _("report_timeline_start_date", default="Start date"), ), ( "measure", "planning_end", _("report_timeline_end_date", default="End date"), ), ( "measure", "responsible", _("report_timeline_responsible", default="Responsible"), ), ("measure", "budget", _("label_action_plan_budget", default="Budget")), ( None, None, _( "report_timeline_progress", default="Status (planned, in process, implemented)", ), ), ("risk", "comment", _("report_timeline_comment", default="Comments")), ] def create_workbook(self): """Create an Excel workbook containing the all risks and measures.""" t = lambda txt: translate(txt, context=self.request) # noqa: E731 survey = self.webhelpers._survey book = Workbook() ws1 = book.active ws1.title = t(_("report_timeline_title", default="Timeline")) header_text = "{title}{extra} - {action_plan}".format( title=survey.title, extra=self.title_extra.strip(), action_plan=t(_("label_action_plan", default="Action Plan")), ) ws1["A1"] = header_text font_basic = ws1["A1"].font font_large = copy(font_basic) font_large.size = 18 ws1["A1"].font = font_large image_filename = resource_filename("osha.oira.client", "resources/oira-logo-colour.png") logo = Image(image_filename) ws1.add_image(logo, "K1") ws1.row_dimensions[1].height = 70 ws1.merge_cells("A1:K1") font_bold = copy(font_basic) font_bold.bold = True alignment_basic = ws1["A1"].alignment.copy() alignment_basic.wrap_text = True alignment_basic.vertical = "center" alignment_basic.horizontal = "left" alignment_header = copy(alignment_basic) alignment_header.horizontal = "center" ws1.cell(row=1, column=1).alignment = alignment_basic b_thin = Side(border_style="thin", color="000000") b_double = Side(border_style="medium", color="000000") ws1["A2"] = t(_("label_title", default="Title")) ws1["A2"].font = font_bold ws1["B2"] = self.session.title ws1["B2"].fill = PatternFill("solid", fgColor="DDDDDD") ws1.merge_cells("B2:C2") ws1["E2"] = t(_("label_report_date", default="Date of editing")) ws1["E2"].font = font_bold ws1["F2"] = formatDate(self.request, self.session.modified) ws1["F2"].fill = PatternFill("solid", fgColor="DDDDDD") for cell in tuple(ws1.iter_rows(2, 2))[0]: cell.alignment = alignment_basic ws1.row_dimensions[2].height = 30 for (column, (type, key, title)) in enumerate(self.columns, 1): if key in self.combine_keys: continue cell = ws1.cell(row=3, column=column) cell.value = t(title) cell.font = font_bold cell.alignment = alignment_header # Light baby blue background color cell.fill = PatternFill("solid", fgColor="97CDDD") cell.border = Border(top=b_double, left=b_double, right=b_double, bottom=b_double) letter = get_column_letter(column) if title in ("report_timeline_measure", "report_timeline_risk_title"): ws1.column_dimensions[letter].width = len(cell.value) + 50 elif title in ("label_risk_number", ): ws1.column_dimensions[letter].width = len(cell.value) else: ws1.column_dimensions[letter].width = len(cell.value) + 5 ws1.row_dimensions[3].height = 60 for (row, (module, risk, measure)) in enumerate(self.get_measures(), 4): column = 1 if not getattr(risk, "is_custom_risk", None): zodb_node = self.context.restrictedTraverse( risk.zodb_path.split("/")) else: zodb_node = None for (type, key, title) in self.columns + self.extra_cols: value = None if type == "measure": value = getattr(measure, key, None) elif type == "risk": value = getattr(risk, key, None) if key == "priority": value = self.priority_name(value) elif key == "title": if zodb_node is None: value = getattr(risk, key, None) elif (zodb_node.problem_description and zodb_node.problem_description.strip()): value = zodb_node.problem_description elif key == "number": if risk.is_custom_risk: num_elems = value.split(".") value = ".".join(["Ω"] + num_elems[1:]) elif type == "module": if key == "title" and module.depth > 1: titles = [] m = module while m: title = getattr(m, "title", None) if title: titles.append(m.title) m = m.parent titles.reverse() value = ", ".join(titles) else: if module.zodb_path == "custom-risks": lang = getattr(self.request, "LANGUAGE", "en") if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format( elems[0], elems[1].upper()) value = translate( _("Custom risks", default="Custom risks"), target_language=lang, ) else: value = getattr(module, key, None) if key in self.combine_keys: if value is not None: # osha wants to combine action_plan (col 5 / E), # and requirements in one cell if not ws1.cell(row=row, column=5).value: ws1.cell(row=row, column=5).value = "" ws1.cell(row=row, column=5).value += "\r\n" + value else: cell = ws1.cell(row=row, column=column) if value is not None: if key == "number": # force string cell.set_explicit_value(value) else: cell.value = value if key == "budget": cell.style = "Comma" cell.alignment = alignment_basic cell.border = Border(top=b_thin, left=b_thin, right=b_thin, bottom=b_thin) column += 1 ws1.freeze_panes = "A4" ws1.set_printer_settings(paper_size=ws1.PAPERSIZE_A4, orientation="landscape") return book def get_measures(self): """Find all data that should be included in the report. The data is returned as a list of tuples containing a :py:class:`Module <euphorie.client.model.Module>`, :py:class:`Risk <euphorie.client.model.Risk>` and :py:class:`ActionPlan <euphorie.client.model.ActionPlan>`. Each entry in the list will correspond to a row in the generated Excel file. This implementation differs from Euphorie in its ordering: it sorts on risk priority instead of start date. """ query = (Session.query( model.Module, model.Risk, model.ActionPlan).select_from(model.Module).filter( sql.and_( model.Module.session == self.session, model.Module.profile_index > -1, )).filter(sql.not_(model.SKIPPED_PARENTS)).filter( sql.or_( model.MODULE_WITH_RISK_OR_TOP5_FILTER, model.RISK_PRESENT_OR_TOP5_FILTER, )).join(model.Risk, model.Risk.parent_id == model.Module.id). join(( model.ActionPlan, sql.and_( model.ActionPlan.risk_id == model.Risk.id, sql.or_( model.ActionPlan.plan_type == "measure_standard", model.ActionPlan.plan_type == "measure_custom", ), ), )).order_by( sql.case(value=model.Risk.priority, whens={ "high": 0, "medium": 1 }, else_=2), model.Risk.path, )) return [ t for t in query.all() if ((t[-1].planning_start is not None or t[-1].planning_end is not None or t[-1].responsible is not None or t[-1].requirements is not None or t[-1].budget is not None or t[-1].action is not None) and ( t[1].identification == "no" or t[1].risk_type == "top5")) ]
def label(self): return _("Edit Solution", default="Edit Measure")
class ActionPlanTimeline(report.ActionPlanTimeline): grok.layer(IOSHAReportPhaseSkinLayer) combine_keys = ['prevention_plan', 'requirements'] columns = sorted((col for col in report.ActionPlanTimeline.columns if (col[0], col[1]) in COLUMN_ORDER), key=lambda d, co=COLUMN_ORDER: co.index((d[0], d[1]))) extra_cols = [x for x in columns if x[1] in combine_keys] columns = [x for x in columns if x[1] not in combine_keys] columns[2] = ('measure', 'action_plan', _('report_timeline_measure', default=u'Measure')) columns[3] = ('measure', 'planning_start', _('report_timeline_start_date', default=u'Start date')) columns[4] = ('measure', 'planning_end', _('report_timeline_end_date', default=u'End date')) columns[5] = ('measure', 'responsible', _('report_timeline_responsible', default=u'Responsible')) columns.insert(-1, (None, None, _('report_timeline_progress', default=u'Status (planned, in process, implemented)'))) def create_workbook(self): """Create an Excel workbook containing the all risks and measures. """ t = lambda txt: translate(txt, context=self.request) book = Workbook() sheet = book.worksheets[0] sheet.title = t(_('report_timeline_title', default=u'Timeline')) sheet.default_column_dimension.auto_size = True for (column, (type, key, title)) in enumerate(self.columns): if key in self.combine_keys: continue cell = sheet.cell(row=0, column=column) cell.value = t(title) cell.style.font.bold = True cell.style.alignment.wrap_text = True letter = get_column_letter(column + 1) if title == 'report_timeline_measure': sheet.column_dimensions[letter].width = len(cell.value) + 50 else: sheet.column_dimensions[letter].width = len(cell.value) + 5 for (row, (module, risk, measure)) in \ enumerate(self.get_measures(), 1): column = 0 if not getattr(risk, 'is_custom_risk', None): zodb_node = self.request.survey.restrictedTraverse( risk.zodb_path.split('/')) else: zodb_node = None for (type, key, title) in self.columns + self.extra_cols: value = None if type == 'measure': value = getattr(measure, key, None) elif type == 'risk': value = getattr(risk, key, None) if key == 'priority': value = self.priority_name(value) elif key == 'title': if zodb_node is None: value = getattr(risk, key, None) elif zodb_node.problem_description and \ zodb_node.problem_description.strip(): value = zodb_node.problem_description elif type == 'module': if key == 'title' and module.depth > 1: titles = [] m = module while m: title = getattr(m, 'title', None) if title: titles.append(m.title) m = m.parent titles.reverse() value = ', '.join(titles) else: if module.zodb_path == 'custom-risks': lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format( elems[0], elems[1].upper()) value = translate(_( 'title_other_risks', default=u'Added risks (by you)'), target_language=lang) else: value = getattr(module, key, None) sheet.cell(row=row, column=column)\ .style.alignment.wrap_text = True # style if key in self.combine_keys and value is not None: # osha wants to combine action_plan (col 3), # prevention_plan and requirements in one cell if not sheet.cell(row=row, column=2).value: sheet.cell(row=row, column=2).value = u'' sheet.cell(row=row, column=2).value += '\r\n' + value continue if value is not None: sheet.cell(row=row, column=column).value = value column += 1 return book def get_measures(self): """Find all data that should be included in the report. The data is returned as a list of tuples containing a :py:class:`Module <euphorie.client.model.Module>`, :py:class:`Risk <euphorie.client.model.Risk>` and :py:class:`ActionPlan <euphorie.client.model.ActionPlan>`. Each entry in the list will correspond to a row in the generated Excel file. This implementation differs from Euphorie in its ordering: it sorts on risk priority instead of start date. """ query = Session.query(model.Module, model.Risk, model.ActionPlan)\ .filter(sql.and_(model.Module.session == self.session, model.Module.profile_index > -1))\ .filter(sql.not_(model.SKIPPED_PARENTS))\ .filter(sql.or_(model.MODULE_WITH_RISK_OR_TOP5_FILTER, model.RISK_PRESENT_OR_TOP5_FILTER))\ .join((model.Risk, sql.and_(model.Risk.path.startswith(model.Module.path), model.Risk.depth == model.Module.depth+1, model.Risk.session == self.session)))\ .join((model.ActionPlan, model.ActionPlan.risk_id == model.Risk.id))\ .order_by( sql.case( value=model.Risk.priority, whens={'high': 0, 'medium': 1}, else_=2), model.Risk.path) return [ t for t in query.all() if ((t[-1].planning_start is not None or t[-1].planning_end is not None or t[-1].responsible is not None or t[-1]. prevention_plan is not None or t[-1].requirements is not None or t[-1].budget is not None or t[-1].action_plan is not None) and (t[1].identification == 'no' or t[1].risk_type == 'top5')) ]
def addReportNodes(self, document, nodes, heading, toc, body): """ """ t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) ss = document.StyleSheet toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) p.append(character.Text(heading, TextPropertySet(italic=True))) toc.append(p) body.append(Paragraph(ss.ParagraphStyles.Heading1, heading)) survey = self.request.survey styles = ss.ParagraphStyles header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in nodes: zodb_node = None if node.zodb_path == 'custom-risks': title = self.title_custom_risks elif getattr(node, 'is_custom_risk', None): title = node.title else: zodb_node = survey.restrictedTraverse( node.zodb_path.split("/")) title = node_title(node, zodb_node) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) if node.depth == 1: p = Paragraph( header_styles.get(node.depth, styles.Heading6), FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge), u"%s %s" % (node.number, title)) else: p = Paragraph(header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, title)) body.append(p) if node.type != "risk": continue if node.priority: if node.priority == "low": level = _("risk_priority_low", default=u"low") elif node.priority == "medium": level = _("risk_priority_medium", default=u"medium") elif node.priority == "high": level = _("risk_priority_high", default=u"high") msg = _("risk_priority", default="This is a ${priority_value} priority risk.", mapping={'priority_value': level}) body.append(Paragraph(styles.RiskPriority, t(msg))) # In the report for Italy, don't print the description if (getattr(node, 'identification', None) == 'no' and not IOSHAItalyReportPhaseSkinLayer.providedBy( self.request)): if zodb_node is None: description = node.title else: description = zodb_node.description body.append( Paragraph( styles.Normal, ParagraphPropertySet(left_indent=300, right_indent=300), t( _( utils.html_unescape( htmllaundry.StripMarkup(description)))))) body.append(Paragraph("")) if node.comment and node.comment.strip(): body.append(Paragraph(styles.Comment, node.comment)) for (idx, measure) in enumerate(node.action_plans): if not measure.action_plan: continue if len(node.action_plans) == 1: heading = t(_("header_measure_single", default=u"Measure")) else: heading = t( _("header_measure", default=u"Measure ${index}", mapping={"index": idx + 1})) self.addMeasure(document, heading, body, measure)
class GlobalStatistics(StatisticsMixin): """Site managers can access statistics for the whole site.""" label = _("title_statistics", default="Statistics Reporting") label_detail = _("label_global", default="Global") title_detail = None
def label(self): return _("Add Solution", default="Add Measure")
def create_workbook(self): """Create an Excel workbook containing the all risks and measures. """ t = lambda txt: translate(txt, context=self.request) book = Workbook() sheet = book.worksheets[0] sheet.title = t(_('report_timeline_title', default=u'Timeline')) sheet.default_column_dimension.auto_size = True for (column, (type, key, title)) in enumerate(self.columns): if key in self.combine_keys: continue cell = sheet.cell(row=0, column=column) cell.value = t(title) cell.style.font.bold = True cell.style.alignment.wrap_text = True letter = get_column_letter(column + 1) if title == 'report_timeline_measure': sheet.column_dimensions[letter].width = len(cell.value) + 50 else: sheet.column_dimensions[letter].width = len(cell.value) + 5 for (row, (module, risk, measure)) in \ enumerate(self.get_measures(), 1): column = 0 if not getattr(risk, 'is_custom_risk', None): zodb_node = self.request.survey.restrictedTraverse( risk.zodb_path.split('/')) else: zodb_node = None for (type, key, title) in self.columns + self.extra_cols: value = None if type == 'measure': value = getattr(measure, key, None) elif type == 'risk': value = getattr(risk, key, None) if key == 'priority': value = self.priority_name(value) elif key == 'title': if zodb_node is None: value = getattr(risk, key, None) elif zodb_node.problem_description and \ zodb_node.problem_description.strip(): value = zodb_node.problem_description elif type == 'module': if key == 'title' and module.depth > 1: titles = [] m = module while m: title = getattr(m, 'title', None) if title: titles.append(m.title) m = m.parent titles.reverse() value = ', '.join(titles) else: if module.zodb_path == 'custom-risks': lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format( elems[0], elems[1].upper()) value = translate(_( 'title_other_risks', default=u'Added risks (by you)'), target_language=lang) else: value = getattr(module, key, None) sheet.cell(row=row, column=column)\ .style.alignment.wrap_text = True # style if key in self.combine_keys and value is not None: # osha wants to combine action_plan (col 3), # prevention_plan and requirements in one cell if not sheet.cell(row=row, column=2).value: sheet.cell(row=row, column=2).value = u'' sheet.cell(row=row, column=2).value += '\r\n' + value continue if value is not None: sheet.cell(row=row, column=column).value = value column += 1 return book
def render(self): """ Mostly a copy of the render method in OSHAActionPlanReportDownload, but with some changes to handle the special reqs of Italy """ document = report.createDocument(self.session) ss = document.StyleSheet # Define some more custom styles ss.ParagraphStyles.append( ParagraphStyle( "RiskPriority", TextStyle( TextPropertySet( font=ss.Fonts.Arial, size=22, italic=True, colour=ss.Colours.Blue)), ParagraphPropertySet(left_indent=300, right_indent=300)) ) ss.ParagraphStyles.append( ParagraphStyle( "MeasureField", TextStyle( TextPropertySet( font=ss.Fonts.Arial, size=18, underline=True)), ParagraphPropertySet(left_indent=300, right_indent=300)) ) ss.ParagraphStyles.append( ParagraphStyle( "ITTitle", TextStyle( TextPropertySet( font=ss.Fonts.Arial, size=36, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300)) ) ss.ParagraphStyles.append( ParagraphStyle( "ITSubtitle", TextStyle( TextPropertySet( font=ss.Fonts.Arial, size=32, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300)) ) ss.ParagraphStyles.append( ParagraphStyle( "ITSubSubtitle", TextStyle( TextPropertySet( font=ss.Fonts.Arial, size=28, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300)) ) ss.ParagraphStyles.append( ParagraphStyle( "ITNormalBold", TextStyle( TextPropertySet( font=ss.Fonts.Arial, size=24, bold=True)), ParagraphPropertySet(left_indent=50, right_indent=50)) ) # XXX: This part is removed # self.addActionPlan(document) # XXX: and replaced with this part: t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) intro = createItalianIntro(document, self.context, self.request) toc = createSection(document, self.context, self.request, first_page_number=2) body = Section() heading = t(_("header_oira_report_download", default=u"OiRA Report: \"${title}\"", mapping=dict(title=self.session.title))) toc.append(Paragraph( ss.ParagraphStyles.Heading1, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), heading, )) if self.session.report_comment: # Add comment. #5985 normal_style = document.StyleSheet.ParagraphStyles.Normal toc.append(Paragraph(normal_style, self.session.report_comment)) toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) txt = t(_("toc_header", default=u"Contents")) p.append(character.Text(txt)) toc.append(p) headings = [ t(u"Adempimenti/rischi identificati, valutati e gestiti con misure " "obbligatorie adottate ed eventuali misure di miglioramento"), t(u"Adempimenti/rischi non pertinenti"), ] nodes = [ self.actioned_nodes, self.risk_not_present_nodes, ] for nodes, heading in zip(nodes, headings): if not nodes: continue self.addReportNodes(document, nodes, heading, toc, body) toc.append(Paragraph(LINE)) body.append(Paragraph(LINE)) document.Sections.append(body) # Until here... renderer = Renderer() output = StringIO() renderer.Write(document, output) # Custom filename filename = u"Documento di valutazione dei rischi {}".format( self.session.title) self.request.response.setHeader( "Content-Disposition", "attachment; filename=\"%s.rtf\"" % filename.encode("utf-8")) self.request.response.setHeader("Content-Type", "application/rtf") return output.getvalue()
def render(self): """ Mostly a copy of the render method in OSHAActionPlanReportDownload, but with some changes to handle the special reqs of Italy """ document = report.createDocument(self.session) ss = document.StyleSheet # Define some more custom styles ss.ParagraphStyles.append( ParagraphStyle( "RiskPriority", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=22, italic=True, colour=ss.Colours.Blue)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "MeasureField", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=18, underline=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITTitle", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=36, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITSubtitle", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=32, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITSubSubtitle", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=28, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITNormalBold", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=24, bold=True)), ParagraphPropertySet(left_indent=50, right_indent=50))) # XXX: This part is removed # self.addActionPlan(document) # XXX: and replaced with this part: t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) intro = createItalianIntro(document, self.context, self.request) toc = createSection(document, self.context, self.request, first_page_number=2) body = Section() heading = t( _("header_oira_report_download", default=u"OiRA Report: \"${title}\"", mapping=dict(title=self.session.title))) toc.append( Paragraph( ss.ParagraphStyles.Heading1, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), heading, )) if self.session.report_comment: # Add comment. #5985 normal_style = document.StyleSheet.ParagraphStyles.Normal toc.append(Paragraph(normal_style, self.session.report_comment)) toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) txt = t(_("toc_header", default=u"Contents")) p.append(character.Text(txt)) toc.append(p) headings = [ t(u"Adempimenti/rischi identificati, valutati e gestiti con misure " "obbligatorie adottate ed eventuali misure di miglioramento"), t(u"Adempimenti/rischi non pertinenti"), ] nodes = [ self.actioned_nodes, self.risk_not_present_nodes, ] for nodes, heading in zip(nodes, headings): if not nodes: continue self.addReportNodes(document, nodes, heading, toc, body) toc.append(Paragraph(LINE)) body.append(Paragraph(LINE)) document.Sections.append(body) # Until here... renderer = Renderer() output = StringIO() renderer.Write(document, output) # Custom filename filename = u"Documento di valutazione dei rischi {}".format( self.session.title) self.request.response.setHeader( "Content-Disposition", "attachment; filename=\"%s.rtf\"" % filename.encode("utf-8")) self.request.response.setHeader("Content-Type", "application/rtf") return output.getvalue()
def addIdentificationResults(self, document): survey = self.request.survey section = createIdentificationReportSection(document, self.context, self.request) lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) styles = document.StyleSheet.ParagraphStyles normal_style = document.StyleSheet.ParagraphStyles.Normal header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in self.getNodes(): section.append( Paragraph(header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, node.title))) if node.type != "risk": continue description = legal_reference = None if not getattr(node, 'is_custom_node', None): zope_node = survey.restrictedTraverse( node.zodb_path.split("/"), None) if zope_node is not None: description = getattr(zope_node, "description", None) legal_reference = getattr(zope_node, "legal_reference", None) if description and description.strip(): for el in report.HtmlToRtf(description, normal_style): section.append(el) if legal_reference and legal_reference.strip(): p = Paragraph(styles.Normal, "") section.append(p) section.append( Paragraph( styles.LegalHeading, translate(_('header_legal_references', default=u'Legal and policy references'), target_language=lang), )) p = Paragraph(styles.Normal, "") section.append(p) for el in report.HtmlToRtf(legal_reference, normal_style): section.append(el) tabs = TabPropertySet(section.TwipsToRightMargin(), alignment=TabPropertySet.RIGHT, leader=getattr(TabPropertySet, 'UNDERLINE')) p = Paragraph(styles.Normal, ParagraphPropertySet(tabs=[tabs])) p.append(TAB) section.append(p) if node.comment and node.comment.strip(): section.append(Paragraph(styles.Comment, node.comment))
def addIdentificationResults(self, document): survey = self.request.survey section = createIdentificationReportSection( document, self.context, self.request) lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) styles = document.StyleSheet.ParagraphStyles normal_style = document.StyleSheet.ParagraphStyles.Normal header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in self.getNodes(): section.append( Paragraph( header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, node.title)) ) if node.type != "risk": continue description = legal_reference = None if not getattr(node, 'is_custom_node', None): zope_node = survey.restrictedTraverse( node.zodb_path.split("/"), None) if zope_node is not None: description = getattr(zope_node, "description", None) legal_reference = getattr(zope_node, "legal_reference", None) if description and description.strip(): for el in report.HtmlToRtf(description, normal_style): section.append(el) if legal_reference and legal_reference.strip(): p = Paragraph(styles.Normal, "") section.append(p) section.append( Paragraph( styles.LegalHeading, translate(_( 'header_legal_references', default=u'Legal and policy references'), target_language=lang), ) ) p = Paragraph(styles.Normal, "") section.append(p) for el in report.HtmlToRtf(legal_reference, normal_style): section.append(el) tabs = TabPropertySet( section.TwipsToRightMargin(), alignment=TabPropertySet.RIGHT, leader=getattr(TabPropertySet, 'UNDERLINE') ) p = Paragraph(styles.Normal, ParagraphPropertySet(tabs=[tabs])) p.append(TAB) section.append(p) if node.comment and node.comment.strip(): section.append(Paragraph(styles.Comment, node.comment))
def render(self): """ Mostly a copy of the render method in euphorie.client, but with some changes to also show unanswered risks and non-present risks. #1517 and #1518 """ document = report.createDocument(self.session) ss = document.StyleSheet # Define some more custom styles ss.ParagraphStyles.append( ParagraphStyle( "RiskPriority", TextStyle(TextPropertySet(font=ss.Fonts.Arial, size=22, italic=True, colour=ss.Colours.Blue)), ParagraphPropertySet(left_indent=300, right_indent=300), ) ) ss.ParagraphStyles.append( ParagraphStyle( "MeasureField", TextStyle(TextPropertySet(font=ss.Fonts.Arial, size=18, underline=True)), ParagraphPropertySet(left_indent=300, right_indent=300), ) ) # XXX: This part is removed # self.addActionPlan(document) # XXX: and replaced with this part: t = lambda txt: "".join(["\u%s?" % str(ord(e)) for e in translate(txt, context=self.request)]) toc = createSection(document, self.context, self.request) body = Section() heading = t( _("header_oira_report_download", default=u'OiRA Report: "${title}"', mapping=dict(title=self.session.title)) ) toc.append( Paragraph(ss.ParagraphStyles.Heading1, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), heading) ) if self.session.report_comment: # Add comment. #5985 normal_style = document.StyleSheet.ParagraphStyles.Normal toc.append(Paragraph(normal_style, self.session.report_comment)) toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) txt = t(_("toc_header", default=u"Contents")) p.append(character.Text(txt)) toc.append(p) headings = [ t( _( "header_present_risks", default=u"Risks that have been identified, " u"evaluated and have an Action Plan", ) ), t( _( "header_unevaluated_risks", default=u"Risks that have been identified but " u"do NOT have an Action Plan", ) ), t( _( "header_unanswered_risks", default=u'Hazards/problems that have been "parked"' u"and are still to be dealt with", ) ), t( _( "header_risks_not_present", default=u"Hazards/problems that have been managed " u"or are not present in your organisation", ) ), ] nodes = [self.actioned_nodes, self.unactioned_nodes, self.unanswered_nodes, self.risk_not_present_nodes] for nodes, heading in zip(nodes, headings): if not nodes: continue self.addReportNodes(document, nodes, heading, toc, body) toc.append(Paragraph(LINE)) body.append(Paragraph(LINE)) self.addConsultationBox(body, document) document.Sections.append(body) # Until here... renderer = Renderer() output = StringIO() renderer.Write(document, output) filename = translate( _("filename_report_actionplan", default=u"Action plan ${title}", mapping=dict(title=self.session.title)), context=self.request, ) self.request.response.setHeader( "Content-Disposition", 'attachment; filename="%s.rtf"' % filename.encode("utf-8") ) self.request.response.setHeader("Content-Type", "application/rtf") return output.getvalue()
def render(self): """ Mostly a copy of the render method in euphorie.client, but with some changes to also show unanswered risks and non-present risks. #1517 and #1518 """ document = report.createDocument(self.session) ss = document.StyleSheet # Define some more custom styles ss.ParagraphStyles.append( ParagraphStyle( "RiskPriority", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=22, italic=True, colour=ss.Colours.Blue)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "MeasureField", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=18, underline=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) # XXX: This part is removed # self.addActionPlan(document) # XXX: and replaced with this part: t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) toc = createSection(document, self.context, self.request) body = Section() heading = t( _("header_oira_report_download", default=u"OiRA Report: \"${title}\"", mapping=dict(title=self.session.title))) toc.append( Paragraph( ss.ParagraphStyles.Heading1, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), heading, )) if self.session.report_comment: # Add comment. #5985 normal_style = document.StyleSheet.ParagraphStyles.Normal toc.append(Paragraph(normal_style, self.session.report_comment)) toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) txt = t(_("toc_header", default=u"Contents")) p.append(character.Text(txt)) toc.append(p) headings = [ t( _("header_present_risks", default=u"Risks that have been identified, " u"evaluated and have an Action Plan")), t( _("header_unevaluated_risks", default=u"Risks that have been identified but " u"do NOT have an Action Plan")), t( _("header_unanswered_risks", default=u'Hazards/problems that have been "parked" ' u'and are still to be dealt with')), t( _("header_risks_not_present", default=u"Hazards/problems that have been managed " u"or are not present in your organisation")) ] nodes = [ self.actioned_nodes, self.unactioned_nodes, self.unanswered_nodes, self.risk_not_present_nodes, ] for nodes, heading in zip(nodes, headings): if not nodes: continue self.addReportNodes(document, nodes, heading, toc, body) toc.append(Paragraph(LINE)) body.append(Paragraph(LINE)) self.addConsultationBox(body, document) document.Sections.append(body) # Until here... renderer = Renderer() output = StringIO() renderer.Write(document, output) filename = translate( _("filename_report_actionplan", default=u"Action plan ${title}", mapping=dict(title=self.session.title)), context=self.request, ) self.request.response.setHeader( "Content-Disposition", "attachment; filename=\"%s.rtf\"" % filename.encode("utf-8")) self.request.response.setHeader("Content-Type", "application/rtf") return output.getvalue()
def addMeasure(self, document, heading, section, measure): """ Requirements for how the measure section should be displayed are in #2611 """ t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) ss = document.StyleSheet styles = ss.ParagraphStyles table = Table(9500) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) no_edge = BorderPropertySet(width=0, colour=ss.Colours.White) p = Paragraph(styles.MeasureHeading, ParagraphPropertySet(left_indent=300, right_indent=300), t(_("header_measure_single", default=u"Measure"))) c = Cell(p, FramePropertySet(thin_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) ss = document.StyleSheet styles = document.StyleSheet.ParagraphStyles headings = [ t( _("label_measure_action_plan", default=u"General approach (to " u"eliminate or reduce the risk)")), t( _("label_measure_prevention_plan", default=u"Specific action(s) " u"required to implement this approach")), t( _("label_measure_requirements", default=u"Level of expertise " u"and/or requirements needed")), t( _("label_action_plan_responsible", default=u"Who is " u"responsible?")), t(_("label_action_plan_budget", default=u"Budget")), t(_("label_action_plan_start", default=u"Planning start")), t(_("label_action_plan_end", default=u"Planning end")), ] m = measure values = [ m.action_plan, m.prevention_plan, m.requirements, m.responsible, m.budget and str(m.budget) or '', m.planning_start and formatDate(self.request, m.planning_start) or '', m.planning_end and formatDate(self.request, m.planning_end) or '', ] for heading, value in zip(headings, values): p = Paragraph(styles.MeasureField, heading) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) if headings.index(heading) == len(headings) - 1: frame = FramePropertySet(no_edge, thin_edge, thin_edge, thin_edge) else: frame = FramePropertySet(no_edge, thin_edge, no_edge, thin_edge) p = Paragraph( styles.Normal, ParagraphPropertySet(left_indent=600, right_indent=600), value) c = Cell(p, frame) table.AddRow(c) section.append(table)
def create_workbook(self): """Create an Excel workbook containing the all risks and measures. """ t = lambda txt: translate(txt, context=self.request) book = Workbook() sheet = book.worksheets[0] sheet.title = t(_('report_timeline_title', default=u'Timeline')) sheet.default_column_dimension.auto_size = True for (column, (type, key, title)) in enumerate(self.columns): if key in self.combine_keys: continue cell = sheet.cell(row=0, column=column) cell.value = t(title) cell.style.font.bold = True cell.style.alignment.wrap_text = True letter = get_column_letter(column+1) if title == 'report_timeline_measure': sheet.column_dimensions[letter].width = len(cell.value)+50 else: sheet.column_dimensions[letter].width = len(cell.value)+5 for (row, (module, risk, measure)) in \ enumerate(self.get_measures(), 1): column = 0 if not getattr(risk, 'is_custom_risk', None): zodb_node = self.request.survey.restrictedTraverse( risk.zodb_path.split('/')) else: zodb_node = None for (type, key, title) in self.columns+self.extra_cols: value = None if type == 'measure': value = getattr(measure, key, None) elif type == 'risk': value = getattr(risk, key, None) if key == 'priority': value = self.priority_name(value) elif key == 'title': if zodb_node is None: value = getattr(risk, key, None) elif zodb_node.problem_description and \ zodb_node.problem_description.strip(): value = zodb_node.problem_description elif type == 'module': if key == 'title' and module.depth > 1: titles = [] m = module while m: title = getattr(m, 'title', None) if title: titles.append(m.title) m = m.parent titles.reverse() value = ', '.join(titles) else: if module.zodb_path == 'custom-risks': lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) value = translate(_( 'title_other_risks', default=u'Added risks (by you)'), target_language=lang) else: value = getattr(module, key, None) sheet.cell(row=row, column=column)\ .style.alignment.wrap_text = True # style if key in self.combine_keys and value is not None: # osha wants to combine action_plan (col 3), # prevention_plan and requirements in one cell if not sheet.cell(row=row, column=2).value: sheet.cell(row=row, column=2).value = u'' sheet.cell(row=row, column=2).value += '\r\n'+value continue if value is not None: sheet.cell(row=row, column=column).value = value column += 1 return book