def test_spi_fields_are_serialised(self, data_flow_api_client, ist_adviser): """Test that SPI fields are serialised.""" pm_assigned_by = AdviserFactory() pm_assigned_on = now() investment_project = VerifyWinInvestmentProjectFactory( project_manager=ist_adviser, project_manager_first_assigned_on=pm_assigned_on, project_manager_first_assigned_by=pm_assigned_by, ) spi1 = InvestmentProjectInteractionFactory( investment_project=investment_project, service_id=ServiceConstant. investment_enquiry_requested_more_information.value.id, ) spi2 = InvestmentProjectInteractionFactory( investment_project=investment_project, service_id=ServiceConstant.investment_enquiry_assigned_to_ist_cmc. value.id, ) with freeze_time('2017-01-01'): investment_project.stage_id = InvestmentProjectStageConstant.won.value.id investment_project.save() spi5 = InvestmentProjectInteractionFactory( investment_project=investment_project, service_id=ServiceConstant.investment_ist_aftercare_offered.value. id, ) response = data_flow_api_client.get(self.view_url) assert response.status_code == status.HTTP_200_OK response_results = response.json()['results'] assert response_results == [ { 'enquiry_processed': spi1.created_on.isoformat(), 'enquiry_type': spi1.service.name, 'enquiry_processed_by_id': str(spi1.created_by.id), 'assigned_to_ist': spi2.created_on.isoformat(), 'project_manager_assigned': pm_assigned_on.isoformat(), 'project_manager_assigned_by_id': str(pm_assigned_by.id), 'investment_project_id': str(investment_project.id), 'project_moved_to_won': '2017-01-01T00:00:00+00:00', 'aftercare_offered_on': spi5.created_on.isoformat(), 'propositions': [], }, ]
def test_can_get_spi5_start_and_end(spi_report, ist_adviser): """Tests if we can see spi5 start and end dates.""" investment_project = VerifyWinInvestmentProjectFactory( project_manager=ist_adviser, ) with freeze_time('2017-01-01'): investment_project.stage_id = InvestmentProjectStage.won.value.id investment_project.save() with freeze_time('2017-01-15'): InvestmentProjectInteractionFactory( service_id=Service.investment_ist_aftercare_offered.value.id, investment_project=investment_project, ) rows = list(spi_report.rows()) assert len(rows) == 1 assert rows[0]['Project moved to won'] == '2017-01-01T00:00:00+00:00' assert rows[0]['Aftercare offered on'] == '2017-01-15T00:00:00+00:00'
def test_move_assign_pm_investment_projects_back_to_prospect(self): """ Test moving any existing project that is at the assign pm stage back to a prospect and check an audit entry has been logged. """ assign_pm_project = AssignPMInvestmentProjectFactory() verify_win_project = VerifyWinInvestmentProjectFactory() command = activate_streamlined_investment_flow.Command() command.move_assign_pm_investment_projects_back_to_prospect() assign_pm_project.refresh_from_db() verify_win_project.refresh_from_db() assert str(assign_pm_project.stage.id ) == InvestmentProjectStage.prospect.value.id assert str(verify_win_project.stage.id ) == InvestmentProjectStage.verify_win.value.id assert Version.objects.get_for_object(assign_pm_project).count() == 1 assert Version.objects.get_for_object(verify_win_project).count() == 0
def test_cannot_get_spi5_start_and_end_for_non_new_investor( spi_report, ist_adviser, ): """Tests if we are not going to see spi5 start and end dates if investor is not new.""" investment_project = VerifyWinInvestmentProjectFactory( project_manager=ist_adviser, investor_type_id=InvestorType.existing_investor.value.id, ) with freeze_time('2017-01-01'): investment_project.stage_id = InvestmentProjectStage.won.value.id investment_project.save() with freeze_time('2017-01-15'): InvestmentProjectInteractionFactory( service_id=Service.investment_ist_aftercare_offered.value.id, investment_project=investment_project, ) rows = list(spi_report.rows()) assert len(rows) == 1 assert 'Project moved to won' not in rows[0] assert 'Aftercare offered on' not in rows[0]
def test_investment_project_verify_win_added(api_client): """ Get a list of investment project and test the returned JSON is valid as per: https://www.w3.org/TR/activitystreams-core/ Investment Project with verified win will have fields such as totalInvestment, numberNewJobs and foreignEquityInvestment. """ project = VerifyWinInvestmentProjectFactory() response = hawk.get( api_client, get_url('api-v3:activity-stream:investment-project-added')) assert response.status_code == status.HTTP_200_OK assert response.json() == { '@context': 'https://www.w3.org/ns/activitystreams', 'summary': 'Investment Activities Added', 'type': 'OrderedCollectionPage', 'id': 'http://testserver/v3/activity-stream/investment/project-added', 'partOf': 'http://testserver/v3/activity-stream/investment/project-added', 'previous': None, 'next': None, 'orderedItems': [ { 'id': f'dit:DataHubInvestmentProject:{project.id}:Add', 'type': 'Add', 'published': format_date_or_datetime(project.created_on), 'generator': { 'name': 'dit:dataHub', 'type': 'Application' }, 'actor': { 'id': f'dit:DataHubAdviser:{project.created_by.pk}', 'type': ['Person', 'dit:Adviser'], 'dit:emailAddress': project.created_by.contact_email or project.created_by.email, 'name': project.created_by.name, }, 'object': { 'id': f'dit:DataHubInvestmentProject:{project.id}', 'type': ['dit:InvestmentProject'], 'startTime': format_date_or_datetime(project.created_on), 'name': project.name, 'dit:investmentType': { 'name': project.investment_type.name, }, 'dit:estimatedLandDate': format_date_or_datetime(project.estimated_land_date, ), 'dit:totalInvestment': project.total_investment, 'dit:foreignEquityInvestment': project.foreign_equity_investment, 'dit:numberNewJobs': project.number_new_jobs, 'attributedTo': [ { 'id': f'dit:DataHubCompany:{project.investor_company.pk}', 'dit:dunsNumber': project.investor_company.duns_number, 'dit:companiesHouseNumber': project.investor_company.company_number, 'type': ['Organization', 'dit:Company'], 'name': project.investor_company.name, }, *[{ 'id': f'dit:DataHubContact:{contact.pk}', 'type': ['Person', 'dit:Contact'], 'url': contact.get_absolute_url(), 'dit:emailAddress': contact.email, 'dit:jobTitle': contact.job_title, 'name': contact.name, } for contact in project.client_contacts.order_by('pk') ], ], 'url': project.get_absolute_url(), }, }, ], }
def test_export(self, setup_es, request_sortby, orm_ordering): """Test export of investment project search results.""" url = reverse('api-v3:search:investment_project-export') InvestmentProjectFactory() InvestmentProjectFactory(cdms_project_code='cdms-code') VerifyWinInvestmentProjectFactory() won_project = WonInvestmentProjectFactory() InvestmentProjectTeamMemberFactory.create_batch(3, investment_project=won_project) InvestmentProjectFactory( name='project for subsidiary', investor_company=CompanyFactory( global_headquarters=CompanyFactory( one_list_tier_id=OneListTier.objects.first().id, one_list_account_owner=AdviserFactory(), ), ), ) setup_es.indices.refresh() data = {} if request_sortby: data['sortby'] = request_sortby with freeze_time('2018-01-01 11:12:13'): response = self.api_client.post(url, data=data) assert response.status_code == status.HTTP_200_OK assert parse_header(response.get('Content-Disposition')) == ( 'attachment', {'filename': 'Data Hub - Investment projects - 2018-01-01-11-12-13.csv'}, ) sorted_projects = InvestmentProject.objects.order_by(orm_ordering, 'pk') response_text = response.getvalue().decode('utf-8-sig') reader = DictReader(StringIO(response_text)) assert reader.fieldnames == list(SearchInvestmentExportAPIView.field_titles.values()) expected_row_data = [ { 'Date created': project.created_on, 'Project reference': project.project_code, 'Project name': project.name, 'Investor company': project.investor_company.name, 'Investor company town or city': project.investor_company.address_town, 'Country of origin': get_attr_or_none(project, 'investor_company.address_country.name'), 'Investment type': get_attr_or_none(project, 'investment_type.name'), 'Status': project.get_status_display(), 'Stage': get_attr_or_none(project, 'stage.name'), 'Link': f'{settings.DATAHUB_FRONTEND_URL_PREFIXES["investmentproject"]}' f'/{project.pk}', 'Actual land date': project.actual_land_date, 'Estimated land date': project.estimated_land_date, 'FDI value': get_attr_or_none(project, 'fdi_value.name'), 'Sector': get_attr_or_none(project, 'sector.name'), 'Date of latest interaction': None, 'Project manager': get_attr_or_none(project, 'project_manager.name'), 'Client relationship manager': get_attr_or_none(project, 'client_relationship_manager.name'), 'Global account manager': self._get_global_account_manager_name(project), 'Project assurance adviser': get_attr_or_none(project, 'project_assurance_adviser.name'), 'Other team members': join_attr_values(project.team_members.all(), 'adviser.name'), 'Delivery partners': join_attr_values(project.delivery_partners.all()), 'Possible UK regions': join_attr_values(project.uk_region_locations.all()), 'Actual UK regions': join_attr_values(project.actual_uk_regions.all()), 'Specific investment programme': get_attr_or_none(project, 'specific_programme.name'), 'Referral source activity': get_attr_or_none(project, 'referral_source_activity.name'), 'Referral source activity website': get_attr_or_none(project, 'referral_source_activity_website.name'), 'Total investment': project.total_investment, 'New jobs': project.number_new_jobs, 'Average salary of new jobs': get_attr_or_none(project, 'average_salary.name'), 'Safeguarded jobs': project.number_safeguarded_jobs, 'Level of involvement': get_attr_or_none(project, 'level_of_involvement.name'), 'Likelihood to land': get_attr_or_none(project, 'likelihood_to_land.name'), 'R&D budget': project.r_and_d_budget, 'Associated non-FDI R&D project': project.non_fdi_r_and_d_budget, 'New to world tech': project.new_tech_to_uk, 'FDI type': project.fdi_type, 'Foreign equity investment': project.foreign_equity_investment, 'GVA multiplier': get_attr_or_none(project, 'gva_multiplier.multiplier'), 'GVA': project.gross_value_added, } for project in sorted_projects ] expected_rows = format_csv_data(expected_row_data) # item is an ordered dict so is cast to a dict to make the comparison easier to # interpret in the event of the assert actual_rows == expected_rows failing. actual_rows = [dict(item) for item in reader] # Support for ordering was added to StringAgg in Django 2.2. However, it is not # currently used due to https://code.djangoproject.com/ticket/30315. While that # remains the case, our StringAgg fields are unordered and we use this workaround to # compare them. unordered_fields = ( 'Other team members', 'Delivery partners', 'Possible UK regions', 'Actual UK regions', ) for row in chain(actual_rows, expected_rows): for field in unordered_fields: row[field] = frozenset(row[field].split(', ')) assert actual_rows == expected_rows
def test_write_report(ist_adviser): """Test that SPI report CSV is generated correctly.""" pm_assigned_by = AdviserFactory() pm_assigned_on = now() investment_project = VerifyWinInvestmentProjectFactory( project_manager=ist_adviser, project_manager_first_assigned_on=pm_assigned_on, project_manager_first_assigned_by=pm_assigned_by, ) spi1 = InvestmentProjectInteractionFactory( investment_project=investment_project, service_id=ServiceConstant.investment_enquiry_requested_more_information.value.id, ) spi2 = InvestmentProjectInteractionFactory( investment_project=investment_project, service_id=ServiceConstant.investment_enquiry_assigned_to_ist_cmc.value.id, ) proposition = PropositionFactory( deadline='2017-01-05', status='ongoing', adviser=pm_assigned_by, investment_project=investment_project, created_by=ist_adviser, ) investment_project.stage_id = InvestmentProjectStageConstant.won.value.id investment_project.save() spi5 = InvestmentProjectInteractionFactory( investment_project=investment_project, service_id=ServiceConstant.investment_ist_aftercare_offered.value.id, ) lines = [] file = Mock() file.write = lambda line: lines.append(line.decode('utf8')) write_report(file) headers = ','.join(SPIReport.field_titles.keys()) assert lines[1] == f'{headers}\r\n' row = [ str(investment_project.pk), investment_project.project_code, investment_project.name, investment_project.created_on.isoformat(), spi1.created_on.isoformat(), spi1.service.name, spi1.created_by.name, spi2.created_on.isoformat(), investment_project.project_manager_first_assigned_on.isoformat(), investment_project.project_manager_first_assigned_by.name, investment_project.stage_log.get( stage_id=InvestmentProjectStageConstant.won.value.id, ).created_on.isoformat(), spi5.created_on.isoformat(), f'{proposition.deadline};{proposition.status};;{proposition.adviser.name}', ] expected_line = ','.join(row) assert lines[2] == f'{expected_line}\r\n'