Beispiel #1
0
    def test_set_team_country_on_create(self):
        """
        Tests that when creating a new OrderAssignee, the `team` and `country`
        properties get populated automatically.
        """
        # adviser belonging to a team with a country
        team = TeamFactory(country_id=constants.Country.france.value.id)
        adviser = AdviserFactory(dit_team=team)
        assignee = OrderAssigneeFactory(adviser=adviser)

        assert assignee.team == team
        assert str(assignee.country_id) == constants.Country.france.value.id

        # adviser belonging to a team without country
        team = TeamFactory(country=None)
        adviser = AdviserFactory(dit_team=team)
        assignee = OrderAssigneeFactory(adviser=adviser)

        assert assignee.team == team
        assert not assignee.country

        # adviser not belonging to any team
        adviser = AdviserFactory(dit_team=None)
        assignee = OrderAssigneeFactory(adviser=adviser)

        assert not assignee.team
        assert not assignee.country
Beispiel #2
0
    def test_if_assigning_project_manager_second_time_doesnt_update_related_columns(self):
        """
        Test that the assignment of project manager for the second time, doesn't update who and
        when made an assignment.
        """
        investment_project = InvestmentProjectFactory(
            project_manager=AdviserFactory(),
            project_manager_first_assigned_on=datetime(2010, 1, 2, 0, 0, tzinfo=utc),
            project_manager_first_assigned_by=AdviserFactory(),
        )
        url = reverse('admin:investment_investmentproject_change', args=(investment_project.pk,))

        data = {}

        # populate data with required field values
        admin_form = InvestmentProjectAdmin(InvestmentProject, site).get_form(mock.Mock())
        for field_name, field in admin_form.base_fields.items():
            if field.required:
                field_value = getattr(investment_project, field_name)
                data[field_name] = field.prepare_value(field_value)

        project_manager = AdviserFactory()
        data['project_manager'] = project_manager.pk

        response = self.client.post(url, data, follow=True)

        assert response.status_code == status.HTTP_200_OK

        investment_project.refresh_from_db()
        assert investment_project.project_manager == project_manager
        assert investment_project.project_manager_first_assigned_on != now()
        assert investment_project.project_manager_first_assigned_by != self.user
    def test_team_member_list_update_add_only(self):
        """Tests updating adding team members when none previously existed."""
        project = InvestmentProjectFactory()

        new_team_member_data = [
            {
                'investment_project': project,
                'adviser': AdviserFactory(),
                'role': 'new role',
            },
            {
                'investment_project': project,
                'adviser': AdviserFactory(),
                'role': 'new team member',
            },
        ]

        child_serializer = IProjectTeamMemberSerializer()
        serializer = IProjectTeamMemberListSerializer(child=child_serializer)

        updated_team_members = serializer.update([], new_team_member_data)

        assert updated_team_members[0].adviser == new_team_member_data[0][
            'adviser']
        assert updated_team_members[0].role == new_team_member_data[0]['role']
        assert updated_team_members[1].adviser == new_team_member_data[1][
            'adviser']
        assert updated_team_members[1].role == new_team_member_data[1]['role']
        assert project.team_members.count() == 2
Beispiel #4
0
    def test_adviser_notified(self):
        """
        Test that calling `adviser_added` sends an email notifying the adviser that
        they have been added to the order.
        """
        order = OrderFactory()
        adviser = AdviserFactory()
        creator = AdviserFactory()

        notify.client.reset_mock()

        notify.adviser_added(
            order=order,
            adviser=adviser,
            by=creator,
            creation_date=dateutil_parse('2017-05-18'),
        )

        assert notify.client.send_email_notification.called
        call_args = notify.client.send_email_notification.call_args_list[0][1]
        assert call_args['email_address'] == adviser.contact_email
        assert call_args[
            'template_id'] == Template.you_have_been_added_for_adviser.value

        assert call_args['personalisation']['recipient name'] == adviser.name
        assert call_args['personalisation']['creator'] == creator.name
        assert call_args['personalisation']['creation date'] == '18/05/2017'
