예제 #1
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['breadcrumb'] = build_breadcrumb(
         [home_link(), dashboard_link(include_link=False)])
     for notification in context['notification_list']:
         notification.url = get_url_for_notification(
             notification.source, notification.target_id)
     context['todos'] = UserService.get_user_todos(self.request.user,
                                                   self.request.user)
     context['my_tasks'] = ProjectTaskService.get_user_in_progress_tasks(
         self.request.user)
     context[
         'my_task_applications'] = ProjectTaskService.get_volunteer_open_task_applications(
             self.request.user, None)
     context['user_is_volunteer'] = UserService.user_has_volunteer_profile(
         self.request.user)
     context[
         'user_is_any_organization_member'] = OrganizationService.user_is_any_organization_member(
             self.request.user)
     organizations = OrganizationService.get_organizations_with_user_create_project_permission(
         self.request.user)
     if len(organizations) == 1:
         context['single_org_membership'] = organizations[0]
     else:
         context['organization_memberships'] = organizations
     return context
예제 #2
0
파일: org.py 프로젝트: abell5/marketplace
def organization_role_delete_view(request, org_pk, role_pk):
    organization_role = get_organization_role_by_pk(request, org_pk, role_pk)
    if request.method == 'POST':
        form = DeleteOrganizationRoleForm(request.POST)
        if form.is_valid():
            try:
                OrganizationService.delete_organization_role(
                    request.user, org_pk, organization_role)
                messages.info(request, 'Staff member removed successfully.')
                return redirect('marketplace:org_staff', org_pk=org_pk)
            except KeyError:
                raise Http404
            except ValueError as err:
                logger.error(
                    "Error when trying to remove user {0} from organization {1}: {2}"
                    .format(request.user.id, organization_role.organization.id,
                            err))
                form.add_error(None, str(err))
    elif request.method == 'GET':
        form = DeleteOrganizationRoleForm()
    organization = get_organization(request, org_pk)
    return render(
        request, 'marketplace/org_staff_remove.html',
        add_organization_common_context(
            request, organization, 'staff', {
                'organizationrole':
                organization_role,
                'breadcrumb':
                organization_breadcrumb(organization,
                                        organization_staff_link(organization),
                                        ('Remove staff member', None)),
                'form':
                form,
            }))
예제 #3
0
파일: org.py 프로젝트: abell5/marketplace
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['breadcrumb'] = organization_breadcrumb(self.object)
        organization = self.object

        members = []
        if organization.is_volunteer_group():
            members = OrganizationService.get_organization_members(
                self.request.user, organization)
        context['members'] = paginate(self.request,
                                      members,
                                      request_key='members_page',
                                      page_size=25)

        projects = OrganizationService.get_organization_projects(
            self.request.user, organization)
        context['projects'] = paginate(self.request,
                                       projects,
                                       request_key='projects_page',
                                       page_size=25)

        add_organization_common_context(self.request, self.object, 'info',
                                        context)
        context[
            'user_is_pending_membership'] = OrganizationService.user_is_pending_membership(
                self.request.user, organization)

        return context
예제 #4
0
 def test_create_duplicate_organization(self):
     with self.assertRaisesMessage(
             ValueError, 'An organization with this name already exists.'):
         OrganizationService.create_organization(self.organization_user,
                                                 self.organization)
         OrganizationService.create_organization(self.organization_user,
                                                 self.organization)
예제 #5
0
파일: org.py 프로젝트: abell5/marketplace
 def form_valid(self, form):
     organization_role = form.save(commit=False)
     try:
         OrganizationService.save_organization_role(self.request.user,
                                                    self.kwargs['org_pk'],
                                                    organization_role)
         messages.info(self.request, 'User role edited successfully.')
         return HttpResponseRedirect(self.get_success_url())
     except ValueError as v:
         form.add_error(None, str(v))
         return super().form_invalid(form)
