def resolve_getTransactionDetail(self, info, **kwargs):
        transactionID = kwargs.get('transactionID')
        user = info.context.user
        try:
            tobj = Transaction.objects.get(transactionID=transactionID)

            # a superuser can always see the transaction
            if user.is_superuser:
                return tobj

            # an user can view details of his own transaction
            if user == tobj.user:
                return tobj

            # check user's access based on UserAccess Model
            try:
                access = UserAccess.objects.get(user=user)
                if access.canAcceptPayment or access.viewAllTransactions:

                    # TODO: CRITICAL! if its not viewed at counter, but elsewhere, it shouldn't modify the transaction
                    # Modify transaction if it was viewed at the counter
                    if tobj.isPaid is False:  # no modification required if already paid
                        tobj.issuer = user
                        tobj.isPending = True
                        tobj.isProcessed = False
                        tobj.save()

                    return tobj
                else:
                    raise APIException("Access level set for you is not enough to perform this query.")
            except UserAccess.DoesNotExist:
                raise APIException("You are not permitted to view the details of this transactions.")
        except Transaction.DoesNotExist:
            raise APIException("Transaction not found in the database.")
Beispiel #2
0
 def resolve_getTeam(self, info, **kwargs):
     user = info.context.user
     try:
         team = Team.objects.get(hash=kwargs.get('hash'))
         if user in team.members.all():
             mlist = []
             for member in team.members.order_by('first_name').all():
                 mlist.append({
                     "name": member.first_name + ' ' + member.last_name,
                     "username": member.username
                 })
             isEditable = False
             if EventRegistration.objects.filter(team=team).count() == 0 | team.allowEditing:
                 isEditable = True
             documentURL = None
             if team.document and hasattr(team.document, 'url'):
                 documentURL = info.context.build_absolute_uri(team.document.url)
             return TeamObj(
                 name=team.name,
                 leader={
                     "name": team.leader.first_name + ' ' + team.leader.last_name,
                     "username": team.leader.username
                 },
                 members=mlist,
                 membersCount=len(mlist),
                 hash=team.hash,
                 isUserLeader=user == team.leader,
                 isEditable=isEditable,
                 document=documentURL
             )
         else:
             raise APIException("You should be a member of the team to retrieve details of the team.")
     except Team.DoesNotExist:
         raise APIException("The team queried does not exist or have been deleted.")
 def resolve_getTransactionList(self, info, **kwargs):
     user = info.context.user
     transactions = Transaction.objects.values().all().order_by('-timestamp')
     if user.is_superuser:
         return transactions
     try:
         if UserAccess.objects.get(user=user).viewAllTransactions:
             return transactions
         else:
             raise APIException(
                 "Access denied: You dont have the access enabled to view details of all transactions."
             )
     except UserAccess.DoesNotExist:
         raise APIException("Access denied: You are not allowed view all transactions.")
Beispiel #4
0
    def mutate(self, info, teamHash):
        user = info.context.user
        obj = Team.objects.get(hash=teamHash)
        if obj.leader == user:

            # checks if team has already registered for some events
            rCount = EventRegistration.objects.filter(team=obj).count()
            if rCount > 0:
                raise APIException('You cannot delete a team after it has registered for an event.')

            obj.delete()
            return TeamUpdateStatusObj(status=True)
        else:
            raise APIException('You should be the leader of the team to delete the team')
Beispiel #5
0
    def mutate(self, info, teamHash):
        user = info.context.user
        try:
            obj = Team.objects.get(hash=teamHash)

            # checks if team has already registered for some events
            rCount = EventRegistration.objects.filter(team=obj).count()
            if rCount > 0 and obj.allowEditing is False:
                raise APIException('You cannot join a team after it has registered for an event.')

            obj.members.add(user)
            obj.save()
            return CreateTeamObj(hash=obj.hash)
        except Team.DoesNotExist:
            raise APIException('Team does not exist or have been deleted')