Beispiel #5
0
def test_adviser_report_generation():
    """Test the generation of the report."""
    disabled_team = TeamFactory(
        disabled_on=datetime(1980, 1, 1, tzinfo=timezone.utc),
    )
    advisers = [
        AdviserFactory(date_joined=datetime(1980, 1, 1, tzinfo=timezone.utc)),
        AdviserFactory(date_joined=datetime(1990, 1, 1, tzinfo=timezone.utc), dit_team=None),
        AdviserFactory(
            date_joined=datetime(2000, 1, 1, tzinfo=timezone.utc),
            dit_team=disabled_team,
        ),
    ]

    report = AllAdvisersReport()
    assert list(report.rows()) == [{
        'id': adviser.pk,
        'email': adviser.email,
        'name': adviser.name,
        'contact_email': adviser.contact_email,
        'is_active': adviser.is_active,
        'dit_team__name': adviser.dit_team.name if adviser.dit_team else None,
        'is_team_active': adviser.dit_team.disabled_on is None if adviser.dit_team else None,
        'dit_team__role__name': adviser.dit_team.role.name if adviser.dit_team else None,
    } for adviser in advisers]
    def test_falls_back_to_email_field(self, api_request_factory,
                                       requests_mock):
        """
        Test that advisers are looked up using the email field when a match using
        sso_email_user_id is not found, and the adviser's sso_email_user_id is updated.
        """
        adviser = AdviserFactory(email='*****@*****.**',
                                 sso_email_user_id=None)

        requests_mock.post(
            STAFF_SSO_INTROSPECT_URL,
            json=_make_introspection_data(username='******'),
        )

        request = api_request_factory.get('/test-path',
                                          HTTP_AUTHORIZATION='Bearer token')
        response = view(request)

        assert request.user == adviser
        assert response.status_code == status.HTTP_200_OK
        assert response.data == {'content': 'introspection-test-view'}

        # Check that the sso_email_user_id was set on the user
        adviser.refresh_from_db()
        assert adviser.sso_email_user_id == '*****@*****.**'
def test_simulate(s3_stubber):
    """Test that the command only simulates the actions if --simulate is passed in."""
    advisers = [
        AdviserFactory(telephone_number='000000000'),
        AdviserFactory(telephone_number='111111111'),
    ]

    bucket = 'test_bucket'
    object_key = 'test_key'
    csv_content = f"""id,telephone_number
{advisers[0].id},+441234567890
{advisers[1].id},+440987654321
"""
    s3_stubber.add_response(
        'get_object',
        {
            'Body': BytesIO(bytes(csv_content, encoding='utf-8')),
        },
        expected_params={
            'Bucket': bucket,
            'Key': object_key,
        },
    )

    call_command('update_adviser_telephone_number',
                 bucket,
                 object_key,
                 simulate=True)

    for adviser in advisers:
        adviser.refresh_from_db()

    assert advisers[0].telephone_number == '000000000'
    assert advisers[1].telephone_number == '111111111'
def test_audit_log(s3_stubber):
    """Test that the audit log is being created."""
    adviser = AdviserFactory()

    bucket = 'test_bucket'
    object_key = 'test_key'
    csv_content = f"""id,telephone_number
{adviser.id},111222333
"""
    s3_stubber.add_response(
        'get_object',
        {
            'Body': BytesIO(bytes(csv_content, encoding='utf-8')),
        },
        expected_params={
            'Bucket': bucket,
            'Key': object_key,
        },
    )

    call_command('update_adviser_telephone_number', bucket, object_key)

    adviser.refresh_from_db()

    assert adviser.telephone_number == '111222333'

    versions = Version.objects.get_for_object(adviser)
    assert len(versions) == 1
    assert versions[0].revision.get_comment() == 'Telephone number migration.'
Beispiel #9
0
def project_with_max_gross_value_added():
    """Test fixture returns an investment project with the max gross value."""
    gva_multiplier = GVAMultiplierFactory(
        multiplier=Decimal('9.999999'),
        financial_year=1980,
    )

    with mock.patch(
        'datahub.investment.project.gva_utils.GrossValueAddedCalculator._get_gva_multiplier',
    ) as mock_get_multiplier:
        mock_get_multiplier.return_value = gva_multiplier
        project = InvestmentProjectFactory(
            investment_type_id=constants.InvestmentType.fdi.value.id,
            name='won project',
            description='investmentproject3',
            estimated_land_date=datetime.date(2027, 9, 13),
            actual_land_date=datetime.date(2022, 11, 13),
            investor_company=CompanyFactory(
                address_country_id=constants.Country.united_kingdom.value.id,
            ),
            project_manager=AdviserFactory(),
            project_assurance_adviser=AdviserFactory(),
            fdi_value_id=constants.FDIValue.higher.value.id,
            status=InvestmentProject.STATUSES.won,
            uk_region_locations=[
                constants.UKRegion.north_west.value.id,
            ],
            level_of_involvement_id=Involvement.hq_only.value.id,
            likelihood_to_land_id=None,
            foreign_equity_investment=9999999999999999999,
        )
    return project