예제 #6
0
파일: org.py 프로젝트: abell5/marketplace
 def form_valid(self, form):
     organization = form.save(commit=False)
     try:
         OrganizationService.save_organization_info(self.request.user,
                                                    self.kwargs['org_pk'],
                                                    organization)
         OrganizationService.save_organization_social_causes(
             self.request.user, self.kwargs['org_pk'], organization,
             self.request.POST)
         return HttpResponseRedirect(self.get_success_url())
     except KeyError as k:
         form.add_error(None, str(k))
         return super().form_invalid(form)
예제 #7
0
파일: org.py 프로젝트: abell5/marketplace
def add_organization_staff_view(request, org_pk):
    if request.method == 'POST':
        form_errors = []
        userid = request.POST.get('userid')
        role = request.POST.get('role')
        if userid and role:
            try:
                OrganizationService.add_staff_member_by_id(
                    request.user, org_pk, userid, role)
                messages.info(request, 'Staff member added successfully.')
                return redirect('marketplace:org_staff', org_pk=org_pk)
            except ValueError as v:
                form_errors.append(str(v))
            except KeyError as k:
                form_errors.append(str(k))
        else:
            if not userid:
                form_errors.append(
                    'Plese select a user to add to the organization.')
            if not role:
                form_errors.append('Plese select a role for the user.')

    organization = get_organization(request, org_pk)
    organization_staff = OrganizationService.get_organization_staff(
        request.user, organization)
    staff_page = paginate(request,
                          organization_staff,
                          request_key='staff_page',
                          page_size=25)

    organization_requests = OrganizationService.get_membership_requests(
        request.user, organization)
    requests_page = paginate(request,
                             organization_requests,
                             request_key='requests_page',
                             page_size=25)
    return render(
        request, 'marketplace/org_staff.html',
        add_organization_common_context(
            request, organization, 'staff', {
                'breadcrumb':
                organization_breadcrumb(organization, ('Staff', None)),
                'organization_staff':
                staff_page,
                'organization_requests':
                requests_page,
                'organization_roles':
                OrganizationService.get_organization_roles(),
                'form_errors':
                form_errors,
            }))
예제 #8
0
    def test_edit_organization(self):
        OrganizationService.create_organization(self.organization_user,
                                                self.organization)
        self.organization.name = "EDITED Organization A"
        self.organization.short_summary = "EDITED A short description of the org"
        self.organization.description = "EDITED A long form description of the organization"
        self.organization.website_url = "http://exampleorg.com/EDITED"
        self.organization.phone_number = "(111)111-EDITED"
        self.organization.email_address = "*****@*****.**"
        self.organization.street_address = "EDITED 1 One Street"
        self.organization.city = "EDITED OrgCity"
        self.organization.state = "EDITED OrgState"
        self.organization.zipcode = "EDITED11111"
        self.organization.budget = Budget.B50MP
        self.organization.years_operation = YearsInOperation.Y25
        self.organization.organization_scope = GeographicalScope.COUNTRY

        with self.subTest(stage='Add staff member'):
            OrganizationService.add_staff_member_by_id(self.organization_user,
                                                       self.organization.id,
                                                       self.staff_user.id,
                                                       None)

        with self.subTest(stage='Edit organization'):
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user, self.staff_user],
                lambda x: OrganizationService.save_organization_info(
                    x, self.organization.id, self.organization))
            OrganizationService.save_organization_info(self.organization_user,
                                                       self.organization.id,
                                                       self.organization)
            self.assertEqual(
                self.organization,
                OrganizationService.get_organization(self.organization_user,
                                                     self.organization.id))
예제 #9
0
파일: org.py 프로젝트: abell5/marketplace
 def form_valid(self, form):
     membership_request = form.save(commit=False)
     try:
         OrganizationService.create_membership_request(
             self.request.user, self.request.user, self.kwargs['org_pk'],
             membership_request)
         messages.info(
             self.request, 'Membership request for ' +
             membership_request.organization.name +
             ' successful. You will be notifed when the administrators make a decision about your membership.'
         )
         return HttpResponseRedirect(self.get_success_url())
     except KeyError:
         raise Http404