Beispiel #6
0
 def mutate(self, info, teamHash):
     user = info.context.user
     try:
         access = UserAccess.objects.get(user=user)
         obj = Team.objects.get(hash=teamHash)
         if (obj.id in access.productsManaged.all() or access.productsManaged.count() == 0) and access.canViewRegistrations:
             if obj.allowEditing is False:
                 obj.allowEditing = True
             else:
                 obj.allowEditing = False
             obj.save()
             return TeamUpdateStatusObj(status=True)
         else:
             raise APIException('Permission denied to do this action.')
     except UserAccess.DoesNotExist:
         raise APIException('You dont have access to perform this action')
 def resolve_fixUnassociatedPayments(self, info, **kwargs):
     user = info.context.user  # get request user
     if user.is_superuser:  # only super user is allowed to perform this action
         # find successful transactions that do not have a order associated
         trans = Transaction.objects.filter(
             isPaid=True,
             order__isnull=True
         )
         log = []  # for logging
         # for each of those transactions
         for t in trans:
             # try to find a matching order
             orders = Order.objects.filter(
                 # order should be the same user, of course!
                 user=t.user,
                 # trans associated should have same value in order to be replaced
                 transaction__amount=t.amount,
                 # existing associated trans should have failed in order to be replaced with the curr
                 transaction__isPaid=False,
             )
             # if a single fixable match is found
             if orders.count() == 1:
                 order = orders.first()
                 log.append({
                     "email": t.user.email,
                     "amount": t.amount,
                     "oldTransaction": order.transaction,
                     "newTransaction": t
                 })
                 # replace the failed transaction with the successful
                 order.transaction = t
                 order.save()  # save changes
             # TODO how to handle if multiple failed orders exist with same amount?
         return log
     raise APIException('You should be a super user to perform this action')
Beispiel #8
0
    def resolve_listRegistrations(self, info, **kwargs):
        user = info.context.user
        access = UserAccess.objects.get(user=user)
        if access.adminAccess and access.canViewRegistrations:
            events = EventRegistration.objects.filter(
                Q(order__transaction__isPaid=True)
                | Q(event__competition__hasSelectionProcess=True)
                | Q(event__requireAdvancePayment=False)).values_list(
                    'event__productID', flat=True)

            if access.productsManaged.count() > 0:
                events = events.filter(event__in=access.productsManaged.all())

            products = Product.objects.filter(requireRegistration=True,
                                              productID__in=events)

            eventType = kwargs.get('eventType')
            if eventType is not None:
                if eventType == 'competition':
                    return products.filter(competition__isnull=False)
                elif eventType == 'workshop':
                    return products.filter(workshop__isnull=False)
                elif eventType == 'ticket':  #unused case
                    return products.filter(ticket__isnull=False)
                return products

            eventID = kwargs.get('eventType')
            if eventID is not None:
                return products.filter(id=eventID)
            return products
        else:
            raise APIException('Permission Denied')
 def resolve_getProfile(self, info, **kwargs):
     user = info.context.user
     if UserAccess.objects.get(user=user).canViewProfiles:
         key = kwargs.get('key')
         if key is not None:
             try:
                 if is_valid_uuid(key):
                     return Profile.objects.get(vidyutHash=key)
                 return Profile.objects.get(
                     Q(vidyutID=key) | Q(user__username=key) | Q(user__email=key)
                 )
             except Profile.DoesNotExist:
                 raise APIException(
                     'Profile does not exist. Please enter a valid VidyutID / VidyutHash / Username / Email'
                 )
     raise APIException('You do not have the permission to view profiles of users')
Beispiel #10
0
 def resolve_getTransactionStats(self, info, **kwargs):
     user = info.context.user
     if UserAccess.objects.get(
             user=user).viewAllTransactions or user.is_superuser:
         return True
     else:
         raise APIException('Permission Denied.')
Beispiel #11
0
 def resolve_userProfile(self, info):
     if self.user is not None:
         try:
             return Profile.objects.get(user=self.user)
         except Profile.DoesNotExist:
             raise APIException("Profile Does not exist")
     return None
