def test_get_measures_order_by_start_date(self): dbsession = Session() session = self._create_session(dbsession) module = session.addChild( model.Module( session=session, zodb_path='1', module_id='1', )) module.addChild( model.Risk(session=session, zodb_path='1/2', risk_id='1', identification='no', action_plans=[ model.ActionPlan(action_plan=u'Plan 2', planning_start=datetime.date( 2011, 12, 15)), model.ActionPlan(action_plan=u'Plan 1', planning_start=datetime.date( 2011, 11, 15)) ])) request = testRequest() request.survey = mock.Mock() request.survey.restrictedTraverse = lambda x: object request.survey.ProfileQuestions = lambda: [] setRequest(request) view = self.ActionPlanTimeline(None, request) view.session = session measures = view.get_measures() self.assertEqual(len(measures), 2) self.assertEqual([row[2].action_plan for row in measures], [u'Plan 1', u'Plan 2'])
def test_get_measures_order_by_priority(self): session = self.createSurveySession() module = model.Module( title=u'Root', module_id='1', zodb_path='1', skip_children=False) session.addChild(module) module.addChild(model.Risk( title=u'Risk 1', risk_id='2', zodb_path='1/2', type='risk', priority=u'low', identification='no', action_plans=[model.ActionPlan( action_plan=u"Do something awesome", planning_start=datetime.date(2013, 3, 4))])) module.addChild(model.Risk( title=u'Risk 2', risk_id='3', zodb_path='1/3', type='risk', priority=u'high', identification='no', action_plans=[model.ActionPlan( action_plan=u"Do something awesome", planning_start=datetime.date(2013, 5, 2))])) module.addChild(model.Risk( title=u'Risk 3', risk_id='4', zodb_path='1/4', type='risk', priority=u'medium', identification='no', action_plans=[model.ActionPlan( action_plan=u"Do something awesome", planning_start=datetime.date(2013, 4, 1))])) view = self.ActionPlanTimeline(None, None) view.session = self.session measures = view.get_measures() self.assertEqual( [risk.priority for (m, risk, measure) in measures], [u'high', u'medium', u'low'])
def test_get_measures_order_by_start_date(self): view = self._get_timeline() session = view.context.session module = session.addChild( model.Module( session=session, zodb_path="1", module_id="1", )) module.addChild( model.Risk( session=session, zodb_path="1/2", risk_id="1", identification="no", action_plans=[ model.ActionPlan(action="Plan 2", planning_start=datetime.date( 2011, 12, 15)), model.ActionPlan(action="Plan 1", planning_start=datetime.date( 2011, 11, 15)), ], )) survey = view.context.aq_parent survey.restrictedTraverse = lambda x: object survey.ProfileQuestions = lambda: [] measures = view.get_measures() self.assertEqual(len(measures), 2) self.assertEqual([row[2].action for row in measures], ["Plan 1", "Plan 2"])
def test_get_measures_with_profile_questions(self): """ Test for #7322 and #8850 """ session = self.createSurveySession() question = model.Module( depth=1, title=u'(Repeatable Module) Do you have multiple shops?', module_id='1', zodb_path='1', skip_children=False, profile_index=-1, ) session.addChild(question) i = 0 for module_title in [ u'(Repeating instance) Somerset West', u'(Repeating instance) Stellenbosch']: answer = model.Module( depth=2, title=module_title, module_id='2', zodb_path='1', skip_children=False, profile_index=i, ) question.addChild(answer) answer.addChild( model.Risk( depth=3, title=u'Hands are washed', risk_id='1', zodb_path='1/2', type='risk', priority=u'low', identification='no', action_plans=[ model.ActionPlan( action_plan=u"Do something awesome", planning_start=datetime.date(2013, 3, 4)) ] ) ) i += 1 view = self.ActionPlanTimeline(None, None) view.session = self.session measures = view.get_measures() self.assertEqual(len(measures), 2) self.assertEqual( measures[0][0].title, u'(Repeating instance) Somerset West', ) self.assertEqual( measures[1][0].title, u'(Repeating instance) Stellenbosch', )
def test_get_measures_filter_on_session(self): view = self._get_timeline() sessions = [ view.context.session, self._create_session(), ] for session in sessions: module = session.addChild( model.Module( session=session, zodb_path="1", module_id="1", )) module.addChild( model.Risk( session=session, zodb_path="1/2", risk_id="1", identification="no", action_plans=[ model.ActionPlan(action="Measure 1 for %s" % session.account.loginname) ], )) survey = view.context.aq_parent survey.restrictedTraverse = lambda x: object survey.ProfileQuestions = lambda: [] measures = view.get_measures() self.assertEqual(len(measures), 1) self.assertEqual(measures[0][2].action, "Measure 1 for [email protected]")
def testInvalidDateDoesNotBreakRendering(self): from euphorie.client import model from euphorie.content.tests.utils import BASIC_SURVEY from z3c.saconfig import Session import datetime # Test for http://code.simplon.biz/tracker/tno-euphorie/ticket/150 self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) survey_url = self.portal.client.nl["ict"][ "software-development"].absolute_url() browser = self.get_browser() browser.open(survey_url) registerUserInClient(browser) # Create a new survey session browser.getControl(name="survey").value = ["ict/software-development"] browser.getForm(action="new-session").submit() browser.getControl(name="form.widgets.title").value = "Sessiøn".encode( "utf-8") # noqa # Start the survey browser.getControl(name="form.button.submit").click() session_url = browser.url.replace("/@@identification", "") # Update the risk risk = Session.query(model.Risk).first() risk.identification = "no" risk.action_plans.append( model.ActionPlan( action_plan="Do something awesome", planning_start=datetime.date(1, 2, 3), )) # Render the report browser.handleErrors = False browser.open("%s/@@report_view" % session_url)
def testInvalidDateDoesNotBreakRendering(self): import datetime from euphorie.content.tests.utils import BASIC_SURVEY from z3c.saconfig import Session from euphorie.client import model # Test for http://code.simplon.biz/tracker/tno-euphorie/ticket/150 self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) browser = Browser() survey_url = self.portal.client.nl["ict"]["software-development"]\ .absolute_url() browser.open(survey_url) registerUserInClient(browser) # Create a new survey session browser.getControl(name="title:utf8:ustring").value = \ u"Sessiøn".encode("utf-8") browser.getControl(name="next").click() # Start the survey browser.getForm().submit() browser.getLink("Start Risk Identification").click() # Update the risk risk = Session.query(model.Risk).first() risk.identification = "no" risk.action_plans.append(model.ActionPlan( action_plan=u"Do something awesome", planning_start=datetime.date(1, 2, 3))) # Render the report browser.handleErrors = False browser.open("http://nohost/plone/client/nl/ict/" "software-development/report/view")
def setUp(self): super(TestCloningViews, self).setUp() self.loginAsPortalOwner() addSurvey(self.portal, BASIC_SURVEY) self.jane = addAccount("*****@*****.**", password="******") self.john = addAccount("*****@*****.**", password="******") group = model.Group(group_id="1") model.Session.add(group) self.jane.group = group self.john.group = group model.Session.flush() survey_session = model.SurveySession( title="Dummy session", created=datetime(2012, 4, 22, 23, 5, 12), modified=datetime(2012, 4, 23, 11, 50, 30), zodb_path="nl/ict/software-development", account=self.jane, group=group, company=model.Company(country="nl", employees="1-9", referer="other"), ) module = survey_session.addChild( model.Module(title="module 1", module_id="1", zodb_path="a")) risk = module.addChild( model.Risk(title="question 1", risk_id="1", zodb_path="a/b")) model.ActionPlan(action_plan="This is the plan", risk=risk) model.Session.add(survey_session)
def test_get_measures_filter_on_session(self): dbsession = Session() sessions = [] for login in ['jane', 'john']: session = self._create_session(dbsession, loginname=login) module = session.addChild( model.Module( session=session, zodb_path='1', module_id='1', )) module.addChild( model.Risk(session=session, zodb_path='1/2', risk_id='1', identification='no', action_plans=[ model.ActionPlan( action_plan=u'Measure 1 for %s' % login) ])) sessions.append(session) request = testRequest() request.survey = mock.Mock() request.survey.restrictedTraverse = lambda x: object request.survey.ProfileQuestions = lambda: [] setRequest(request) view = self.ActionPlanTimeline(None, request) view.session = sessions[0] measures = view.get_measures() self.assertEqual(len(measures), 1) self.assertEqual(measures[0][2].action_plan, 'Measure 1 for jane')
def test_get_measures_with_nested_modules(self): """ """ session = self.createSurveySession() module = model.Module( depth=1, title="Root Module", module_id="1", zodb_path="1", skip_children=False, profile_index=0, ) session.addChild(module) nested_module1 = model.Module( depth=2, title="Nested Module 1", module_id="2", zodb_path="1/1", skip_children=False, profile_index=1, ) module.addChild(nested_module1) nested_module2 = model.Module( depth=3, title="Nested Module 2", module_id="3", zodb_path="1/1/1", skip_children=False, profile_index=2, ) nested_module1.addChild(nested_module2) risk = model.Risk( depth=4, title="Floors are washed", risk_id="1", zodb_path="1/1/1/1", type="risk", priority="low", identification="no", action_plans=[ model.ActionPlan( action_plan="Do something awesome", planning_start=datetime.date(2013, 3, 4), ) ], ) nested_module2.addChild(risk) view = self.ActionPlanTimeline(None, None) view.session = self.session measures = view.get_measures() self.assertEqual(len(measures), 1) self.assertEqual( measures[0][0].title, "Nested Module 2", )
def test_get_measures_with_nested_modules(self): """ """ session = self.createSurveySession() module = model.Module( depth=1, title=u'Root Module', module_id='1', zodb_path='1', skip_children=False, profile_index=0, ) session.addChild(module) nested_module1 = model.Module( depth=2, title=u'Nested Module 1', module_id='2', zodb_path='1/1', skip_children=False, profile_index=1, ) module.addChild(nested_module1) nested_module2 = model.Module( depth=3, title=u'Nested Module 2', module_id='3', zodb_path='1/1/1', skip_children=False, profile_index=2, ) nested_module1.addChild(nested_module2) risk = model.Risk( depth=4, title=u'Floors are washed', risk_id='1', zodb_path='1/1/1/1', type='risk', priority=u'low', identification='no', action_plans=[ model.ActionPlan( action_plan=u"Do something awesome", planning_start=datetime.date(2013, 3, 4)) ] ) nested_module2.addChild(risk) view = self.ActionPlanTimeline(None, None) view.session = self.session measures = view.get_measures() self.assertEqual(len(measures), 1) self.assertEqual( measures[0][0].title, u'Nested Module 2', )
def test_create_workbook_plan_information(self): dbsession = Session() session = self._create_session(dbsession) module = model.Module( zodb_path='1', title=u'Top-level Module title', ) risk = model.Risk(zodb_path='1/2/3', risk_id='1', title=u'Risk title', priority='high', identification='no', path='001002003', comment=u'Risk comment') plan = model.ActionPlan(action_plan=u'Plan 2', planning_start=datetime.date(2011, 12, 15), budget=500) request = testRequest() request.survey = mock.Mock() zodb_node = mock.Mock() zodb_node.problem_description = u'This is wrong.' request.survey.restrictedTraverse.return_value = zodb_node view = self.ActionPlanTimeline(None, request) view.session = session view.get_measures = lambda: [(module, risk, plan)] sheet = view.create_workbook().worksheets[0] # planning start self.assertEqual( sheet.cell('A2').value.date(), datetime.date(2011, 12, 15)) # planning end self.assertEqual(sheet.cell('B2').value, None) # action plan self.assertEqual(sheet.cell('C2').value, u'Plan 2') # prevention plan self.assertEqual(sheet.cell('D2').value, None) # requirements self.assertEqual(sheet.cell('E2').value, None) # responsible self.assertEqual(sheet.cell('F2').value, None) # budget self.assertEqual(sheet.cell('G2').value, 500) # module title self.assertEqual(sheet.cell('H2').value, u'Top-level Module title') # risk number self.assertEqual(sheet.cell('I2').value, u'1.2.3') # risk title self.assertEqual(sheet.cell('J2').value, u'This is wrong.') # risk priority self.assertEqual(sheet.cell('K2').value, u'High') # risk comment self.assertEqual(sheet.cell('L2').value, u'Risk comment')
def test_create_workbook_plan_information(self): view = self._get_timeline() module = model.Module( zodb_path="1", title="Top-level Module title", ) risk = model.Risk( zodb_path="1/2/3", risk_id="1", title="Risk title", priority="high", identification="no", path="001002003", comment="Risk comment", ) plan = model.ActionPlan(action="Plan 2", planning_start=datetime.date(2011, 12, 15), budget=500) survey = view.context.aq_parent zodb_node = mock.Mock() zodb_node.problem_description = "This is wrong." survey.restrictedTraverse.return_value = zodb_node view.get_measures = lambda: [(module, risk, plan)] wb = view.create_workbook() sheet = wb.worksheets[0] # planning start self.assertEqual(sheet["A2"].value, datetime.date(2011, 12, 15)) # planning end self.assertEqual(sheet["B2"].value, None) # action plan self.assertEqual(sheet["C2"].value, "Plan 2") # requirements self.assertEqual(sheet["D2"].value, None) # responsible self.assertEqual(sheet["E2"].value, None) # budget self.assertEqual(sheet["F2"].value, 500) # module title self.assertEqual(sheet["G2"].value, "Top-level Module title") # risk number self.assertEqual(sheet["H2"].value, "1.2.3") # risk title self.assertEqual(sheet["I2"].value, "This is wrong.") # risk priority self.assertEqual(sheet["J2"].value, "High") # risk comment self.assertEqual(sheet["K2"].value, "Risk comment")
def extract_plans_from_request(self): """ Create new ActionPlan objects by parsing the Request. """ new_plans = [] added = 0 updated = 0 existing_plans = {} for plan in self.context.action_plans: existing_plans[str(plan.id)] = plan form = self.request.form form["action_plans"] = [] for i in range(0, len(form['measure'])): measure = dict( [p for p in form['measure'][i].items() if p[1].strip()]) form['action_plans'].append(measure) if len(measure): budget = measure.get("budget") budget = budget and budget.split(',')[0].split('.')[0] if measure.get('id', '-1') in existing_plans: plan = existing_plans[measure.get('id')] if (measure.get("action_plan") != plan.action_plan or measure.get("prevention_plan") != plan.prevention_plan or measure.get("requirements") != plan.requirements or measure.get("responsible") != plan.responsible or (plan.budget and (budget != str(plan.budget)) or plan.budget is None and budget) or ((plan.planning_start and measure.get('planning_start') != plan.planning_start.strftime('%Y-%m-%d')) or (plan.planning_start is None and measure.get('planning_start'))) or ((plan.planning_end and measure.get('planning_end') != plan.planning_end.strftime('%Y-%m-%d')) or (plan.planning_end is None and measure.get('planning_end')))): updated += 1 del existing_plans[measure.get('id')] else: added += 1 new_plans.append( model.ActionPlan( action_plan=measure.get("action_plan"), prevention_plan=measure.get("prevention_plan"), requirements=measure.get("requirements"), responsible=measure.get("responsible"), budget=budget, planning_start=measure.get('planning_start'), planning_end=measure.get('planning_end'))) removed = len(existing_plans) if added == 0 and updated == 0 and removed == 0: IStatusMessage(self.request).add( _(u"No changes were made to measures in your action plan."), type='info') if added == 1: IStatusMessage(self.request).add(_( u"message_measure_saved", default=u"A measure has been added to your action plan."), type='success') elif added == 2: IStatusMessage(self.request).add(_( u"message_measures_saved_2", default= u"${no_of_measures} measures have been added to your action plan.", mapping={'no_of_measures': str(added)}), type='success') elif added in (3, 4): IStatusMessage(self.request).add(_( u"message_measures_saved_3_4", default= u"${no_of_measures} measures have been added to your action plan.", mapping={'no_of_measures': str(added)}), type='success') elif added > 4: IStatusMessage(self.request).add(_( u"message_measures_saved", default= u"${no_of_measures} measures have been added to your action plan.", mapping={'no_of_measures': str(added)}), type='success') if updated == 1: IStatusMessage(self.request).add(_( u"message_measure_updated", default=u"A measure has been updated in your action plan."), type='success') elif updated == 2: IStatusMessage(self.request).add(_( u"message_measures_updated_2", default= u"${no_of_measures} measures have been updated in your action plan.", mapping={'no_of_measures': str(updated)}), type='success') elif updated in (3, 4): IStatusMessage(self.request).add(_( u"message_measures_updated_3_4", default= u"${no_of_measures} measures have been updated in your action plan.", mapping={'no_of_measures': str(updated)}), type='success') elif updated > 4: IStatusMessage(self.request).add(_( u"message_measures_updated", default= u"${no_of_measures} measures have been updated in your action plan.", mapping={'no_of_measures': str(updated)}), type='success') if removed == 1: IStatusMessage(self.request).add(_( u"message_measure_removed", default=u"A measure has been removed from your action plan."), type='success') elif removed == 2: IStatusMessage(self.request).add(_( u"message_measures_removed_3", default= u"${no_of_measures} measures have been removed from your action plan.", mapping={'no_of_measures': str(removed)}), type='success') elif removed in (3, 4): IStatusMessage(self.request).add(_( u"message_measures_removed_3_4", default= u"${no_of_measures} measures have been removed from your action plan.", mapping={'no_of_measures': str(removed)}), type='success') elif removed > 4: IStatusMessage(self.request).add(_( u"message_measures_removed", default= u"${no_of_measures} measures have been removed from your action plan.", mapping={'no_of_measures': str(removed)}), type='success') return new_plans
def update(self): if redirectOnSurveyUpdate(self.request): return context = aq_inner(self.context) appconfig = getUtility(IAppConfig) settings = appconfig.get('euphorie') self.use_existing_measures = settings.get('use_existing_measures', False) self.next_is_report = False # already compute "next" here, so that we can know in the template # if the next step might be the report phase, in which case we # need to switch off the sidebar next = FindNextQuestion(context, filter=self.question_filter) if next is None: # We ran out of questions, proceed to the report url = "%s/report" % self.request.survey.absolute_url() self.next_is_report = True else: url = QuestionURL(self.request.survey, next, phase="actionplan") if self.request.environ["REQUEST_METHOD"] == "POST": reply = self.request.form session = Session() context.comment = reply.get("comment") context.priority = reply.get("priority") new_plans = self.extract_plans_from_request() for plan in context.action_plans: session.delete(plan) context.action_plans.extend(new_plans) SessionManager.session.touch() if reply["next"] == "previous": next = FindPreviousQuestion(context, filter=self.question_filter) if next is None: # We ran out of questions, step back to intro page url = "%s/evaluation" % self.request.survey.absolute_url() else: url = QuestionURL(self.request.survey, next, phase="actionplan") return self.request.response.redirect(url) else: self.data = context if len(context.action_plans) == 0: self.data.empty_action_plan = [model.ActionPlan()] self.title = context.parent.title self.tree = getTreeData(self.request, context, filter=self.question_filter, phase="actionplan") if self.context.is_custom_risk: self.risk = self.context self.description_intro = u"" self.risk.description = u"" number_images = 0 else: self.risk = self.request.survey.restrictedTraverse( context.zodb_path.split("/")) number_images = getattr(self.risk, 'image', None) and 1 or 0 if number_images: for i in range(2, 5): number_images += getattr(self.risk, 'image{0}'.format(i), None) and 1 or 0 ploneview = getMultiAdapter((self.context, self.request), name="plone") stripped_description = StripMarkup(self.risk.description) if len(stripped_description) > self.DESCRIPTION_CROP_LENGTH: self.description_intro = ploneview.cropText( stripped_description, self.DESCRIPTION_CROP_LENGTH) else: self.description_intro = "" self.solutions = [ solution for solution in self.risk.values() if ISolution.providedBy(solution) ] self.number_images = number_images self.has_images = number_images > 0 self.image_class = IMAGE_CLASS[number_images] self.risk_number = self.context.number lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) self.delete_confirmation = translate(_( u"Are you sure you want to delete this measure? This action can " u"not be reverted."), target_language=lang) self.override_confirmation = translate(_( u"The current text in the fields 'Action plan', 'Prevention plan' and " u"'Requirements' of this measure will be overwritten. This action cannot be " u"reverted. Are you sure you want to continue?"), target_language=lang) self.message_date_before = translate(_( u"error_validation_before_end_date", default=u"This date must be on or before the end date."), target_language=lang) self.message_date_after = translate(_( u"error_validation_after_start_date", default=u"This date must be on or after the start date."), target_language=lang) self.message_positive_number = translate(_( u"error_validation_positive_whole_number", default=u"This value must be a positive whole number."), target_language=lang) super(ActionPlanView, self).update()
def test_get_measures_with_profile_questions_and_submodules(self): """ """ session = self.createSurveySession() question = model.Module( depth=1, title="(Repeatable Module) Do you have multiple shops?", module_id="1", zodb_path="1", skip_children=False, profile_index=-1, ) session.addChild(question) i = 0 for module_title in [ "(Repeating instance) Somerset West", "(Repeating instance) Stellenbosch", ]: location_path = "%s/%d" % (question.zodb_path, i) location = model.Module( depth=3, title=module_title, module_id="2", zodb_path=location_path, skip_children=False, profile_index=i, ) question.addChild(location) submodule_path = "%s/1" % location_path submodule = model.Module( depth=2, title="Nested Module 1", module_id="2", zodb_path="%s/1" % location_path, skip_children=False, profile_index=1, ) location.addChild(submodule) submodule.addChild( model.Risk( depth=4, title="Hands are washed", risk_id="1", zodb_path="%s/%d" % (submodule_path, i), type="risk", priority="low", identification="no", action_plans=[ model.ActionPlan( action_plan="Do something awesome", planning_start=datetime.date(2013, 3, 4), ) ], ) ) i += 1 view = self.ActionPlanTimeline(None, None) view.session = self.session measures = view.get_measures() self.assertEqual(len(measures), 2) self.assertEqual( measures[0][0].title, "Nested Module 1", ) self.assertEqual( measures[1][0].title, "Nested Module 1", )
def migrate_actgion_plans(context): # Work in chunks of 25 max_tools = 25 site = api.portal.get() client = getattr(site, "client") today = date.today() request = context.REQUEST.clone() alsoProvides(request, IClientSkinLayer) # path = "eu/maritime-transport/maritime-transport-1" tool_paths = Session.query(model.SurveySession.zodb_path).distinct() # .filter(model.SurveySession.zodb_path==path).distinct() tool_count = 0 skip_count = 0 for result in tool_paths: tool_path = str(result[0]) try: tool = client.restrictedTraverse(tool_path) except KeyError: log.warning("No tool in client found for {}".format(tool_path)) continue country = tool_path.split("/")[0] sessions = ( Session.query(model.SurveySession).filter( and_( model.Account.id == model.SurveySession.account_id, model.Account.account_type != "guest", model.SurveySession.zodb_path == tool_path, model.SurveySession.migrated == None, # noqa: E711 )).order_by(model.SurveySession.zodb_path)) if not sessions.count(): skip_count += 1 if skip_count % 5 == 0: log.info("Skipped the first %d, already handled" % skip_count) continue log.info("\n\nHandle tool {}".format(tool_path)) risks_by_path = {} solutions_by_path = {} measures_by_path = {} for session in sessions: log.info("Session {}".format(session.id)) risks = (Session.query(model.Risk).filter( model.Risk.session_id == session.id).order_by(model.Risk.path)) for risk in risks: risk_path = str(risk.zodb_path) is_custom = "custom" in risk_path if is_custom: zodb_risk = None elif risk_path not in risks_by_path: try: zodb_risk = tool.restrictedTraverse(risk_path) except Exception: log.warning("Risk {} not found in tool {}".format( risk_path, tool_path)) continue else: if not IRisk.providedBy(zodb_risk): zodb_risk = None solutions_by_path[risk_path] = [] measures_by_path[risk_path] = [] else: solutions = zodb_risk._solutions solutions_by_path[risk_path] = solutions measures_by_path[ risk_path] = get_pre_defined_measures( solutions, country) risks_by_path[risk_path] = zodb_risk else: zodb_risk = risks_by_path[risk_path] # convert ActionPlan items that are clearly based on solutions # to "standard" type if not is_custom: for ap in risk.custom_measures: for solution in solutions_by_path[risk_path]: if solution.action_plan == (ap.action_plan or "").strip(): if (getattr(solution, "prevention_plan", "") or "").strip() == ( ap.prevention_plan or "") and (getattr( solution, "requirements", "") or "").strip() == ( ap.requirements or ""): ap.plan_type = "measure_standard" ap.solution_id = solution.id # Convert the measures-in-place to their respective ActionPlan items try: saved_existing_measures = (risk.existing_measures and loads(risk.existing_measures) or []) except ValueError: saved_existing_measures = [] # Backwards compat. We used to save dicts before we # switched to list of tuples. if isinstance(saved_existing_measures, dict): saved_existing_measures = [ (k, v) for (k, v) in saved_existing_measures.items() ] new_action_plans = [] already_converted_measure_ids = [ x.solution_id for x in risk.in_place_standard_measures ] already_converted_custom_texts = [ x.action for x in risk.in_place_custom_measures ] if saved_existing_measures: custom = [] while saved_existing_measures: text, active = saved_existing_measures.pop() if not active: continue if not is_custom and text in measures_by_path[ risk_path]: solution_id = measures_by_path[risk_path][text] if solution_id not in already_converted_measure_ids: new_action_plans.append( model.ActionPlan( action=text, plan_type="in_place_standard", solution_id=solution_id, )) else: if text not in already_converted_custom_texts: custom.append(text) for text in custom: new_action_plans.append( model.ActionPlan(action=text, plan_type="in_place_custom")) if new_action_plans: risk.action_plans.extend(new_action_plans) session.migrated = today tool_count += 1 if max_tools > 0 and tool_count >= max_tools: log.info("Broke off after %d tools" % tool_count) return
def test_get_measures_order_by_priority(self): session = self.createSurveySession() module = model.Module( title="Root", module_id="1", zodb_path="1", skip_children=False ) session.addChild(module) module.addChild( model.Risk( title="Risk 1", risk_id="2", zodb_path="1/2", type="risk", priority="low", identification="no", action_plans=[ model.ActionPlan( action_plan="Do something awesome", planning_start=datetime.date(2013, 3, 4), ) ], ) ) module.addChild( model.Risk( title="Risk 2", risk_id="3", zodb_path="1/3", type="risk", priority="high", identification="no", action_plans=[ model.ActionPlan( action_plan="Do something awesome", planning_start=datetime.date(2013, 5, 2), ) ], ) ) module.addChild( model.Risk( title="Risk 3", risk_id="4", zodb_path="1/4", type="risk", priority="medium", identification="no", action_plans=[ model.ActionPlan( action_plan="Do something awesome", planning_start=datetime.date(2013, 4, 1), ) ], ) ) view = self.ActionPlanTimeline(None, None) view.session = self.session measures = view.get_measures() self.assertEqual( [risk.priority for (m, risk, measure) in measures], ["high", "medium", "low"], )