예제 #10
0
파일: org.py 프로젝트: abell5/marketplace
def add_organization_common_context(request, organization, page_tab, context):
    context['organization'] = organization
    context['page_tab'] = page_tab
    if not request.user.is_anonymous:
        context[
            'user_is_staff'] = OrganizationService.user_is_organization_staff(
                request.user, organization)
        context[
            'user_is_administrator'] = OrganizationService.user_is_organization_admin(
                request.user, organization)
        context[
            'user_is_member'] = OrganizationService.user_is_organization_member(
                request.user, organization)
    return context
예제 #11
0
파일: org.py 프로젝트: abell5/marketplace
def organization_list_view(request):
    checked_social_cause_fields = {}
    checked_type_fields = {}
    checked_project_fields = {}
    filter_orgname = ""
    if request.method == 'POST':
        search_config = {}
        if 'orgname' in request.POST and request.POST.get('orgname'):
            search_config['name'] = request.POST.get('orgname')
            filter_orgname = request.POST.get('orgname')
        if 'socialcause' in request.POST:
            search_config['social_cause'] = request.POST.getlist('socialcause')
            for f in request.POST.getlist('socialcause'):
                checked_social_cause_fields[f] = True
        if 'type' in request.POST:
            search_config['type'] = request.POST.getlist('type')
            for f in request.POST.getlist('type'):
                checked_type_fields[f] = True
        if 'projectstatus' in request.POST:
            search_config['project_status'] = request.POST.getlist(
                'projectstatus')
            for f in request.POST.getlist('projectstatus'):
                checked_project_fields[f] = True
        organizations = OrganizationService.get_all_organizations(
            request.user, search_config)
    elif request.method == 'GET':
        organizations = OrganizationService.get_all_organizations(request.user)

    if organizations:
        organizations_page = paginate(request, organizations, page_size=15)
    else:
        organizations_page = []

    return render(
        request, 'marketplace/org_list.html', {
            'breadcrumb':
            build_breadcrumb([home_link(),
                              organizations_link(False)]),
            'org_list':
            organizations_page,
            'checked_social_cause_fields':
            checked_social_cause_fields,
            'checked_type_fields':
            checked_type_fields,
            'checked_project_fields':
            checked_project_fields,
            'filter_orgname':
            filter_orgname
        })
예제 #12
0
파일: org.py 프로젝트: abell5/marketplace
def organization_staff_view(request, org_pk):
    if request.method == 'POST':
        form = CreateOrganizationRoleForm(request.POST)
        if form.is_valid():
            organization_role = form.save(commit=False)
            try:
                OrganizationService.add_staff_member(request.user, org_pk,
                                                     organization_role)
                messages.info(request, 'Staff member added successfully.')
                return redirect('marketplace:org_staff', org_pk=org_pk)
            except KeyError:
                raise Http404
            except ValueError:
                form.add_error(
                    None, "This user is already a member of the organization.")
    elif request.method == 'GET':
        form = CreateOrganizationRoleForm()
    organization = get_organization(request, org_pk)

    organization_staff = OrganizationService.get_organization_staff(
        request.user, organization)
    staff_page = paginate(request,
                          organization_staff,
                          request_key='staff_page',
                          page_size=25)

    organization_requests = OrganizationService.get_membership_requests(
        request.user, organization)
    requests_page = paginate(request,
                             organization_requests,
                             request_key='requests_page',
                             page_size=25)

    return render(
        request, 'marketplace/org_staff.html',
        add_organization_common_context(
            request, organization, 'staff', {
                'breadcrumb':
                organization_breadcrumb(organization, ('Staff', None)),
                'organization_staff':
                staff_page,
                'organization_requests':
                requests_page,
                'add_staff_form':
                form,
                'organization_roles':
                OrganizationService.get_organization_roles(),
            }))
