def add_measures(self, skip_planned_measures, skip_existing_measures, node, doc): if (self.use_existing_measures and self.tool_type in self.tti.types_existing_measures and not skip_existing_measures): if self.italy_special: skip_planned_measures = True for (idx, action_plan) in enumerate(node.in_place_standard_measures + node.in_place_custom_measures): heading = (self.t( _( "label_existing_measure", default="Measure already implemented", )) + " " + str(idx + 1)) self.add_measure(doc, heading, action_plan, implemented=True) if not skip_planned_measures: action_plans = node.standard_measures + node.custom_measures for (idx, measure) in enumerate(action_plans): if not measure.action: continue if len(action_plans) == 1: heading = self.t( _("header_measure_single", default="Measure")) else: heading = self.t( _( "header_measure", default="Measure ${index}", mapping={"index": idx + 1}, )) self.add_measure(doc, heading, measure)
class PreferencesSchema(model.Schema): first_name = schema.TextLine(title=_("label_first_name", default="First name"), required=False) last_name = schema.TextLine(title=_("label_last_name", default="Last name"), required=False)
def handleSave(self, action): flash = IStatusMessage(self.request).addStatusMessage (data, errors) = self.extractData() if errors: for error in errors: flash(error.message, "notice") return user = get_current_account() if not data["new_password"]: flash(_("There were no changes to be saved."), "notice") return login_view = api.content.get_view( name="login", context=self.context, request=self.request, ) error = login_view.check_password_policy(data["new_password"]) if error: raise WidgetActionExecutionError("new_password", Invalid(error)) if not user.verify_password(data["old_password"]): raise WidgetActionExecutionError("old_password", Invalid(_("Invalid password"))) user.password = data["new_password"] flash(_("Your password was successfully changed."), "success")
def handlePreview(self, action): self.publish() IStatusMessage(self.request).add( _( "no_translate_link_preview_success", default= ('${text_message_preview_success}: <a href="${url}">${url}</a>.' ), mapping={ "url": self.preview_url(), "text_message_preview_success": _( "message_preview_success", default= ("Succesfully created a preview for the OiRA Tool. It can " "be accessed at"), ), }, ), type="success", ) state = getMultiAdapter((aq_inner(self.context), self.request), name="plone_context_state") self.request.response.redirect(state.view_url())
def menu_contents(self): return [ { "class_outer": "menu-item-preferences", "class_inner": "icon-cog", "url": f"{self.webhelpers.country_url}/preferences", "label": _("title_preferences", default="Preferences"), }, { "class_outer": "menu-item-change-password", "class_inner": "icon-key", "url": f"{self.webhelpers.country_url}/account-settings", "label": _("title_change_password", default="Change password"), }, { "class_outer": "menu-item-change-email-address", "class_inner": "icon-mail", "url": f"{self.webhelpers.country_url}/new-email", "label": _("Change email address"), }, { "class_outer": "menu-item-delete-account", "class_inner": "icon-cancel-circle", "url": f"{self.webhelpers.country_url}/account-delete", "label": _("Delete account"), }, { "class_outer": "menu-item-logout", "class_inner": "icon-exit", "url": f"{self.webhelpers.country_url}/logout", "label": _("navigation_logout", default="Logout"), }, ]
class EmailChangeSchema(model.Schema): loginname = RFC822MailAddress(title=_("Email address/account name"), required=True) directives.widget("loginname", type="email") password = schema.Password(title=_("Your password for confirmation"), required=True) directives.widget(password="******")
def __call__(self): self.allow_guest_accounts = api.portal.get_registry_record( "euphorie.allow_guest_accounts", default=False) context = aq_inner(self.context) webhelpers = api.content.get_view(name="webhelpers", context=self.context, request=self.request) came_from = webhelpers.get_came_from(default=context.absolute_url()) self.register_url = "%s/@@login?%s#registration" % ( context.absolute_url(), urlencode({"came_from": came_from}), ) setLanguage(self.request, self.context) if self.request.environ["REQUEST_METHOD"] == "POST": if not self.allow_guest_accounts: flash = IStatusMessage(self.request).addStatusMessage flash( _("Starting a test session is not available in this OiRA " "application."), "error", ) self.request.response.redirect(came_from) else: form = self.request.form if form["action"] == "new": account = self.createGuestAccount() self.login(account, False) self._NewSurvey(form, account) self._updateSurveys() return self.index()
def set_session_title_row(self, data): request = self.request survey = self.context.aq_parent # Remove existing paragraphs for paragraph in self.template.paragraphs: delete_paragraph(paragraph) header = self.template.sections[0].header header_table = header.tables[0] header_table.cell(0, 0).paragraphs[0].text = data["title"] header_table.cell(0, 1).paragraphs[0].text = formatDate( request, date.today()) footer_txt = self.t( _( "report_identification_revision", default="This document was based on the OiRA Tool '${title}' " "of revision date ${date}.", mapping={ "title": survey.published[1], "date": formatDate(request, survey.published[2]), }, )) footer = self.template.sections[0].footer paragraph = footer.tables[0].cell(0, 0).paragraphs[0] paragraph.style = "Footer" paragraph.text = footer_txt
def set_session_title_row(self, data): request = self.request doc = self.template # Remove existing paragraphs for paragraph in doc.paragraphs: delete_paragraph(paragraph) header = doc.sections[0].header h_table = header.tables[0] h_table.cell(0, 0).paragraphs[0].text = data["heading"] h_table.cell(0, 1).paragraphs[0].text = u"Datum download: {}".format( formatDate(request, date.today())) # doc.paragraphs[0].text = data['heading'] survey = aq_parent(self.context) footer_txt = self.t( _( "report_survey_revision", default=u"This document was based on the OiRA Tool '${title}' " u"of revision date ${date}.", mapping={ "title": survey.published[1], "date": formatDate(request, survey.published[2]), }, )) footer = doc.sections[0].footer f_table = footer.tables[0] paragraph = f_table.cell(0, 0).paragraphs[0] paragraph.style = "Footer" paragraph.text = footer_txt
def set_cell_risk(self, cell, risk): """Take the risk and add the appropriate text: title, descripton, comment, measures in place """ paragraph = cell.paragraphs[0] paragraph.style = "Risk Bold List" paragraph.text = risk["title"] if self.show_priority: priority = risk.get("priority", "high") if priority: if priority == "low": level = _("risk_priority_low", default="low") elif priority == "medium": level = _("risk_priority_medium", default="medium") elif priority == "high": level = _("risk_priority_high", default="high") paragraph = cell.add_paragraph( "{}: {}".format( api.portal.translate( _("report_timeline_priority", default="Priority")), api.portal.translate(level), ), style="Measure Indent", ) paragraph.runs[0].italic = True if risk["comment"] and risk["comment"].strip(): HtmlToWord(risk["comment"], cell, style="Risk Normal") if self.show_risk_descriptions: HtmlToWord(risk["description"], cell) if risk["measures"]: if self.show_risk_descriptions: cell.add_paragraph() if self.use_measures_subheading: cell.add_paragraph( api.portal.translate( _( "report_measures_in_place", default="Measures already in place:", )), style="Risk Italics", ) for measure in risk["measures"]: HtmlToWord(_simple_breaks(measure), cell, style="Risk Italics List") paragraph = cell.add_paragraph(style="Risk Normal")
def set_cell_actions(self, cell, risk): """Take the risk and add the appropriate text: planned measures """ paragraph = cell.paragraphs[0] for idx, action in enumerate(risk["actions"]): if idx != 0: paragraph = cell.add_paragraph() paragraph.style = "Measure List" paragraph.text = _simple_breaks(action["text"]) if action.get("requirements", None): paragraph = cell.add_paragraph(style="Measure Indent") run = paragraph.add_run() run.text = api.portal.translate( _("report_competences", default="Required expertise:")) run.underline = True run = paragraph.add_run() run.text = " " run = paragraph.add_run() run.text = (_simple_breaks(action["requirements"]), ) if action.get("responsible", None): paragraph = cell.add_paragraph( api.portal.translate( _( "report_responsible", default="Responsible: ${responsible_name}", mapping={ "responsible_name": action["responsible"] }, )), style="Measure Indent", ) paragraph.runs[0].italic = True if action.get("planning_end", None): paragraph = cell.add_paragraph( api.portal.translate( _( "report_end_date", default="To be done by: ${date}", mapping={"date": action["planning_end"]}, )), style="Measure Indent", ) paragraph.runs[0].italic = True
class AccountSettings(AutoExtensibleForm, form.Form): """View name: @@account-settings""" template = ViewPageTemplateFile("templates/account-settings.pt") schema = PasswordChangeSchema ignoreContext = True label = _("title_change_password", default="Change password") def updateWidgets(self): super(AccountSettings, self).updateWidgets() self.widgets["old_password"].addClass("password") self.widgets["new_password"].addClass("password") @button.buttonAndHandler(_("Save changes"), name="save") def handleSave(self, action): flash = IStatusMessage(self.request).addStatusMessage (data, errors) = self.extractData() if errors: for error in errors: flash(error.message, "notice") return user = get_current_account() if not data["new_password"]: flash(_("There were no changes to be saved."), "notice") return login_view = api.content.get_view( name="login", context=self.context, request=self.request, ) error = login_view.check_password_policy(data["new_password"]) if error: raise WidgetActionExecutionError("new_password", Invalid(error)) if not user.verify_password(data["old_password"]): raise WidgetActionExecutionError("old_password", Invalid(_("Invalid password"))) user.password = data["new_password"] flash(_("Your password was successfully changed."), "success") @button.buttonAndHandler(_("button_cancel", default="Cancel"), name="cancel") def handleCancel(self, action): self.request.response.redirect(self.request.client.absolute_url())
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)
def check_password_policy(self, password): if not self.is_valid_password(password): return _( "error_password_policy_violation", default= ("The password needs to be at least 12 characters long and " "needs to contain at least one lower case letter, one upper " "case letter and one digit."), )
def session_title_lookup(self): lookup = { 0: { 0: { "fname": "title", "title": _("label_title", default="Title") } } } return lookup
def handleSave(self, action): flash = IStatusMessage(self.request).addStatusMessage (data, errors) = self.extractData() if errors: return url = self.context.absolute_url() user = get_current_account() if not user.verify_password(data["password"]): raise WidgetActionExecutionError("password", Invalid(_("Invalid password"))) settings_url = "%s/account-settings" % url if not data["loginname"] or data["loginname"].strip( ) == user.loginname: self.request.response.redirect(settings_url) flash(_("There were no changes to be saved."), "notice") return login = data["loginname"].strip().lower() existing = Session.query(Account.id).filter(Account.loginname == login) if existing.count(): raise WidgetActionExecutionError( "loginname", Invalid(_("This email address is not available."))) self.initiateRequest(user, login) flash( _( "email_change_pending", default=( "Please confirm your new email address by clicking on " "the link in the email that will be sent in a few " 'minutes to "${email}". Please note that the new ' "email address is also your new login name."), mapping={"email": data["loginname"]}, ), "warning", ) self.request.response.redirect("%s/" % url)
def __call__(self): url = "%s/" % aq_inner(self.context).absolute_url() flash = IStatusMessage(self.request).addStatusMessage key = self.request.get("key") if key is None: flash(_("This request could not be processed."), "warning") self.request.response.redirect(url) return request = Session.query(AccountChangeRequest).get(key) if request is None: flash(_("This request could not be processed."), "warning") self.request.response.redirect(url) return request.account.loginname = request.value alsoProvides(self.request, IDisableCSRFProtection) Session.delete(request) flash(_("Your email address has been updated."), "success") self.request.response.redirect(url)
def set_consultation_box(self): doc = self.template doc.add_paragraph() doc.add_paragraph() table = doc.add_table(rows=4, cols=1) color = "000000" row = table.rows[0] cell = row.cells[0] self.set_row_borders(row, settings=ALL_BORDERS, color=color) paragraph = cell.paragraphs[0] paragraph.style = "Heading 3" paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER paragraph.text = self.t( _("header_oira_report_consultation", default="Consultation of workers")) paragraph = cell.add_paragraph() paragraph.text = self.t( _( "paragraph_oira_consultation_of_workers", default="The undersigned hereby declare that the workers " "have been consulted on the content of this " "document.", )) paragraph = cell.add_paragraph() employer = self.t( _("oira_consultation_employer", default="On behalf of the employer:")) workers = self.t( _("oira_consultation_workers", default="On behalf of the workers:")) paragraph.text = "{0}\t\t\t{1}".format(employer, workers) cell.add_paragraph() cell.add_paragraph() paragraph = cell.add_paragraph() paragraph.text = self.t(_("oira_survey_date", default="Date:")) cell.add_paragraph() cell.add_paragraph()
def session_title_lookup(self): lookup = { 0: { 0: { "fname": "title", "title": _("label_title", default="Title") }, 2: { "title": _( "label_report_staff", default="Staff who participated in the risk assessment", ) }, 4: { "fname": "today", "title": _("label_report_date", default="Date of editing"), }, } } return lookup
def set_session_title_row(self, data): """This fills the workspace activity run with some text""" request = self.request self.template.paragraphs[self.paragraphs_offset].text = data["heading"] txt = self.t(_("toc_header", default="Contents")) par_contents = self.template.paragraphs[self.paragraphs_offset + 1] par_contents.text = txt par_toc = self.template.paragraphs[self.paragraphs_offset + 2] for nodes, heading in zip(data["nodes"], data["section_headings"]): if not nodes: continue par_toc.insert_paragraph_before(heading, style="TOC Heading 1") if data.get("comment"): par_toc.insert_paragraph_before("") par_toc.insert_paragraph_before(data["comment"]) survey = self.context.aq_parent header = self.template.sections[self.sections_offset].header header_table = header.tables[0] header_table.cell(0, 0).paragraphs[0].text = data["title"] header_table.cell(0, 1).paragraphs[0].text = formatDate( request, date.today()) footer_txt = self.t( _( "report_survey_revision", default="This document was based on the OiRA Tool '${title}' " "of revision date ${date}.", mapping={ "title": survey.published[1], "date": formatDate(request, survey.published[2]), }, )) footer = self.template.sections[self.sections_offset].footer paragraph = footer.tables[0].cell(0, 0).paragraphs[0] paragraph.style = "Footer" paragraph.text = footer_txt
class PasswordChangeSchema(model.Schema): old_password = schema.Password(title=_("label_old_password", default="Current Password"), required=True) directives.widget( old_password="******") new_password = schema.Password( title=_("label_new_password", default="Desired password")) directives.widget( new_password="******") new_password_confirmation = schema.Password( title=_("label_new_password_confirmation", default="Again password")) directives.widget(new_password_confirmation= "z3c.form.browser.password.PasswordFieldWidget") @invariant def validate_same_value(data): if data.new_password != data.new_password_confirmation: raise Invalid( _("Password doesn't compare with confirmation value"))
def handleDelete(self, action): (data, errors) = self.extractData() if errors: return user = get_current_account() if not user.verify_password(data["password"]): raise WidgetActionExecutionError("password", Invalid(_("Invalid password"))) Session.delete(user) self.logout() self.request.response.redirect(self.request.client.absolute_url())
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 DeleteAccount(AutoExtensibleForm, form.Form): """ "View name: @@account-delete""" template = ViewPageTemplateFile("templates/account-delete.pt") schema = AccountDeleteSchema ignoreContext = True label = _("title_account_delete", default="Delete account") def updateWidgets(self): super(DeleteAccount, self).updateWidgets() self.widgets["password"].addClass("password") def logout(self): pas = getToolByName(self.context, "acl_users") pas.resetCredentials(self.request, self.request.response) @button.buttonAndHandler(_("Delete account"), name="delete") def handleDelete(self, action): (data, errors) = self.extractData() if errors: return user = get_current_account() if not user.verify_password(data["password"]): raise WidgetActionExecutionError("password", Invalid(_("Invalid password"))) Session.delete(user) self.logout() self.request.response.redirect(self.request.client.absolute_url()) @button.buttonAndHandler(_("button_cancel", default="Cancel"), name="cancel") def handleCancel(self, action): self.request.response.redirect(self.request.client.absolute_url())
def EnableCustomRisks(survey): """In order to allow the user to add custom risks, we create a new special module (marked with ICustomRisksModule) in which they may be created. """ if not api.portal.get_registry_record("euphorie.allow_user_defined_risks"): return 0 if "custom-risks" in survey.keys(): # We don't want to create the custom risks module twice. return 0 args = dict( container=survey, type="euphorie.module", id="custom-risks", title=_("label_custom_risks", default="Custom risks"), safe_id=False, description=_( "description_other_risks", default="In case you have identified " "risks not included in the tool, you are able to add them now:", ), optional=True, question=_( "question_other_risks", default="<p><strong>Important:" "</strong> In order to avoid duplicating risks, we strongly " "recommend you to go first through all the previous modules, if " "you have not done it yet.</p><p>If you don't need to add risks, " "please continue.</p>", ), ) try: module = api.content.create(**args) except api.exc.InvalidParameterError: args["id"] = "custom-risks-" + str(random.randint(0, 99999999)) module = api.content.create(**args) alsoProvides(module, ICustomRisksModule) return args["id"]
class Preferences(AutoExtensibleForm, form.Form): template = ViewPageTemplateFile("templates/preferences.pt") schema = PreferencesSchema def getContent(self): user = get_current_account() directlyProvides(user, PreferencesSchema) return user @button.buttonAndHandler(_("Save"), name="save") def handleSave(self, action): flash = IStatusMessage(self.request).addStatusMessage (data, errors) = self.extractData() if errors: for error in errors: flash(error.message, "notice") return user = get_current_account() user.first_name = data["first_name"] user.last_name = data["last_name"]
def update_custom_risks_module_texts(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(): is_new = EnableCustomRisks(survey) count += 1 custom = getattr(survey, "custom-risks", None) if custom: custom.question = _( "question_other_risks", default= ("<p><strong>Important:</strong> In " "order to avoid duplicating risks, " "we strongly recommend you " "to go first through all the previous modules, " "if you have not done it yet.</p>" "<p>If you don't need to add risks, " "please continue.</p>"), ) if is_new: survey.published = ( survey.id, survey.title, datetime.datetime.now(), )
def add_measure(self, doc, heading, measure, implemented=False): doc.add_paragraph(heading, style="Measure Heading") headings = [ self.t( _( "label_measure_action_plan", default="General approach (to " "eliminate or reduce the risk)", )) ] if not implemented: headings = headings + [ self.t( _( "label_measure_requirements", default="Level of expertise and/or requirements needed", )), self.t( _("label_action_plan_responsible", default="Who is responsible?")), self.t(_("label_action_plan_budget", default="Budget")), self.t(_("label_action_plan_start", default="Planning start")), self.t(_("label_action_plan_end", default="Planning end")), ] m = measure values = [_simple_breaks(m.action or "")] if not implemented: values = values + [ _simple_breaks(m.requirements or ""), 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): doc.add_paragraph(heading, style="MeasureField") doc = HtmlToWord(value, doc, style="MeasureText")
def set_session_title_row(self, data): """This fills the workspace activity run with some text""" request = self.request doc = self.template header = doc.sections[0].header h_table = header.tables[0] h_table.cell(0, 0).paragraphs[0].text = data["heading"] h_table.cell(0, 1).paragraphs[0].text = u"Datum download: {}".format( formatDate(request, date.today())) doc.paragraphs[0].text = data["heading"] heading1 = self.t( _("plan_report_intro_header", default=u"Introduction")) intro = self.t( _( "plan_report_intro_1", default=u"By filling in the list of questions, you have " u"completed a risk assessment. This assessment is used to " u"draw up an action plan. The progress of this action " u"plan must be discussed annually and a small report must " u"be written on the progress. Certain subjects might have " u"been completed and perhaps new subjects need to be " u"added.", )) doc.add_paragraph(heading1, style="Heading 1") doc.add_paragraph(intro) survey = aq_parent(self.context) footer_txt = self.t( _( "report_survey_revision", default=u"This document was based on the OiRA Tool '${title}' " u"of revision date ${date}.", mapping={ "title": survey.published[1], "date": formatDate(request, survey.published[2]), }, )) footer = doc.sections[0].footer f_table = footer.tables[0] paragraph = f_table.cell(0, 0).paragraphs[0] # Example code for inserting image (into a newly created table) # width = header_table.cell(0, 0).width + header_table.cell(0, 1).width # table = footer.add_table(rows=1, cols=2, width=width) # wh = self.context.restrictedTraverse('webhelpers') # image = wh.get_sector_logo # img = image.data._blob.open() # from docx.shared import Cm # paragraph = table.cell(0, 1).paragraphs[0] # paragraph.add_run().add_picture(img, width=Cm(1)) # paragraph = table.cell(0, 0).paragraphs[0] paragraph.style = "Footer" paragraph.text = footer_txt doc.add_page_break() doc.add_paragraph( self.t(_("plan_report_company_header", default=u"Company details")), style="Heading 1", ) missing = self.t(_("missing_data", default=u"Not provided")) company = self.session.dutch_company table = doc.add_table(rows=1, cols=2) total_width = table.columns[0].width + table.columns[1].width table.columns[0].width = int(total_width * 0.20) table.columns[1].width = int(total_width * 0.80) field = DutchCompanySchema["title"] row_cells = table.rows[0].cells row_cells[0].text = str(field.title) row_cells[ 1].text = company.title if company and company.title else missing row_cells = table.add_row().cells address = (formatAddress( company.address_visit_address, company.address_visit_postal, company.address_visit_city, ) if company else None) row_cells[0].text = "Bezoekadres bedrijf" row_cells[1].text = address if address else missing row_cells = table.add_row().cells address = (formatAddress( company.address_postal_address, company.address_postal_postal, company.address_postal_city, ) if company else None) row_cells[0].text = "Postadres bedrijf" row_cells[1].text = address if address else missing for key in [ "email", "phone", "activity", "submitter_name", "submitter_function", "department", "location", ]: field = DutchCompanySchema[key] value = getattr(company, key, None) row_cells = table.add_row().cells row_cells[0].text = str(field.title) row_cells[1].text = value if value else missing formatDecimal = request.locale.numbers.getFormatter("decimal").format field = DutchCompanySchema["absentee_percentage"] row_cells = table.add_row().cells row_cells[0].text = str(field.title) row_cells[1].text = (u"%s %%" % formatDecimal(company.absentee_percentage) if company and company.absentee_percentage else missing) for key in ["accidents", "incapacitated_workers"]: field = DutchCompanySchema[key] value = getattr(company, key, None) row_cells = table.add_row().cells row_cells[0].text = str(field.title) row_cells[1].text = "%d" % value if value else missing field = DutchCompanySchema["submit_date"] row_cells = table.add_row().cells row_cells[0].text = str(field.title) row_cells[1].text = (formatDate(request, company.submit_date) if company and company.submit_date else missing) field = DutchCompanySchema["employees"] row_cells = table.add_row().cells row_cells[0].text = str(field.title) row_cells[1].text = (field.vocabulary.getTerm(company.employees).title if company and company.employees else missing) field = DutchCompanySchema["arbo_expert"] row_cells = table.add_row().cells row_cells[0].text = str(field.title) row_cells[1].text = (company.arbo_expert if company and company.arbo_expert else missing) doc.add_page_break()
def title_custom_risks(self): return translate( _("label_custom_risks", default="Custom risks"), target_language=self.lang, )
def add_report_section(self, nodes, heading, **extra): doc = self.template doc.add_paragraph(heading, style="Heading 1") survey = self.context.aq_parent 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) number = node.number if "custom-risks" in node.zodb_path: num_elems = number.split(".") number = ".".join(["Ω"] + num_elems[1:]) doc.add_paragraph("%s %s" % (number, title), style="Heading %d" % (node.depth + 1)) if node.type != "risk": continue if extra.get("show_risk_state", False): msg = "" if node.identification == "no": msg = _("risk_present", default="Risk is present.") elif (node.postponed or not node.identification ) and not node.risk_type == "top5": msg = _( "risk_unanswered", default="This risk still needs to be inventorised.", ) if node.risk_type == "top5": if node.postponed or not node.identification: msg = _( "top5_risk_not_present", default="This risk is not present in your " "organisation, but since the sector organisation " "considers this one of the priority risks it must " "be included in this report.", ) elif node.identification == "yes": # we need this distinction for Dutch RIE msg = _( "top5_risk_not_present_answer_yes", default="This risk is not present in your " "organisation, but since the sector organisation " "considers this one of the priority risks it must " "be included in this report.", ) if msg: doc.add_paragraph(self.t(msg), style="RiskPriority") if (node.priority and extra.get("show_priority", True) and not self.italy_special): if node.priority == "low": level = _("risk_priority_low", default="low") elif node.priority == "medium": level = _("risk_priority_medium", default="medium") elif node.priority == "high": level = _("risk_priority_high", default="high") msg = _( "risk_priority", default="This is a ${priority_value} priority risk.", mapping={"priority_value": level}, ) doc.add_paragraph(self.t(msg), style="RiskPriority") print_description = True # In the report for Italy, don't print the description if self.italy_special: print_description = False if not getattr(node, "identification", None) == "no": if not extra.get("always_print_description", None) is True: print_description = False if print_description: if zodb_node is None: if "custom-risks" in node.zodb_path: description = (getattr(node, "custom_description", node.title) or node.title) else: description = node.title else: description = zodb_node.description doc = HtmlToWord(_sanitize_html(description or ""), doc) if node.comment and node.comment.strip(): msg = translate(_("heading_comments", default="Comments"), target_language=self.lang) doc.add_paragraph(msg, style="Measure Heading") doc = HtmlToWord(_sanitize_html(node.comment or ""), doc) if not extra.get("skip_legal_references", True): legal_reference = getattr(zodb_node, "legal_reference", None) if legal_reference and legal_reference.strip(): doc.add_paragraph() legal_heading = translate( _( "header_legal_references", default="Legal and policy references", ), target_language=self.lang, ) doc.add_paragraph(legal_heading, style="Legal Heading") doc = HtmlToWord(_sanitize_html(legal_reference), doc) if not extra.get("use_solutions", False): skip_planned_measures = extra.get("skip_planned_measures", False) skip_existing_measures = extra.get("skip_existing_measures", False) self.add_measures(skip_planned_measures, skip_existing_measures, node, doc) elif zodb_node is not None: self.add_solutions(zodb_node, doc)