Beispiel #10
0
    def test_merge_when_both_companies_are_on_pipeline_for_same_adviser(
        self,
        source_status,
        target_status,
    ):
        """
        Test that both source and target company are on pipeline for the same adviser
        and same status. And the merge is successful.
        """
        adviser = AdviserFactory()
        source_company = CompanyFactory()
        target_company = CompanyFactory()

        PipelineItemFactory(
            adviser=adviser,
            company=source_company,
            status=source_status,
        )
        PipelineItemFactory(
            adviser=adviser,
            company=target_company,
            status=target_status,
        )

        user = AdviserFactory()
        merge_companies(source_company, target_company, user)

        assert not PipelineItem.objects.filter(
            adviser=adviser,
            company=source_company,
        ).exists()
        assert PipelineItem.objects.filter(
            adviser=adviser,
            company=target_company,
        ).exists()
def test_get_email_domain(email, domain, db):
    """
    Test that the `Adviser.get_email_domain` method
    returns the domain for the given adviser's email.
    """
    adviser = AdviserFactory(email=email, contact_email=email)
    assert adviser.get_email_domain() == domain
Beispiel #12
0
    def test_non_restricted_user_can_see_all_projects(self, setup_es, permissions):
        """Test that normal users can see all projects."""
        team = TeamFactory()
        team_others = TeamFactory()
        adviser_1 = AdviserFactory(dit_team_id=team.id)
        adviser_2 = AdviserFactory(dit_team_id=team_others.id)

        request_user = create_test_user(
            permission_codenames=permissions,
            dit_team=team,
        )
        api_client = self.create_api_client(user=request_user)

        iproject_1 = InvestmentProjectFactory()
        iproject_2 = InvestmentProjectFactory()

        InvestmentProjectTeamMemberFactory(adviser=adviser_1, investment_project=iproject_1)
        InvestmentProjectTeamMemberFactory(adviser=adviser_2, investment_project=iproject_2)

        setup_es.indices.refresh()

        url = reverse('api-v3:search:investment_project')
        response = api_client.post(url, {})

        assert response.status_code == status.HTTP_200_OK
        response_data = response.json()
        assert response_data['count'] == 2
        assert {str(iproject_1.pk), str(iproject_2.pk)} == {
            result['id'] for result in response_data['results']
        }
Beispiel #13
0
    def test_change(self, refund_factory):
        """Test changing a refund record, its status cannot change at this point."""
        refund = refund_factory()
        order = OrderPaidFactory()

        now_datetime = now()
        now_date_str = now_datetime.date().isoformat()
        now_time_str = now_datetime.time().isoformat()

        url = reverse('admin:omis_payment_refund_change', args=(refund.id, ))
        data = {
            'order': order.pk,
            'status': refund.status,
            'requested_on_0': now_date_str,
            'requested_on_1': now_time_str,
            'requested_by': AdviserFactory().pk,
            'requested_amount': order.total_cost,
            'refund_reason': 'lorem ipsum refund reason',
            'level1_approved_on_0': now_date_str,
            'level1_approved_on_1': now_time_str,
            'level1_approved_by': AdviserFactory().pk,
            'level1_approval_notes': 'lorem ipsum level 1',
            'level2_approved_on_0': now_date_str,
            'level2_approved_on_1': now_time_str,
            'level2_approved_by': AdviserFactory().pk,
            'level2_approval_notes': 'lorem ipsum level 2',
            'method': PaymentMethod.BACS,
            'net_amount': order.total_cost - 1,
            'vat_amount': 1,
            'additional_reference': 'additional reference',
            'rejection_reason': 'lorem ipsum rejection reason',
        }
        response = self.client.post(url, data, follow=True)

        assert response.status_code == status.HTTP_200_OK
        refund.refresh_from_db()

        assert refund.order.pk == data['order']
        assert refund.status == data['status']
        assert refund.requested_on == now_datetime
        assert refund.requested_by.pk == data['requested_by']
        assert refund.requested_amount == data['requested_amount']
        assert refund.refund_reason == data['refund_reason']
        assert refund.level1_approved_on == now_datetime
        assert refund.level1_approved_by.pk == data['level1_approved_by']
        assert refund.level1_approval_notes == data['level1_approval_notes']
        assert refund.level2_approved_on == now_datetime
        assert refund.level2_approved_by.pk == data['level2_approved_by']
        assert refund.level2_approval_notes == data['level2_approval_notes']
        assert refund.method == data['method']
        assert refund.net_amount == data['net_amount']
        assert refund.vat_amount == data['vat_amount']
        assert refund.additional_reference == data['additional_reference']
        assert refund.rejection_reason == data['rejection_reason']

        assert refund.total_amount == order.total_cost
        assert refund.created_by != self.user
        assert refund.modified_by == self.user
        assert not refund.payment
    def test_cannot_change_adviser_after_creation(self):
        """After creating an OrderAssignee, the related adviser cannot be changed."""
        adviser = AdviserFactory()
        assignee = OrderAssigneeFactory(adviser=adviser)

        with pytest.raises(ValueError):
            assignee.adviser = AdviserFactory()
            assignee.save()