예제 #13
0
 def test_filter_organization(self):
     OrganizationService.create_organization(self.organization_user,
                                             self.organization)
     sc = OrganizationSocialCause()
     sc.social_cause = SocialCause.EDUCATION
     sc.organization = self.organization
     sc.save()
     org_result_list = [self.organization]
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user, {'name': 'ORGAN'})),
         org_result_list)
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user, {'name': 'no match'})), [])
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user, {'name': ' A'})), org_result_list)
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user, {'social_cause': 'education'})),
         org_result_list)
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user,
                 {'social_cause': ['education', 'health']})),
         org_result_list)
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user, {'social_cause': ['health']})), [])
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user, {'project_status': 'new'})), [])
     self.assertEqual(
         list(
             OrganizationService.get_all_organizations(
                 self.organization_user,
                 {'project_status': ['new', 'completed']})), [])
예제 #14
0
파일: org.py 프로젝트: abell5/marketplace
 def delete(self, request, *args, **kwargs):
     organization_role = self.get_object()
     self.object = organization_role
     try:
         OrganizationService.leave_organization(request.user,
                                                self.kwargs['org_pk'],
                                                organization_role)
         messages.info(
             request, 'You left ' + organization_role.organization.name +
             ' successfully.')
         return HttpResponseRedirect(self.get_success_url())
     except ValueError as err:
         messages.error(request, 'There was a problem with your request.')
         logger.error(
             "Error when user {0} tried to leave organization {1}: {2}".
             format(request.user.id, organization_role.organization.id,
                    err))
         return HttpResponseRedirect(self.get_success_url())
예제 #15
0
파일: org.py 프로젝트: abell5/marketplace
 def form_valid(self, form):
     organization = form.save(commit=False)
     try:
         organization = OrganizationService.create_organization(
             self.request.user, organization, self.request.POST.get('type'))
         OrganizationService.save_organization_social_causes(
             self.request.user, organization.id, organization,
             self.request.POST)
         messages.info(
             self.request,
             "You have created a new organization and are now its first administrator user."
         )
         self.object = organization
         return HttpResponseRedirect(self.get_success_url())
     except KeyError:
         raise Http404
     except ValueError as v:
         form.add_error(None, str(v))
         return self.form_invalid(form)
예제 #16
0
파일: org.py 프로젝트: abell5/marketplace
def process_organization_membership_request_view(request,
                                                 org_pk,
                                                 request_pk,
                                                 action=None):
    membership_request = get_organization_membership_request(
        request, org_pk, request_pk)
    if request.method == 'POST':
        form = OrganizationMembershipRequestForm(request.POST,
                                                 instance=membership_request)
        if form.is_valid():
            membership_request = form.save(commit=False)
            try:
                if action == 'accept':
                    OrganizationService.accept_membership_request(
                        request.user, org_pk, membership_request)
                    messages.info(request, 'Membership request accepted.')
                else:
                    OrganizationService.reject_membership_request(
                        request.user, org_pk, membership_request)
                    messages.info(request, 'Membership request rejected.')
                return redirect('marketplace:org_staff', org_pk=org_pk)
            except KeyError:
                raise Http404
    elif request.method == 'GET':
        form = OrganizationMembershipRequestForm()
    organization = get_organization(request, org_pk)

    return render(
        request, 'marketplace/org_staff_request_review.html',
        add_organization_common_context(
            request, organization, 'staff', {
                'organizationmembershiprequest':
                membership_request,
                'breadcrumb':
                organization_breadcrumb(
                    organization, organization_staff_link(organization),
                    organization_membership_request_link(membership_request,
                                                         include_link=False)),
                'form':
                form,
            }))
