Beispiel #1
0
  def users_download(self, context: Context, community_id, team_id) -> Tuple[list, MassEnergizeAPIError]:
    try:
      self.community_id = community_id
      if team_id:
        community_name = Team.objects.get(id=team_id).name
      elif community_id:
        community_name = Community.objects.get(id=community_id).name

      if context.user_is_super_admin:
        if team_id:
          return (self._team_users_download(team_id), community_name), None
        elif community_id:
          return (self._community_users_download(community_id), community_name), None
        else:
          return (self._all_users_download(), None), None
      elif context.user_is_community_admin:
        if team_id:
          return (self._team_users_download(team_id), community_name), None
        elif community_id:
          return (self._community_users_download(community_id), community_name), None
        else:
          return EMPTY_DOWNLOAD, NotAuthorizedError()
      else:
        return EMPTY_DOWNLOAD, NotAuthorizedError()
    except Exception as e:
      print(str(e))
      capture_message(str(e), level="error")
      return EMPTY_DOWNLOAD, CustomMassenergizeError(e)
Beispiel #2
0
    def list_teams_for_community_admin(self, context: Context,
                                       args) -> (list, MassEnergizeAPIError):
        try:
            if context.user_is_super_admin:
                return self.list_teams_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            community_id = args.pop('community_id', None)
            if not community_id or community_id == 'undefined':
                user = UserProfile.objects.get(pk=context.user_id)
                admin_groups = user.communityadmingroup_set.all()
                comm_ids = [ag.community.id for ag in admin_groups]
                teams = Team.objects.filter(community__id__in=comm_ids,
                                            is_deleted=False).select_related(
                                                'logo', 'community')
                return teams, None

            teams = Team.objects.filter(community__id=community_id,
                                        is_deleted=False).select_related(
                                            'logo', 'community')
            return teams, None

        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)
Beispiel #3
0
  def list_vendors_for_community_admin(self, context: Context, community_id) -> Tuple[list, MassEnergizeAPIError]:
    try:
      if context.user_is_super_admin:
        return self.list_vendors_for_super_admin(context)

      elif not context.user_is_community_admin:
        return None, NotAuthorizedError()

      # community_id coming from admin portal as "null"
      if not community_id or community_id=='undefined' or community_id=='null':     
        # different code in action.py/event.py
        #user = UserProfile.objects.get(pk=context.user_id)
        #admin_groups = user.communityadmingroup_set.all()
        #comm_ids = [ag.community.id for ag in admin_groups]
        #vendors = Vendor.objects.filter(community__id__in = comm_ids, is_deleted=False).select_related('logo', 'community')
        communities, err = get_admin_communities(context)
        vendors = None
        for c in communities:
          if vendors is not None:
            vendors |= c.community_vendors.filter(is_deleted=False).select_related('logo').prefetch_related('communities', 'tags')
          else:
            vendors = c.community_vendors.filter(is_deleted=False).select_related('logo').prefetch_related('communities', 'tags')

        return vendors.distinct(), None

      community = get_community_or_die(context, {'community_id': community_id})
      vendors = community.community_vendors.filter(is_deleted=False).select_related('logo').prefetch_related('communities', 'tags')
      return vendors, None
    except Exception as e:
      capture_message(str(e), level="error")
      return None, CustomMassenergizeError(e)
Beispiel #4
0
    def list_graphs_for_community_admin(
            self, context: Context,
            community_id) -> Tuple[list, MassEnergizeAPIError]:
        try:
            if context.user_is_super_admin:
                return self.list_graphs_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            user = UserProfile.objects.get(pk=context.user_id)
            admin_groups = user.communityadmingroup_set.all()
            comm_ids = [ag.community.id for ag in admin_groups]
            communities = [ag.community for ag in admin_groups]

            graphs = []
            for community in communities:
                g, err = self.graph_actions_completed(
                    context, {"community_id": community.id})
                if g:
                    graphs.append({community.name: g["data"]})

            comm_impact = []
            for c in Community.objects.filter(is_deleted=False,
                                              id__in=comm_ids):
                comm_impact.append(get_households_engaged(c))
            comm_impact.append(get_all_households_engaged())
            return {
                "actions_completed": graphs,
                "communities_impact": comm_impact
            }, None

        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)
Beispiel #5
0
    def list_events_for_community_admin(
            self, context: Context,
            community_id) -> (list, MassEnergizeAPIError):
        try:
            if context.user_is_super_admin:
                return self.list_events_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            # community_id coming from admin portal is 'undefined'
            if not community_id or community_id == 'undefined':
                user = UserProfile.objects.get(pk=context.user_id)
                admin_groups = user.communityadmingroup_set.all()
                comm_ids = [ag.community.id for ag in admin_groups]
                events = Event.objects.filter(
                    Q(community__id__in=comm_ids) | Q(is_global=True),
                    is_deleted=False).select_related(
                        'image', 'community').prefetch_related('tags')
                return events, None

            events = Event.objects.filter(
                Q(community__id=community_id) | Q(is_global=True),
                is_deleted=False).select_related(
                    'image', 'community').prefetch_related('tags')
            return events, None
        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)