Beispiel #15
0
    def test_error_returned_if_duplicate_participating_advisers_specified(self):
        """
        Test that an error is returned if an adviser is specified as a DIT participant
        multiple times.
        """
        contact = ContactFactory()
        communication_channel = random_obj_for_model(CommunicationChannel)
        dit_adviser = AdviserFactory()

        url = reverse('api-v3:interaction:collection')
        request_data = {
            'kind': Interaction.Kind.INTERACTION,
            'communication_channel': communication_channel.pk,
            'subject': 'whatever',
            'date': date.today().isoformat(),
            'dit_participants': [
                {
                    'adviser': {
                        'id': dit_adviser.pk,
                    },
                },
                {
                    'adviser': {
                        'id': AdviserFactory().pk,
                    },
                },
                {
                    'adviser': {
                        'id': dit_adviser.pk,
                    },
                },
            ],
            'company': {
                'id': contact.company.pk,
            },
            'contacts': [{
                'id': contact.pk,
            }],
            'service': {
                'id': random_service().pk,
            },
            'was_policy_feedback_provided': False,
        }

        api_client = self.create_api_client()
        response = api_client.post(url, request_data)
        assert response.status_code == status.HTTP_400_BAD_REQUEST

        # An error should be returned for each duplicated item in the dit_participants list in
        # the request
        assert response.json() == {
            'dit_participants': [
                {'adviser': ['You cannot add the same adviser more than once.']},
                {},
                {'adviser': ['You cannot add the same adviser more than once.']},
            ],
        }
Beispiel #16
0
def setup_data(setup_es, project_with_max_gross_value_added):
    """Sets up data for the tests."""
    investment_projects = [
        InvestmentProjectFactory(
            investment_type_id=constants.InvestmentType.fdi.value.id,
            name='abc defg',
            description='investmentproject1',
            estimated_land_date=datetime.date(2011, 6, 13),
            actual_land_date=datetime.date(2010, 8, 13),
            investor_company=CompanyFactory(
                address_country_id=constants.Country.united_states.value.id,
            ),
            status=InvestmentProject.STATUSES.ongoing,
            uk_region_locations=[
                constants.UKRegion.east_midlands.value.id,
                constants.UKRegion.isle_of_man.value.id,
            ],
            level_of_involvement_id=Involvement.hq_and_post_only.value.id,
            likelihood_to_land_id=LikelihoodToLand.high.value.id,
            foreign_equity_investment=100000,
        ),
        InvestmentProjectFactory(
            investment_type_id=constants.InvestmentType.fdi.value.id,
            name='delayed project',
            description='investmentproject2',
            estimated_land_date=datetime.date(2057, 6, 13),
            actual_land_date=datetime.date(2047, 8, 13),
            country_investment_originates_from_id=constants.Country.ireland.value.id,
            investor_company=CompanyFactory(
                address_country_id=constants.Country.japan.value.id,
            ),
            project_manager=AdviserFactory(),
            project_assurance_adviser=AdviserFactory(),
            fdi_value_id=constants.FDIValue.higher.value.id,
            status=InvestmentProject.STATUSES.delayed,
            uk_region_locations=[
                constants.UKRegion.north_west.value.id,
            ],
            level_of_involvement_id=Involvement.no_involvement.value.id,
            likelihood_to_land_id=LikelihoodToLand.medium.value.id,
        ),
        project_with_max_gross_value_added,
        InvestmentProjectFactory(
            name='new project',
            description='investmentproject4',
            country_investment_originates_from_id=constants.Country.canada.value.id,
            estimated_land_date=None,
            level_of_involvement_id=None,
            likelihood_to_land_id=LikelihoodToLand.low.value.id,
        ),
    ]
    setup_es.indices.refresh()

    yield investment_projects