예제 #17
0
def home_view(request):
    # featured volunteer
    featured_volunteer = UserService.get_featured_volunteer()
    if featured_volunteer:
        featured_volunteer_skills = (
            featured_volunteer.user.volunteerskill_set.filter(
                level=SkillLevel.EXPERT).values_list('skill__name', flat=True))
    else:
        featured_volunteer_skills = None

    # platform stats
    avg_days_month = 365.25 / 12
    one_avg_month = timedelta(days=avg_days_month)
    one_avg_month_ago = timezone.now() - one_avg_month

    return render(
        request, 'marketplace/home_anonymous.html', {
            'user_is_any_organization_member':
            OrganizationService.user_can_create_projects(request.user),
            'featured_project':
            ProjectService.get_featured_project(),
            'featured_organization':
            OrganizationService.get_featured_organization(),
            'featured_volunteer':
            featured_volunteer,
            'featured_volunteer_skills':
            featured_volunteer_skills,
            'news':
            NewsService.get_latest_news(request.user),
            'platform_stats': {
                'projects_in_design':
                Project.objects.filter(status=ProjectStatus.DESIGN).count(),
                'projects_this_month':
                Project.objects.filter(
                    creation_date__gte=one_avg_month_ago).count(),
                'volunteers_this_month':
                VolunteerProfile.objects.filter(
                    creation_date__gte=one_avg_month_ago).count(),
            },
        })
예제 #18
0
    def test_create_organization(self):
        all_organizations = OrganizationService.get_all_organizations(
            self.organization_user)
        with self.subTest(stage='No starting organizations'):
            self.assertFalse(all_organizations.exists())

        with self.subTest(stage='Create organization'):
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user],
                lambda x: OrganizationService.create_organization(
                    x, self.organization))
            OrganizationService.create_organization(self.organization_user,
                                                    self.organization)

        all_organizations = OrganizationService.get_all_organizations(
            self.organization_user)
        saved_organization = OrganizationService.get_organization(
            self.organization_user, self.organization.id)

        with self.subTest(stage='Test created organization'):
            self.assertEqual(len(all_organizations), 1)
            self.assertEqual(all_organizations.first().name,
                             self.organization.name)
            self.assertEqual(all_organizations.first(), saved_organization)
            self.assertEqual(
                list(OrganizationService.get_all_organizations(
                    AnonymousUser())),
                list(
                    OrganizationService.get_all_organizations(
                        self.organization_user)),
            )
            self.assertEqual(
                saved_organization,
                OrganizationService.get_organization(AnonymousUser(),
                                                     self.organization.id),
            )
            self.assertEqual(OrganizationService.get_featured_organization(),
                             self.organization)
예제 #19
0
파일: org.py 프로젝트: abell5/marketplace
def get_all_users_not_organization_members_json(request, org_pk, query=None):
    users = OrganizationService.get_all_users_not_organization_members(
        org_pk, query)
    json_users = []
    for user in users:
        json_users.append({
            'name':
            user['first_name'] + " " + user['last_name'] + " (" +
            user['username'] + ")",
            'id':
            str(user['id'])
        })
    data = {'users': json_users}
    return JsonResponse(data)
예제 #20
0
 def test_create_duplicate_role(self):
     OrganizationService.create_organization(self.organization_user,
                                             self.organization)
     OrganizationService.add_staff_member_by_id(self.organization_user,
                                                self.organization.id,
                                                self.staff_user.id, None)
     with self.assertRaisesMessage(ValueError, ''):
         OrganizationService.add_staff_member_by_id(self.organization_user,
                                                    self.organization.id,
                                                    self.staff_user.id,
                                                    None)