Beispiel #6
0
    def list_testimonials_for_community_admin(
            self, context: Context,
            community_id) -> (list, MassEnergizeAPIError):
        try:
            if context.user_is_super_admin:
                return self.list_testimonials_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            if not community_id:
                user = UserProfile.objects.get(pk=context.user_id)
                admin_groups = user.communityadmingroup_set.all()
                comm_ids = [ag.community.id for ag in admin_groups]
                testimonials = Testimonial.objects.filter(
                    community__id__in=comm_ids,
                    is_deleted=False).select_related(
                        'image', 'community').prefetch_related('tags')
                return testimonials, None

            testimonials = Testimonial.objects.filter(
                community__id=community_id, is_deleted=False).select_related(
                    'image', 'community').prefetch_related('tags')
            return testimonials, None
        except Exception as e:
            print(e)
            return None, CustomMassenergizeError(e)
Beispiel #7
0
    def list_events_for_community_admin(
            self, context: Context, args) -> Tuple[list, MassEnergizeAPIError]:
        try:
            community_id = args.pop("community_id", None)

            if context.user_is_super_admin:
                return self.list_events_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            # community_id coming from admin portal is 'undefined'
            if not community_id or community_id == 'undefined':
                user = UserProfile.objects.get(pk=context.user_id)
                admin_groups = user.communityadmingroup_set.all()
                comm_ids = [ag.community.id for ag in admin_groups]
                # don't return the events that are rescheduled instances of recurring events - these should be edited by CAdmins in the recurring event's edit form,
                # not as their own separate events
                events = Event.objects.filter(
                    Q(community__id__in=comm_ids) | Q(is_global=True),
                    is_deleted=False).exclude(
                        name__contains=" (rescheduled)").select_related(
                            'image', 'community').prefetch_related('tags')

                return events, None

            events = Event.objects.filter(
                Q(community__id=community_id) | Q(is_global=True),
                is_deleted=False).select_related(
                    'image', 'community').prefetch_related('tags')
            return events, None
        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)
Beispiel #8
0
 def communities_download(self, context: Context) -> Tuple[list, MassEnergizeAPIError]:
   try:
     if not context.user_is_super_admin:
       return EMPTY_DOWNLOAD, NotAuthorizedError()
     return (self._all_communities_download(), None), None
   except Exception as e:
     capture_message(str(e), level="error")
     return EMPTY_DOWNLOAD, CustomMassenergizeError(e)
Beispiel #9
0
 def list_users_for_super_admin(self, context: Context):
     try:
         if not context.user_is_super_admin:
             return None, NotAuthorizedError()
         users = UserProfile.objects.filter(is_deleted=False)
         return users, None
     except Exception as e:
         capture_message(str(e), level="error")
         return None, CustomMassenergizeError(str(e))
Beispiel #10
0
 def list_testimonials_for_super_admin(self, context: Context):
   try:
     if not context.user_is_super_admin:
       return None, NotAuthorizedError()
     events = Testimonial.objects.filter(is_deleted=False).select_related('image', 'community', 'vendor').prefetch_related('tags')
     return events, None
   except Exception as e:
     capture_message(str(e), level="error")
     return None, CustomMassenergizeError(str(e))
Beispiel #11
0
 def list_events_for_super_admin(self, context: Context):
     try:
         if not context.user_is_super_admin:
             return None, NotAuthorizedError()
         events = Event.objects.filter(is_deleted=False).select_related(
             'image', 'community').prefetch_related('tags')
         return events, None
     except Exception as e:
         print(e)
         return None, CustomMassenergizeError(str(e))
Beispiel #12
0
    def list_teams_for_super_admin(self, context: Context):
        try:
            if not context.user_is_super_admin:
                return None, NotAuthorizedError()
            teams = Team.objects.filter(is_deleted=False).select_related(
                'logo', 'primary_community')
            return teams, None

        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(str(e))
Beispiel #13
0
 def _get_auth_token(self, request):
     try:
         authz = request.headers.get('Authorization', None)
         cleaned_path = request.path.split('/')[-1]
         if (authz is None) and (cleaned_path in self.restricted_paths):
             return None, NotAuthorizedError()
         elif authz:
             id_token = authz.split(' ')[-1]
             return id_token, None
         return None, None
     except Exception as e:
         return None, CustomMassenergizeError(e)