Beispiel #17
0
def setup_data(setup_es):
    """Sets up data for the tests."""
    with freeze_time('2017-01-01 13:00:00'):
        company = CompanyFactory(name='Mercury trading', alias='Uranus supplies')
        contact = ContactFactory(company=company, first_name='John', last_name='Doe')
        order = OrderFactory(
            reference='abcd',
            primary_market_id=constants.Country.japan.value.id,
            uk_region_id=constants.UKRegion.channel_islands.value.id,
            assignees=[],
            status=OrderStatus.draft,
            company=company,
            contact=contact,
            discount_value=0,
            delivery_date=dateutil_parse('2018-01-01').date(),
            vat_verified=False,
        )
        OrderSubscriberFactory(
            order=order,
            adviser=AdviserFactory(dit_team_id=constants.Team.healthcare_uk.value.id),
        )
        OrderAssigneeFactory(
            order=order,
            adviser=AdviserFactory(dit_team_id=constants.Team.tees_valley_lep.value.id),
            estimated_time=60,
        )

    with freeze_time('2017-02-01 13:00:00'):
        company = CompanyFactory(name='Venus Ltd', alias='Earth outsourcing')
        contact = ContactFactory(company=company, first_name='Jenny', last_name='Cakeman')
        order = OrderWithAcceptedQuoteFactory(
            reference='efgh',
            primary_market_id=constants.Country.france.value.id,
            uk_region_id=constants.UKRegion.east_midlands.value.id,
            assignees=[],
            status=OrderStatus.quote_awaiting_acceptance,
            company=company,
            contact=contact,
            discount_value=0,
            delivery_date=dateutil_parse('2018-02-01').date(),
            vat_verified=False,
        )
        OrderSubscriberFactory(
            order=order,
            adviser=AdviserFactory(dit_team_id=constants.Team.td_events_healthcare.value.id),
        )
        OrderAssigneeFactory(
            order=order,
            adviser=AdviserFactory(dit_team_id=constants.Team.food_from_britain.value.id),
            estimated_time=120,
        )

        setup_es.indices.refresh()
Beispiel #18
0
def setup_data(setup_es):
    """Sets up data for the tests."""
    investment_projects = [
        InvestmentProjectFactory(
            name='abc defg',
            description='investmentproject1',
            estimated_land_date=datetime.date(2011, 6, 13),
            actual_land_date=datetime.date(2010, 8, 13),
            investor_company=CompanyFactory(
                registered_address_country_id=constants.Country.united_states.value.id,
            ),
            status=InvestmentProject.STATUSES.ongoing,
            uk_region_locations=[
                constants.UKRegion.east_midlands.value.id,
                constants.UKRegion.isle_of_man.value.id,
            ],
        ),
        InvestmentProjectFactory(
            name='delayed project',
            description='investmentproject2',
            estimated_land_date=datetime.date(2057, 6, 13),
            actual_land_date=datetime.date(2047, 8, 13),
            investor_company=CompanyFactory(
                registered_address_country_id=constants.Country.japan.value.id,
            ),
            project_manager=AdviserFactory(),
            project_assurance_adviser=AdviserFactory(),
            fdi_value_id=constants.FDIValue.higher.value.id,
            status=InvestmentProject.STATUSES.delayed,
            uk_region_locations=[
                constants.UKRegion.north_west.value.id,
            ],
        ),
        InvestmentProjectFactory(
            name='won project',
            description='investmentproject3',
            estimated_land_date=datetime.date(2027, 9, 13),
            actual_land_date=datetime.date(2022, 11, 13),
            investor_company=CompanyFactory(
                registered_address_country_id=constants.Country.united_kingdom.value.id,
            ),
            project_manager=AdviserFactory(),
            project_assurance_adviser=AdviserFactory(),
            fdi_value_id=constants.FDIValue.higher.value.id,
            status=InvestmentProject.STATUSES.won,
            uk_region_locations=[
                constants.UKRegion.north_west.value.id,
            ],
        ),
    ]
    setup_es.indices.refresh()

    yield investment_projects