Beispiel #12
0
    def resolve_getOnlinePaymentStatus(self, info, **kwargs):
        transactionID = kwargs.get('transactionID')
        try:
            tobj = Transaction.objects.get(transactionID=transactionID)
        except Transaction.DoesNotExist:
            raise APIException("Transaction not found in the database.")

        payload = getTransactionPayload(tobj.amount, transactionID)
        try:
            f = requests.post(ACRD_ENDPOINT + '/doubleverifythirdparty',
                              data=payload)
            k = f.json()
        # TODO : Do better error handling
        except Exception as e:
            return PaymentStatusObj(status=False, data='Failed')

        # Decrypt Response Data from ACRD, receives a JSON
        data = decryptPayload(k["data"])

        if k["response"]:
            jsonData = json.loads(data)
            tobj.isPaid = jsonData['status'] == "SUCCESS"
            tobj.isProcessed = True
            tobj.manualIssue = False
            tobj.transactionData = data
            tobj.save()
        return PaymentStatusObj(status=k["response"], data=data)
Beispiel #13
0
 def resolve_viewTicketSaleCount(self, info, **kwargs):
     user = info.context.user
     if UserAccess.objects.get(
             user=user).canViewRegistrations or user.is_superuser:
         tickets = Ticket.objects.all()
         return Product.objects.filter(ticket__in=tickets)
     else:
         raise APIException('Permission Denied.')
Beispiel #14
0
    def mutate(self, info, teamHash):
        user = info.context.user
        obj = Team.objects.get(hash=teamHash)

        # checks if team has already registered for some events
        rCount = EventRegistration.objects.filter(team=obj).count()
        if rCount > 0 and obj.allowEditing is False:
            raise APIException('You cannot edit a team after it has registered for an event.')
        if obj.leader == user:
            if "document" in info.context.FILES:
                document = info.context.FILES['document']
                if document is not None:
                    obj.document = document
        else:
            raise APIException('You need to be the leader of the team to upload document.')

        obj.save()

        return TeamUpdateStatusObj(status=True)
Beispiel #15
0
 def resolve_getPaymentGatewayData(self, info, **kwargs):
     transactionID = kwargs.get('transactionID')
     try:
         tobj = Transaction.objects.get(transactionID=transactionID)
     except Transaction.DoesNotExist:
         raise APIException("Transaction not found in the database.")
     payload = getTransactionPayload(tobj.amount, transactionID)
     return PaymentLinkObj(data=payload['encdata'],
                           code=payload['code'],
                           url=ACRD_ENDPOINT + '/makethirdpartypayment')
Beispiel #16
0
    def mutate(self, info, teamHash, details):
        user = info.context.user
        obj = Team.objects.get(hash=teamHash)

        # checks if team has already registered for some events
        rCount = EventRegistration.objects.filter(team=obj).count()
        if rCount > 0 and obj.allowEditing is False:
            raise APIException('You cannot edit a team after it has registered for an event.')

        # name change requested
        if details.name is not None:
            if obj.leader == user:
                obj.name = details.name
            else:
                raise APIException('You need to be the leader of the team to change its name')

        # leader change requested
        if details.leader is not None:
            if obj.leader == user:
                obj.leader = User.objects.get(username=details.leader)
            else:
                raise APIException('You need to be the current leader of the team to change its leader')

        # Removing members requested
        if details.removeMembers is not None:
            for member in details.removeMembers:
                delusr = User.objects.get(username=member)
                if obj.leader == user:
                    if delusr != user:
                        obj.members.remove(delusr)
                    else:
                        raise APIException('You cannot remove yourself from a team, in which you are the leader')
                else:
                    if delusr == user:
                        obj.members.remove(delusr)
                    else:
                        raise APIException(
                            'You cannot remove other members from your team, unless you are the leader'
                        )

            obj.save()  # saves changes
            return TeamUpdateStatusObj(status=True)