Beispiel #14
0
 def list_events_for_super_admin(self, context: Context):
     try:
         if not context.user_is_super_admin:
             return None, NotAuthorizedError()
         # don't return the events that are rescheduled instances of recurring events - these should be edited by CAdmins in the recurring event's edit form,
         # not as their own separate events
         events = Event.objects.filter(is_deleted=False).exclude(
             name__contains=" (rescheduled)").select_related(
                 'image', 'community').prefetch_related('tags')
         return events, None
     except Exception as e:
         capture_message(str(e), level="error")
         return None, CustomMassenergizeError(str(e))
Beispiel #15
0
 def teams_download(self, context: Context, community_id) -> Tuple[list, MassEnergizeAPIError]:
   self.community_id = community_id
   try:
     if context.user_is_community_admin or context.user_is_super_admin:
         community = Community.objects.get(id=community_id)
         if community:
           return (self._community_teams_download(community.id), community.name), None
         else:
           return EMPTY_DOWNLOAD, InvalidResourceError()
     else:
         return EMPTY_DOWNLOAD, NotAuthorizedError()
   except Exception as e:
     capture_message(str(e), level="error")
     return EMPTY_DOWNLOAD, CustomMassenergizeError(e)
Beispiel #16
0
    def members(self, context: Context, args) -> (Team, MassEnergizeAPIError):
        try:
            if not context.user_is_admin():
                return None, NotAuthorizedError()
            team_id = args.get('team_id', None)
            if not team_id:
                return [], CustomMassenergizeError(
                    'Please provide a valid team_id')

            members = TeamMember.objects.filter(is_deleted=False,
                                                team__id=team_id)
            return members, None
        except Exception:
            return None, InvalidResourceError()
Beispiel #17
0
    def delete_user(self, context: Context,
                    user_id) -> Tuple[dict, MassEnergizeAPIError]:
        try:
            if not user_id:
                return None, InvalidResourceError()

            # check to make sure the one deleting is an admin
            if not context.user_is_admin():

                # if they are not an admin make sure they can only delete themselves
                if context.user_id != user_id:
                    return None, NotAuthorizedError()

            users = UserProfile.objects.filter(id=user_id)
            users.update(is_deleted=True)
            return users.first(), None
        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)
Beispiel #18
0
 def actions_download(self, context: Context,
                      community_id) -> (list, MassEnergizeAPIError):
     try:
         if community_id:
             community_name = Community.objects.get(id=community_id).name
         if context.user_is_super_admin:
             if community_id:
                 return (self._community_actions_download(community_id),
                         community_name), None
             else:
                 return (self._all_actions_download(), None), None
         elif context.user_is_community_admin and community_id:
             return (self._community_actions_download(community_id),
                     community_name), None
         else:
             return None, NotAuthorizedError()
     except Exception as e:
         capture_message(str(e), level="error")
         return None, CustomMassenergizeError(e)
Beispiel #19
0
    def list_users_for_community_admin(
            self, context: Context,
            community_id) -> Tuple[list, MassEnergizeAPIError]:
        try:
            if context.user_is_super_admin:
                return self.list_users_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            community, err = get_community(community_id)

            if not community and context.user_id:
                communities, err = get_admin_communities(context)
                comm_ids = [c.id for c in communities]
                users = [
                    cm.user for cm in CommunityMember.objects.filter(
                        community_id__in=comm_ids, user__is_deleted=False)
                ]

                # now remove all duplicates
                users = remove_dups(users)

                return users, None
            elif not community:
                print(err)
                return [], None

            users = [
                cm.user for cm in CommunityMember.objects.filter(
                    community=community,
                    is_deleted=False,
                    user__is_deleted=False)
            ]
            users = remove_dups(users)
            return users, None
        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)
Beispiel #20
0
  def list_users_for_community_admin(self,  context: Context, community_id) -> (list, MassEnergizeAPIError):
    try:
      if context.user_is_super_admin:
        return self.list_users_for_super_admin(context)

      elif not context.user_is_community_admin:
        return None, NotAuthorizedError()

      community, err = get_community(community_id)

      if not community and context.user_id:
        communities, err =  get_admin_communities(context)
        comm_ids = [c.id for c in communities]      
        users = set(cm.user for cm in CommunityMember.objects.filter(community_id__in=comm_ids))
        return users, None
      elif not community:
        return [], None

      users = CommunityMember.objects.filter(community=community, is_deleted=False)
      return users, None
    except Exception as e:
      print(e)
      return None, CustomMassenergizeError(e)