def test_assigning_non_ist_project_manager_doesnt_end_spi2(spi_report):
    """Test that non IST project manager wont end SPI 2."""
    investment_project = InvestmentProjectFactory()
    investment_project.project_manager = AdviserFactory()
    investment_project.project_manager_first_assigned_on = now()
    investment_project.project_manager_first_assigned_by = AdviserFactory()
    investment_project.save()

    rows = list(spi_report.rows())

    assert len(rows) == 1
    assert 'Project manager assigned' not in rows[0]
    assert 'Project manager assigned by' not in rows[0]
Beispiel #20
0
def calendar_data_fixture():
    """
    Create advisers, contacts and companies so that our email samples can be
    attributed to some DB entities.
    """
    advisers = [
        ('*****@*****.**', 'Adviser', '1'),
        ('*****@*****.**', 'Adviser', '2'),
    ]
    AdviserFactory.create_batch(
        len(advisers),
        email=factory.Iterator(advisers, getter=lambda a: a[0]),
        first_name=factory.Iterator(advisers, getter=lambda a: a[1]),
        last_name=factory.Iterator(advisers, getter=lambda a: a[2]),
        contact_email=factory.SelfAttribute('email'),
    )
    AdviserFactory(
        email='*****@*****.**',
        first_name='Adviser',
        last_name='3',
        contact_email='*****@*****.**',
    )
    company_1 = CompanyFactory(name='Company 1')
    company_2 = CompanyFactory(name='Company 2')
    contacts = [
        ('Bill Adama', company_1),
        ('Saul Tigh', company_1),
        ('Laura Roslin', company_2),
        ('Sharon Valerii', company_1),
        ('Sharon Valerii', company_2),
    ]
    for name, company in contacts:
        first_name, last_name = name.split(' ')
        email_prefix = name.lower().replace(' ', '.')
        email = f'{email_prefix}@example.net'
        ContactFactory(
            first_name=first_name,
            last_name=last_name,
            email=email,
            company=company,
        )
    # Ensure that our contact who appears on multiple companies
    # with a single email address has more interactions for the
    # contact attributed to 'Company 1'
    contact_with_interactions = Contact.objects.get(
        email='*****@*****.**',
        company=company_1,
    )
    CompanyInteractionFactory(contacts=[contact_with_interactions],
                              company=company_1)
    yield
Beispiel #21
0
def test_is_user_feature_flag(code, user, is_active, lookup, expected):
    """Tests if is_user_feature_flag returns correct state of feature flag."""
    if code != '':
        flag = UserFeatureFlagFactory(code=code, is_active=is_active)

    if user == 'flagged_user':
        advisor = AdviserFactory()
        advisor.features.set([flag])

    if user == 'unflagged_user':
        advisor = AdviserFactory()

    result = is_user_feature_flag_active(lookup, advisor)
    assert result is expected
Beispiel #22
0
def test_company_subsidiaries_auto_update_to_opensearch(
        opensearch_with_signals):
    """Tests if company subsidiaries get updated in OpenSearch."""
    account_owner = AdviserFactory()
    global_headquarters = CompanyFactory(one_list_account_owner=account_owner)
    subsidiaries = CompanyFactory.create_batch(
        2, global_headquarters=global_headquarters)
    opensearch_with_signals.indices.refresh()

    subsidiary_ids = [subsidiary.id for subsidiary in subsidiaries]

    result = get_documents_by_ids(
        opensearch_with_signals,
        CompanySearchApp,
        subsidiary_ids,
    )

    expected_results = {(str(subsidiary_id), str(account_owner.id))
                        for subsidiary_id in subsidiary_ids}
    search_results = {
        (doc['_id'],
         doc['_source']['one_list_group_global_account_manager']['id'])
        for doc in result['docs']
    }

    assert len(result['docs']) == 2
    assert search_results == expected_results

    new_account_owner = AdviserFactory()
    global_headquarters.one_list_account_owner = new_account_owner
    global_headquarters.save()

    opensearch_with_signals.indices.refresh()

    new_result = get_documents_by_ids(
        opensearch_with_signals,
        CompanySearchApp,
        subsidiary_ids,
    )

    new_expected_results = {(str(subsidiary_id), str(new_account_owner.id))
                            for subsidiary_id in subsidiary_ids}
    new_search_results = {
        (doc['_id'],
         doc['_source']['one_list_group_global_account_manager']['id'])
        for doc in new_result['docs']
    }

    assert len(new_result['docs']) == 2
    assert new_search_results == new_expected_results