Beispiel #17
0
    def mutate(self, info, details=None):
        user = info.context.user
        profile = Profile.objects.get(user=user)
        physicalTicket = PhysicalTicket.objects.filter(user=info.context.user)
        if info.context.FILES is not None and physicalTicket.count() == 0:
            if "profilePhoto" in info.context.FILES:
                profilePhoto = info.context.FILES['profilePhoto']
                if profilePhoto is not None:
                    profile.photo = profilePhoto
            if "profileCollegeID" in info.context.FILES:
                profileCollegeID = info.context.FILES['profileCollegeID']
                if profileCollegeID is not None:
                    profile.idPhoto = profileCollegeID
        if details is not None:
            if details.firstName is not None:
                user.first_name = details.firstName
                user.save()
            if details.lastName is not None:
                user.last_name = details.lastName
                user.save()
            if details.rollNo is not None:
                profile.rollNo = details.rollNo
            if details.phone is not None:
                profile.phone = details.phone
            if details.location is not None:
                profile.location = details.location
            if details.gender is not None:
                profile.gender = details.gender
            if details.emergencyPhone is not None:
                profile.emergencyPhone = details.emergencyPhone
            if details.emergencyContactName is not None:
                profile.emergencyContactName = details.emergencyContactName
            if details.foodPreference is not None:
                profile.foodPreference = details.foodPreference
            if details.shirtSize is not None and physicalTicket.count() == 0:
                profile.shirtSize = details.shirtSize
            if details.degreeType is not None:
                profile.degreeType = details.degreeType
            if details.graduationYear is not None:
                profile.admissionYear = int(details.graduationYear)
            if details.isFaculty is not None:
                profile.isFaculty = details.isFaculty
            if details.isSchoolStudent is not None:
                profile.isSchoolStudent = details.isSchoolStudent
            if details.collegeID is not None:
                try:
                    college = College.objects.get(id=details.collegeID)
                    profile.college = college
                except College.DoesNotExist:
                    raise APIException(
                        'College does not exist or has been removed.')
        profile.save()

        return UpdateProfileObj(status=True)
Beispiel #18
0
 def resolve_registrationCount(self, info, **kwargs):
     user = info.context.user
     access = UserAccess.objects.get(user=user)
     if access.adminAccess and access.canViewRegistrations:
         if access.productsManaged.count() > 0:
             return EventRegistration.objects.filter(
                 event__in=access.productsManaged.all())
         else:
             return EventRegistration.objects.all()
     else:
         raise APIException('Forbidden')
 def resolve_getTransactionsApproved(self, info, **kwargs):
     vid = kwargs.get('vid')
     user = info.context.user
     if vid is None:
         try:
             if UserAccess.objects.get(user=user).canAcceptPayment:
                 return Transaction.objects.filter(issuer=user, isPaid=True)
             else:
                 raise APIException(
                     "This API is for volunteer's who can collect payment. You don't have permission to view this."
                 )
         except UserAccess.DoesNotExist:
             raise APIException("You don't have access to view this.")
     else:
         try:
             if UserAccess.objects.get(user=user).viewAllTransactions:
                 return Transaction.objects.filter(issuer=Profile.objects.get(vidyutID=vid).user, isPaid=True)
             else:
                 raise APIException(
                     "You don't have permission to view this."
                 )
         except UserAccess.DoesNotExist:
             raise APIException("You don't have access to view this")