Beispiel #21
0
    def list_vendors_for_community_admin(
            self, context: Context,
            community_id) -> (list, MassEnergizeAPIError):
        try:
            if context.user_is_super_admin:
                return self.list_vendors_for_super_admin(context)

            elif not context.user_is_community_admin:
                return None, NotAuthorizedError()

            if not community_id:
                user = UserProfile.objects.get(pk=context.user_id)
                communities, err = get_admin_communities(context)
                vendors = None
                for c in communities:
                    if vendors is not None:
                        vendors |= c.vendor_set.filter(
                            is_deleted=False).select_related(
                                'logo').prefetch_related(
                                    'communities', 'tags')
                    else:
                        vendors = c.vendor_set.filter(
                            is_deleted=False).select_related(
                                'logo').prefetch_related(
                                    'communities', 'tags')

                return vendors.distinct(), None

            community = get_community_or_die(context,
                                             {'community_id': community_id})
            vendors = community.vendor_set.filter(
                is_deleted=False).select_related('logo').prefetch_related(
                    'communities', 'tags')
            return vendors, None
        except Exception as e:
            print(e)
            return None, CustomMassenergizeError(e)
Beispiel #22
0
    def list_graphs_for_super_admin(self, context: Context):
        try:
            if not context.user_is_super_admin:
                return None, NotAuthorizedError()

            graphs = []
            for community in Community.objects.filter(is_deleted=False)[:4]:
                g, err = self.graph_actions_completed(
                    context, {"community_id": community.id})
                if g:
                    graphs.append({community.name: g["data"]})

            comm_impact = []
            for c in Community.objects.filter(is_deleted=False)[:4]:
                comm_impact.append(get_households_engaged(c))
            comm_impact.append(get_all_households_engaged())
            return {
                "actions_completed": graphs,
                "communities_impact": comm_impact
            }, None

        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(str(e))
Beispiel #23
0
    def update_team(self, context, args) -> Tuple[dict, MassEnergizeAPIError]:
        try:
            team_id = args.get('id', None)
            community_id = args.pop('community_id', None)
            if community_id:
                community = Community.objects.filter(pk=community_id).first()
                subdomain = community.subdomain
            else:
                subdomain = "your_community"

            community_ids = args.pop(
                'communities',
                None)  # in case of a team spanning multiple communities

            logo = args.pop('logo', None)
            parent_id = args.pop('parent_id', None)
            is_published = args.pop('is_published', False)

            team = Team.objects.filter(id=team_id)

            # to update Team, need to be super_admin, community_admin of that community, or a team_admin
            allowed = False
            if context.user_is_super_admin:
                allowed = True
            elif context.user_is_community_admin:
                community = team.first().primary_community
                admin_communities, err = get_admin_communities(context)
                if community in admin_communities:
                    allowed = True
            else:
                # user has to be on the team admin list
                teamMembers = TeamMember.objects.filter(team=team.first())
                for teamMember in teamMembers:
                    teamMember_id = str(teamMember.user.id)
                    if teamMember_id == context.user_id and teamMember.is_admin:
                        allowed = True
                        break

            if not allowed:
                return None, NotAuthorizedError()

            team.update(**args)
            team = team.first()

            # TODO: create a rich email template for this?
            # TODO: only allow a cadmin or super admin to change this particular field?
            if is_published and not team.is_published:
                team.is_published = True
                team_admins = TeamMember.objects.filter(
                    team=team, is_admin=True).select_related('user')
                # fix the broken URL in this message, needs to have community nam
                message = "Your team %s has now been approved by a Community Admin and is viewable to anyone on the MassEnergize portal. See it here:\n\n%s" % (
                    team.name, ("%s/%s/teams/%i") %
                    (COMMUNITY_URL_ROOT, subdomain, team.id))
                for team_admin in team_admins:
                    send_massenergize_email(
                        subject="Your team has been approved",
                        msg=message,
                        to=team_admin.user.email)
            else:
                # this is how teams can get be made not live
                team.is_published = is_published

            if community_id:
                community = Community.objects.filter(pk=community_id).first()
                if community and team.primary_community != community:
                    team.primary_community = community

            if community_ids:
                for community_id in community_ids:
                    community = Community.objects.filter(
                        pk=community_id).first()
                    team.communities.add(community)

            if parent_id:
                team.parent = None
                parent = Team.objects.filter(pk=parent_id).first()
                if parent and can_set_parent(parent, this_team=team):
                    team.parent = parent

            else:
                if parent_id == 0:
                    team.parent = None

            if logo:
                # if existing logo, the string length is around 300 characters
                # If a new logo updated, this will be the length of the file, much larger than that
                new_logo = len(logo) > 1000
                if new_logo:
                    logo = Media.objects.create(
                        file=logo, name=f"{slugify(team.name)}-TeamLogo")
                    logo.save()
                    team.logo = logo
                else:
                    team.logo = None

            team.save()
            return team, None
        except Exception as e:
            capture_message(str(e), level="error")
            return None, CustomMassenergizeError(e)