예제 #21
0
    def test_organization_roles(self):
        OrganizationService.create_organization(self.organization_user,
                                                self.organization)
        with self.subTest(stage='Check initial organization user\'s roles'):
            self.assertTrue(
                OrganizationService.user_is_organization_admin(
                    self.organization_user, self.organization))
            self.assertTrue(
                OrganizationService.user_is_organization_member(
                    self.organization_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_organization_staff(
                    self.organization_user, self.organization))
            self.assertTrue(
                OrganizationService.user_is_any_organization_member(
                    self.organization_user))

        with self.subTest(stage='Check initial volunteer user\'s roles'):
            self.assertFalse(
                OrganizationService.user_is_organization_admin(
                    self.volunteer_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_organization_member(
                    self.volunteer_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_organization_staff(
                    self.volunteer_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_any_organization_member(
                    self.volunteer_user))

        with self.subTest(stage='Add staff member'):
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user, self.staff_user],
                lambda x: OrganizationService.add_staff_member_by_id(
                    x, self.organization.id, self.staff_user.id, None))
            OrganizationService.add_staff_member_by_id(self.organization_user,
                                                       self.organization.id,
                                                       self.staff_user.id,
                                                       None)

        with self.subTest(stage='Check staff user\'s roles'):
            self.assertFalse(
                OrganizationService.user_is_organization_admin(
                    self.staff_user, self.organization))
            self.assertTrue(
                OrganizationService.user_is_organization_member(
                    self.staff_user, self.organization))
            self.assertTrue(
                OrganizationService.user_is_organization_staff(
                    self.staff_user, self.organization))
            self.assertTrue(
                OrganizationService.user_is_any_organization_member(
                    self.staff_user))

        with self.subTest(stage='Check organization group roles'):
            organization_staff_roles = OrganizationService.get_organization_staff(
                self.organization_user, self.organization)
            org_admin_user_role = OrganizationService.get_organization_role(
                self.organization_user, self.organization.id,
                self.organization_user.id)
            org_staff_user_role = OrganizationService.get_organization_role(
                self.organization_user, self.organization.id,
                self.staff_user.id)
            self.assertEqual(list(organization_staff_roles), [
                org_admin_user_role,
                org_staff_user_role,
            ])
            self.assertEqual(
                org_admin_user_role,
                OrganizationService.get_organization_role_by_pk(
                    self.organization_user, self.organization.id,
                    org_admin_user_role.id))
            self.assertEqual(
                org_staff_user_role,
                OrganizationService.get_organization_role_by_pk(
                    self.organization_user, self.organization.id,
                    org_staff_user_role.id))

        with self.subTest(stage='Check organization members'):
            organization_members = OrganizationService.get_organization_members(
                self.organization_user, self.organization)
            self.assertEqual(set(organization_members),
                             set([self.organization_user, self.staff_user]))

        with self.subTest(stage='Check organization admins'):
            organization_admins = OrganizationService.get_organization_admins(
                self.organization_user, self.organization)
            self.assertEqual(set(organization_admins),
                             set([self.organization_user]))

        with self.subTest(stage='Check non members'):
            volunteer_user_match = {
                'id': self.volunteer_user.id,
                'first_name': self.volunteer_user.first_name,
                'last_name': self.volunteer_user.last_name,
                'username': self.volunteer_user.username,
            }
            self.assertEqual(
                list(
                    OrganizationService.get_all_users_not_organization_members(
                        self.organization.id)), [volunteer_user_match])
            self.assertEqual(
                list(
                    OrganizationService.get_all_users_not_organization_members(
                        self.organization.id, "olu")), [volunteer_user_match])
            self.assertEqual(
                list(
                    OrganizationService.get_all_users_not_organization_members(
                        self.organization.id, "volunteer")),
                [volunteer_user_match])
            self.assertEqual(
                list(
                    OrganizationService.get_all_users_not_organization_members(
                        self.organization.id, "use")), [volunteer_user_match])
            self.assertEqual(
                list(
                    OrganizationService.get_all_users_not_organization_members(
                        self.organization.id, "eer@ema")),
                [volunteer_user_match])
            self.assertEqual(
                list(
                    OrganizationService.get_all_users_not_organization_members(
                        self.organization.id, "bad_match")), [])

        with self.subTest(stage='Leave organization'):
            test_permission_denied_operation(
                self,
                [AnonymousUser(), self.volunteer_user, self.organization_user],
                lambda x: OrganizationService.leave_organization(
                    x, self.organization.id, org_staff_user_role))
            OrganizationService.leave_organization(self.staff_user,
                                                   self.organization.id,
                                                   org_staff_user_role)
            self.assertFalse(
                OrganizationService.user_is_organization_admin(
                    self.staff_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_organization_member(
                    self.staff_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_organization_staff(
                    self.staff_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_any_organization_member(
                    self.staff_user))
            with self.assertRaisesMessage(
                    OrganizationRole.DoesNotExist,
                    'OrganizationRole matching query does not exist.'):
                OrganizationService.get_organization_role(
                    self.organization_user, self.organization.id,
                    self.staff_user.id)

        with self.subTest(stage='Add staff member'):
            test_permission_denied_operation(
                self, [AnonymousUser(), self.staff_user],
                lambda x: OrganizationService.add_staff_member(
                    x, self.organization.id, org_staff_user_role))
            OrganizationService.add_staff_member(self.organization_user,
                                                 self.organization.id,
                                                 org_staff_user_role)

        with self.subTest(stage='Edit organization role'):
            org_staff_user_role.role = OrgRole.ADMINISTRATOR
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user, self.staff_user],
                lambda x: OrganizationService.save_organization_role(
                    x, self.organization.id, org_staff_user_role))
            OrganizationService.save_organization_role(self.organization_user,
                                                       self.organization.id,
                                                       org_staff_user_role)
            self.assertTrue(
                OrganizationService.user_is_organization_admin(
                    self.staff_user, self.organization))

        with self.subTest(stage='Delete organization role'):
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user],
                lambda x: OrganizationService.delete_organization_role(
                    x, self.organization.id, org_staff_user_role))
            OrganizationService.delete_organization_role(
                self.organization_user, self.organization.id,
                org_staff_user_role)
            self.assertFalse(
                OrganizationService.user_is_organization_admin(
                    self.staff_user, self.organization))
            self.assertFalse(
                OrganizationService.user_is_organization_member(
                    self.staff_user, self.organization))
예제 #22
0
    def test_organization_membership_requests(self):
        OrganizationService.create_organization(self.organization_user,
                                                self.organization)
        with self.subTest(stage='Initial membership requests'):
            self.assertEqual(
                list(
                    OrganizationService.get_membership_requests(
                        self.organization_user, self.organization)), [])
            self.assertEqual(
                list(
                    OrganizationService.
                    get_user_organizations_with_pending_requests(
                        self.organization_user)), [])

        membership_request = OrganizationMembershipRequest()
        membership_request.user = self.staff_user
        membership_request.role = OrgRole.STAFF

        with self.subTest(stage='Create membership request'):
            with self.assertRaisesMessage(ValueError, ''):
                OrganizationService.create_membership_request(
                    self.staff_user, AnonymousUser(), self.organization.id,
                    membership_request)
            OrganizationService.create_membership_request(
                self.staff_user, self.staff_user, self.organization.id,
                membership_request)
            self.assertEqual(
                list(
                    OrganizationService.get_membership_requests(
                        self.organization_user, self.organization)),
                [membership_request])
            self.assertEqual(
                list(
                    OrganizationService.
                    get_user_organizations_with_pending_requests(
                        self.organization_user)), [self.organization])

        with self.subTest(stage='Accept membership request'):
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user],
                lambda x: OrganizationService.accept_membership_request(
                    x, self.organization.id, membership_request))
            OrganizationService.accept_membership_request(
                self.organization_user, self.organization.id,
                membership_request)
            self.assertEqual(
                OrganizationService.get_organization_membership_request(
                    self.organization_user, self.organization.id,
                    membership_request.id).status, ReviewStatus.ACCEPTED)
            self.assertEqual(
                list(
                    OrganizationService.
                    get_user_organizations_with_pending_requests(
                        self.organization_user)), [])
            self.assertTrue(
                OrganizationService.user_is_organization_staff(
                    self.staff_user, self.organization))

        membership_request = OrganizationMembershipRequest()
        membership_request.user = self.staff_user  # We make sure the user is automatically replaced later with the right one
        membership_request.role = OrgRole.STAFF

        with self.subTest(stage='Reject membership request'):
            OrganizationService.create_membership_request(
                self.organization_user, self.volunteer_user,
                self.organization.id, membership_request)
            test_permission_denied_operation(
                self, [AnonymousUser(), self.volunteer_user, self.staff_user],
                lambda x: OrganizationService.reject_membership_request(
                    x, self.organization.id, membership_request))
            OrganizationService.reject_membership_request(
                self.organization_user, self.organization.id,
                membership_request)
            self.assertEqual(
                list(
                    OrganizationService.
                    get_user_organizations_with_pending_requests(
                        self.organization_user)), [])
            self.assertFalse(
                OrganizationService.user_is_organization_member(
                    self.volunteer_user, self.organization))