def test_one_list_report_generation():
    """Test the generation of the One List."""
    companies = CompanyFactory.create_batch(
        2,
        headquarter_type_id=constants.HeadquarterType.ghq.value.id,
        classification=factory.Iterator(
            CompanyClassification.objects.all(),  # keeps the ordering
        ),
        one_list_account_owner=AdviserFactory(),
    )
    # ignored because headquarter_type is None
    CompanyFactory(
        headquarter_type=None,
        classification=random_obj_for_model(CompanyClassification),
        one_list_account_owner=AdviserFactory(),
    )
    # ignored because classification is None
    CompanyFactory(
        headquarter_type_id=constants.HeadquarterType.ghq.value.id,
        classification=None,
        one_list_account_owner=AdviserFactory(),
    )
    # ignored because one_list_account_owner is None
    CompanyFactory(
        headquarter_type_id=constants.HeadquarterType.ghq.value.id,
        classification=random_obj_for_model(CompanyClassification),
        one_list_account_owner=None,
    )

    report = OneListReport()
    assert list(report.rows()) == [{
        'name':
        company.name,
        'classification__name':
        company.classification.name,
        'sector__segment':
        company.sector.segment,
        'primary_contact_name':
        company.one_list_account_owner.name,
        'one_list_account_owner__telephone_number':
        company.one_list_account_owner.telephone_number,
        'one_list_account_owner__contact_email':
        company.one_list_account_owner.contact_email,
        'registered_address_country__name':
        company.registered_address_country.name,
        'registered_address_town':
        company.registered_address_town,
        'url':
        f'{settings.DATAHUB_FRONTEND_URL_PREFIXES["company"]}/{company.id}',
    } for company in companies]
    def test_with_multiple_advisers(self, data_flow_api_client):
        """Test that endpoint returns correct order of records"""
        adviser_1 = AdviserFactory(date_joined=datetime(2019, 1, 2, tzinfo=utc))
        adviser_2 = AdviserFactory(date_joined=datetime(2019, 1, 3, tzinfo=utc))
        adviser_3 = AdviserFactory(date_joined=datetime(2019, 1, 1, tzinfo=utc))
        adviser_4 = AdviserFactory(date_joined=datetime(2019, 1, 1, tzinfo=utc))

        response = data_flow_api_client.get(self.view_url)
        assert response.status_code == status.HTTP_200_OK

        assert [a['id'] for a in response.json()['results']] == [
            str(a.id)
            for a in sorted([adviser_3, adviser_4], key=lambda x: x.id) + [adviser_1, adviser_2]
        ]
Beispiel #25
0
    def test_validation_error(self, data_delta, errors):
        """Test validation errors."""
        def resolve(value, order, data):
            if callable(value):
                return value(order, data)
            return value

        order = data_delta.pop('order', None) or OrderPaidFactory()
        order = resolve(order, None, None)

        now_datetime = now()
        now_date_str = now_datetime.date().isoformat()
        now_time_str = now_datetime.time().isoformat()

        url = reverse('admin:omis_payment_refund_add')
        data = {
            'order': order.pk,
            'status': RefundStatus.APPROVED,
            'requested_on_0': now_date_str,
            'requested_on_1': now_time_str,
            'requested_by': AdviserFactory().pk,
            'requested_amount': order.total_cost,
            'refund_reason': 'lorem ipsum refund reason',
            'level1_approved_on_0': now_date_str,
            'level1_approved_on_1': now_time_str,
            'level1_approved_by': AdviserFactory().pk,
            'level1_approval_notes': 'lorem ipsum level 1',
            'level2_approved_on_0': now_date_str,
            'level2_approved_on_1': now_time_str,
            'level2_approved_by': AdviserFactory().pk,
            'level2_approval_notes': 'lorem ipsum level 2',
            'method': PaymentMethod.BACS,
            'net_amount': order.total_cost - 1,
            'vat_amount': 1,
            'additional_reference': 'additional reference',
        }

        for data_key, data_value in data_delta.items():
            data[data_key] = resolve(data_value, order, data)
        response = self.client.post(url, data, follow=True)

        assert response.status_code == status.HTTP_200_OK

        form = response.context['adminform'].form
        assert not form.is_valid()

        for error_key, error_value in errors.items():
            errors[error_key] = resolve(error_value, order, errors)
        assert form.errors == errors