Beispiel #20
0
 def resolve_registrationAmount(self, info, **kwargs):
     user = info.context.user
     access = UserAccess.objects.get(user=user)
     if access.adminAccess and access.canViewRegistrations:
         if access.productsManaged.count() > 0:
             return EventRegistration.objects.filter(
                 event__in=access.productsManaged.all(),
                 order__transaction__isPaid=True).values_list('order',
                                                              flat=True)
         else:
             return EventRegistration.objects.filter(
                 order__transaction__isPaid=True).values_list('order',
                                                              flat=True)
     else:
         raise APIException('Forbidden')
    def resolve_getTransactionStatus(self, info, **kwargs):
        user = info.context.user
        transactionID = kwargs.get('transactionID')
        try:
            tobj = Transaction.objects.get(transactionID=transactionID)

            # a superuser can always see transaction status of any transaction
            if user.is_superuser:
                return tobj

            # an user can always view the status of his own transaction
            if tobj.user == user:
                return tobj

            try:
                access = UserAccess.objects.get(user=user)
                if access.canAcceptPayment or access.viewAllTransactions:
                    return tobj
                else:
                    raise APIException("You dont have the access enabled to view the status of this transaction.")
            except UserAccess.DoesNotExist:
                raise APIException("You are not allowed to view the status of this transaction.")
        except Transaction.DoesNotExist:
            raise APIException("Transaction with the given transactionID does not exist")
 def resolve_issuer(self, info):
     if self.issuer is not None:
         try:
             profile = Profile.objects.get(user=self.issuer)
             photo = None
             # TODO doesnt seem to work
             if profile.photo and hasattr(profile.photo, "url"):
                 photo = info.context.build_absolute_uri(profile.photo.url)
             return IssuerObj(firstName=self.issuer.first_name,
                              lastName=self.issuer.last_name,
                              location=self.issuerLocation,
                              device=self.issuerDevice,
                              vidyutID=profile.vidyutID,
                              photo=photo)
         except Profile.DoesNotExist:
             raise APIException(
                 'Issuer does not exist or has been deleted from db.')
     return None
 def resolve_listExcessPayments(self, info, **kwargs):
     user = info.context.user
     if user.is_superuser:
         users = Transaction.objects.filter(
             isPaid=True,
             order__isnull=True
         ).values_list('user', flat=True).distinct()
         list = []
         for u in users:
             trans = Transaction.objects.filter(isPaid=True, user_id=u)
             if trans.values('amount').distinct().count() == 1:
                 data = {
                     "email": trans.first().user.email,
                     "amount": trans.first().amount,
                     "transactions": trans
                 }
                 list.append(data)
         return list
     else:
         raise APIException('You need to be a super-admin to do this.')
Beispiel #24
0
 def resolve_checkForTicket(self, info, **kwargs):
     profile = Profile.objects.get(vidyutHash=kwargs.get('hash'))
     if UserAccess.objects.get(user=info.context.user).canIssueTickets:
         order = Order.objects.filter(user=profile.user,
                                      transaction__isPaid=True,
                                      products__name__contains='Revel')
         status = False
         product = None
         photo = None
         isProfileComplete = True
         isHeadbanger = False
         if order.count() > 0:
             product = order.first().products.all().first()
             if "Headbangers" in product.name:
                 isHeadbanger = True
             if PhysicalTicket.objects.filter(
                     user=profile.user).count() == 0:
                 status = True
                 message = 'Eligible for ticket - ' + product.name
                 profilemsg = 'Profile Incomplete - '
                 if not profile.photo or not hasattr(profile.photo, 'url'):
                     isProfileComplete = False
                     profilemsg += ' Selfie, '
                 if profile.gender is None or len(profile.gender) < 1:
                     isProfileComplete = False
                     profilemsg += ' Gender, '
                 if profile.phone is None or len(profile.phone) < 10:
                     isProfileComplete = False
                     profilemsg += ' Phone No., '
                 if profile.college is None:
                     isProfileComplete = False
                     profilemsg += ' College Name, '
                 if profile.shirtSize is None or len(profile.shirtSize) < 1:
                     isProfileComplete = False
                     profilemsg += ' T-Shirt Size, '
                 profilemsg += ' to be updated'
                 if isProfileComplete is False:
                     status = False
                     message = profilemsg
             else:
                 message = 'Ticket already given.'
         else:
             message = 'No ticket exists for the user'
         ticket = PhysicalTicket.objects.filter(user=profile.user)
         ticketNo = 'No Physical Ticket'
         if ticket.count() == 1:
             ticketNo = ticket.first().number
         if profile.photo and hasattr(profile.photo, 'url'):
             photo = info.context.build_absolute_uri(profile.photo.url)
         return ValidateTicketObj(status=status,
                                  message=message,
                                  ticketNo=ticketNo,
                                  isHeadBanger=isHeadbanger,
                                  userName=profile.user.first_name + ' ' +
                                  profile.user.last_name,
                                  productName=product,
                                  rollNo=profile.rollNo,
                                  tShirtSize=profile.shirtSize,
                                  photo=photo,
                                  isProfileComplete=isProfileComplete)
     raise APIException('Permission denied.')
Beispiel #25
0
 def resolve_leader(self, info):
     if self.leader is not None:
         try:
             return Profile.objects.get(user=self.leader)
         except Profile.DoesNotExist:
             return APIException('Leader profile does not exist in db')