예제 #23
0
def is_organization_role_admin(user, organization_role):
    return OrganizationService.user_is_organization_admin(
        user, organization_role.organization)
예제 #24
0
def is_organization_membership_request_admin(user, membership_request):
    return OrganizationService.user_is_organization_admin(
        user, membership_request.organization)
예제 #25
0
 def handle(self, *args, **options):
     path = options.get('file_path')
     self.stdout.write('Loading projects file {0}'.format(path))
     with open(path) as csvfile:
         reader = DictReader(csvfile)
         # ['user_pk', 'org_pk',
         #     'name', 'short_summary', 'motivation','solution_description',
         #     'challenges', 'banner_image_url', 'project_cause', 'project_impact',
         #     'scoping_process', 'available_staff', 'available_data',
         #     'developer_agreement', 'intended_start_date',
         #     'intended_end_date', 'status', 'deliverables_description',
         #     'deliverable_github_url', 'deliverable_management_url',
         #     'deliverable_documentation_url', 'deliverable_reports_url',
         #     'is_demo'])
         for row in reader:
             new_project = Project()
             new_project.name = row['name']
             new_project.short_summary = row['short_summary']
             new_project.motivation = row['motivation']
             new_project.solution_description = row['solution_description']
             new_project.project_impact = row['project_impact']
             new_project.stakeholders = row['stakeholders']
             new_project.available_staff = row['available_staff']
             new_project.banner_image_url = row['banner_image_url']
             new_project.project_cause = row['project_cause']
             new_project.scope_goals = row['scope_goals']
             new_project.scope_interventions = row['scope_interventions']
             new_project.scope_available_data = row['scope_available_data']
             new_project.scope_analysis = row['scope_analysis']
             new_project.scope_validation_methodology = row[
                 'scope_validation_methodology']
             new_project.scope_implementation = row['scope_implementation']
             new_project.developer_agreement = row['developer_agreement']
             new_project.intended_start_date = row['intended_start_date']
             new_project.intended_end_date = row['intended_end_date']
             new_project.status = row['status']
             new_project.deliverables_description = row[
                 'deliverables_description']
             new_project.deliverable_github_url = row[
                 'deliverable_github_url']
             new_project.deliverable_management_url = row[
                 'deliverable_management_url']
             new_project.deliverable_documentation_url = row[
                 'deliverable_documentation_url']
             new_project.deliverable_reports_url = row[
                 'deliverable_reports_url']
             new_project.is_demo = row['is_demo']
             try:
                 organization_pk = int(row['org_pk'])
                 user_pk = int(row['user_pk'])
                 owner = User.objects.get(pk=user_pk)
                 OrganizationService.create_project(owner, organization_pk,
                                                    new_project)
                 if row['status']:
                     new_project.status = row['status']
                     ProjectService.save_project(owner, new_project.id,
                                                 new_project)
                 self.stdout.write(
                     'Created project {0}'.format(new_project))
             except Exception as e:
                 self.stdout.write(
                     self.style.WARNING(
                         'Failed to create project {0}: {1}'.format(
                             new_project, str(e))))
     self.stdout.write(self.style.SUCCESS('Finished loading projects.'))