Beispiel #26
0
def test_simulate(s3_stubber, caplog):
    """Test that the command simulates updates if --simulate is passed in."""
    caplog.set_level('ERROR')

    advisers = [
        AdviserFactory(contact_email='*****@*****.**'),
        AdviserFactory(contact_email='*****@*****.**'),
        AdviserFactory(contact_email='*****@*****.**'),
        AdviserFactory(contact_email=''),
        AdviserFactory(contact_email='*****@*****.**'),
    ]

    bucket = 'test_bucket'
    object_key = 'test_key'
    csv_content = f"""id,contact_email
00000000-0000-0000-0000-000000000000,[email protected]
{advisers[0].id},invalid_email
{advisers[1].id},[email protected]
{advisers[2].id},[email protected]
{advisers[3].id},[email protected]
{advisers[4].id},
"""

    s3_stubber.add_response(
        'get_object',
        {
            'Body': BytesIO(bytes(csv_content, encoding='utf-8')),
        },
        expected_params={
            'Bucket': bucket,
            'Key': object_key,
        },
    )

    call_command('update_adviser_contact_email', bucket, object_key, simulate=True)

    assert len(caplog.records) == 2
    assert 'Advisor matching query does not exist' in caplog.text
    assert 'Enter a valid email address' in caplog.text

    for adviser in advisers:
        adviser.refresh_from_db()

    expected_emails = [
        '*****@*****.**', '*****@*****.**', '*****@*****.**', '', '*****@*****.**',

    ]
    assert [adviser.contact_email for adviser in advisers] == expected_emails
    def test_ok_if_order_in_allowed_status(self, allowed_status):
        """
        Test that the order can be marked as paid if the order is in one of the allowed statuses.
        """
        order = OrderWithAcceptedQuoteFactory(status=allowed_status)
        adviser = AdviserFactory()

        order.mark_as_paid(
            by=adviser,
            payments_data=[
                {
                    'amount': 1,
                    'received_on': dateutil_parse('2017-01-01').date(),
                },
                {
                    'amount': order.total_cost - 1,
                    'received_on': dateutil_parse('2017-01-02').date(),
                },
            ],
        )

        order.refresh_from_db()
        assert order.status == OrderStatus.paid
        assert order.paid_on == dateutil_parse('2017-01-02T00:00:00Z')
        assert list(
            order.payments.order_by('received_on').values_list(
                'amount', 'received_on'), ) == [
                    (1, dateutil_parse('2017-01-01').date()),
                    (order.total_cost - 1,
                     dateutil_parse('2017-01-02').date()),
                ]
Beispiel #28
0
    def test_get_one_list_group_core_team(
        self,
        build_company,
        with_global_account_manager,
    ):
        """
        Test that `get_one_list_group_core_team` returns the Core Team of `self` if the company
        has no `global_headquarters` or the one of its `global_headquarters` otherwise.
        """
        team_member_advisers = AdviserFactory.create_batch(
            3,
            first_name=factory.Iterator(
                ('Adam', 'Barbara', 'Chris'),
            ),
        )
        global_account_manager = team_member_advisers[0] if with_global_account_manager else None

        company = build_company(global_account_manager)
        group_global_headquarters = company.global_headquarters or company

        OneListCoreTeamMemberFactory.create_batch(
            len(team_member_advisers),
            company=group_global_headquarters,
            adviser=factory.Iterator(team_member_advisers),
        )

        core_team = company.get_one_list_group_core_team()
        assert core_team == [
            {
                'adviser': adviser,
                'is_global_account_manager': adviser is global_account_manager,
            }
            for adviser in team_member_advisers
        ]
    def test_400_if_assignee_added_with_extra_field(self, data):
        """
        Test that estimated_time and is_lead cannot be set at this stage
        even when adding a new assignee.
        """
        order = OrderPaidFactory()
        new_adviser = AdviserFactory()

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.patch(
            url,
            [
                {
                    'adviser': {
                        'id': new_adviser.id,
                    },
                    **data,
                },
            ],
        )

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.json() == [
            {
                list(data)[0]: [
                    'This field cannot be changed at this stage.',
                ],
            },
        ]
    def test_409_if_order_not_in_allowed_status(self, disallowed_status):
        """
        Test that if the order is not in one of the allowed statuses, the endpoint
        returns 409.
        """
        order = OrderFactory(status=disallowed_status)

        url = reverse(
            'api-v3:omis:order:assignee',
            kwargs={'order_pk': order.id},
        )
        response = self.api_client.patch(
            url,
            [{
                'adviser': {
                    'id': AdviserFactory().id
                },
            }],
        )

        assert response.status_code == status.HTTP_409_CONFLICT
        assert response.json() == {
            'detail': ('The action cannot be performed '
                       f'in the current status {disallowed_status.label}.'),
        }