예제 #1
0
def apply_common(request, app):
    if request.method == "POST":
        count = 1
        answers = []
        for q in appmodule.questions:
            answer = Answer(app=app,
                            question=q["text"],
                            text=request.POST.get("q" + unicode(count)))
            answers.append(answer)
            count += 1
        app.status = 1
        app.timezone = request.POST.get('tz')
        app.applicantProfile = request.user.userprofile
        app.applicationDate = datetime.utcnow()
        app.save()
        recruiter = Group.objects.filter(name="Recruiter").first()
        note = Notification(cssClass="success")
        note.content = "New Application from <a href='" + reverse(
            'applications:viewapp', kwargs={
                "app": app.token
            }) + "'>" + unicode(request.user.userprofile) + "</a>."
        note.save()
        note.targetGroup.add(recruiter)

        Answer.objects.bulk_create(answers)

        return redirect("applications:mystatus")

    else:
        return render(request, "apply.html",
                      {"questions": appmodule.questions})
예제 #2
0
def send2FASMS(request):
    email = request.data.get('email')
    if email:
        email = email.lower()
    success = False
    try:
        user = get_object_or_404(User, email__iexact=email)
        profile = get_object_or_404(Profile, user=user)
        wallet = Wallet.objects.get(profile=profile)
        TransactionManager.createVerify2FASMSTransaction(
            settings.TWO_FACTOR_SMS_COST, wallet.id)
        profile.setVerificationCode()
        profile.save()
        messageSend = sendVerificationCodeSMS(request,
                                              profile.verificationCode,
                                              profile.mobile)
        success = messageSend
    except ValueError:
        profile.enable2FASMS = False
        notification = Notification()
        notification.alert = True
        notification.user = profile.user
        alertText = "Two factor authentication has been disabled due to low credit"
        notification.alertData = alertText
        notification.save()
        profile.save()
    except Exception as e:
        return Response({
            'success': False,
            'error': {
                'code': 'no.sms.sent',
                'msg': e.message
            }
        })
    return Response({'success': success})
예제 #3
0
def reply_to_notification(request):

    if request.method == 'POST':
        try:
            old_notification = Notification.objects.filter(
                pk=request.POST.get('notification_pk'))[0]
            sender = request.user
            if old_notification.sender == sender:
                receiver = old_notification.receiver
            else:
                receiver = old_notification.sender
            response_data = {}

            message = request.POST.get('message')
            notification = Notification()
            notification.sender = sender
            notification.receiver = receiver
            notification.notification_type = "CLAIM"
            notification.message = message
            notification.topic = old_notification.topic
            notification.save()
            response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
예제 #4
0
def cancel(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), profile=profile)
        order.state = ORDER_STATUS['cancelled']
        order.save()
        orderSerializer = OrderProtectedSerializer(order, context={'request': request})

        # Notification to forwarder
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.service.profile.user
        orderLink = "%sorders/forwarder/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order %s" % (order.state),
            "notifications/email/forwarder_order_change_status.html",
            {
                'order': order,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d changed status to %s" % (order.id, order.state)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/forwarder/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
예제 #5
0
def addOrderForwarderFeedbackToBuyer(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=int(request.data.get('orderId')), service__profile=profile)
        orderFeedback = getOrderFeedback(order, profile)
        orderFeedback.score = request.data.get('score')
        orderFeedback.text = request.data.get('text')
        orderFeedback.save()
        buyerProfile = order.profile
        buyerProfile.feedback = FeedbackManager.updateBuyerProfileFeedback(buyerProfile)
        buyerProfile.save()

        feedbackNotification = Notification()
        feedbackNotification.alert = True
        feedbackNotification.user = buyerProfile.user
        orderLink = "%sbuyer" % (
            feedbackNotification.getEmailLinkBaseUrl()
        )
        alertText = "User %s left a feedback %.2f/5" % (profile.user.username, orderFeedback.score)
        feedbackNotification.alertData = "%s|%s" % (alertText, "/buyer")
        feedbackNotification.save()

        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})
        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
예제 #6
0
def postNotification(target, text, cssClass="info"):
    n = Notification(content=text, cssClass=cssClass)
    n.save()

    if type(target) is User:
        n.targetUsers.add(target)
    elif type(target) is Group:
        n.targetGroup.add(target)
예제 #7
0
파일: views.py 프로젝트: mertyildiran/echo
 def patch(self, request, pk, format=None):
     user = self.get_object(pk)
     user.profile.hearts += 1
     user.save()
     notification = Notification(sender=Token.objects.get(
         key=self.request.META['HTTP_AUTHORIZATION'].split(' ', 1)[1]).user,
                                 receiver=user)
     notification.save()
     return Response(status=status.HTTP_200_OK)
예제 #8
0
def notify(request):

    if request.method == 'POST':
        try:
            item = Item.objects.filter(pk=request.POST.get('item_id'))[0]
            sender = request.user
            receiver = item.found_by_user
            response_data = {}

            method = request.POST.get('method')
            message = request.POST.get('message')

            if (method == 'IBF'):
                notification = Notification()
                notification.sender = sender
                notification.receiver = receiver
                notification.message = message
                notification.topic = item
                notification.notification_type = 'CLAIM'
                notification.save()
                item.status = 'CLAIMED'
                item.lost_by_user = sender
                item.save()
                response_data['result'] = 'OK'

            elif (method == 'email'):
                email_subject = 'IBF: Claimed Item'
                email_body = "Hey %s, someone is claiming one of the items you found. Here's his email address so you can get in touchL %s" % (
                    receiver.username, sender.email)

                send_mail(email_subject,
                          email_body,
                          '*****@*****.**', [receiver.email],
                          fail_silently=False)
                item.status = 'CLAIMED'
                item.lost_by_user = sender
                item.save()
                response_data['result'] = 'OK'

            elif (method == 'phone'):
                item.status = 'CLAIMED'
                item.lost_by_user = sender
                item.save()
                response_data['result'] = 'OK'
            if (method == 'leave_message'):
                notification = Notification()
                notification.sender = sender
                notification.receiver = receiver
                notification.message = message
                notification.topic = item
                notification.notification_type = 'CLAIM'
                notification.save()
                response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
예제 #9
0
def updateForwarderTrackingInfo(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), service__profile=profile)
        try:
            orderTrackingInfo = OrderTrackingInfo.objects.get(
                order=order,
                profile=profile,
                fromForwarder=True,
                trackingStatus=settings.ORDER_TRACKING_INFO_STATUS_CHOICES[1][0]
            )
            orderTrackingInfo.courier = request.data.get('courier')
            orderTrackingInfo.courierOther = request.data.get('courierOther')
            orderTrackingInfo.trn = request.data.get('trn')
            orderTrackingInfo.link = request.data.get('link')
        except OrderTrackingInfo.DoesNotExist:
            orderTrackingInfo = OrderTrackingInfo(
                order=order,
                profile=profile,
                fromForwarder=True,
                courier=request.data.get('courier'),
                courierOther=request.data.get('courierOther'),
                trn=request.data.get('trn'),
                link=request.data.get('link'),
                trackingStatus=settings.ORDER_TRACKING_INFO_STATUS_CHOICES[1][0]
            )
        orderTrackingInfo.save()
        order.save()
        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})

        # Notification to buyer
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.profile.user
        orderLink = "%sorders/buyer/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order Tracking Info Updated",
            "notifications/email/buyer_order_tracking_changed.html",
            {
                'order': order,
                'orderTrackingInfo': orderTrackingInfo,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d tracking info updated" % (order.id)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
예제 #10
0
def notify(request):

  if request.method=='POST':
    try:
      item = Item.objects.filter(pk=request.POST.get('item_id'))[0]
      sender = request.user
      receiver = item.found_by_user
      response_data = {}

      method =  request.POST.get('method')
      message = request.POST.get('message')

      if (method == 'IBF'):
        notification = Notification()
        notification.sender = sender
        notification.receiver = receiver
        notification.message = message
        notification.topic = item
        notification.notification_type = 'CLAIM'
        notification.save()
        item.status = 'CLAIMED'
        item.lost_by_user = sender
        item.save()
        response_data['result'] = 'OK'

      elif (method == 'email'):
        email_subject = 'IBF: Claimed Item'
        email_body = "Hey %s, someone is claiming one of the items you found. Here's his email address so you can get in touchL %s" % (receiver.username, sender.email)

        send_mail(email_subject, email_body, '*****@*****.**',
              [receiver.email], fail_silently=False)
        item.status = 'CLAIMED'
        item.lost_by_user = sender
        item.save()
        response_data['result'] = 'OK'

      elif (method == 'phone'):
        item.status = 'CLAIMED'
        item.lost_by_user = sender
        item.save()
        response_data['result'] = 'OK'
      if (method == 'leave_message'):
        notification = Notification()
        notification.sender = sender
        notification.receiver = receiver
        notification.message = message
        notification.topic = item
        notification.notification_type = 'CLAIM'
        notification.save()
        response_data['result'] = 'OK'
    except Exception, e:
      traceback.print_exc()
      response_data['result'] = 'ERROR'
예제 #11
0
def submit(request):
    if not isDropbears(request.user):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a member.'
        })
    c = {}
    if request.method == "POST":
        error = False
        new = SRPRequest()
        new.owner = request.user.userprofile

        link = request.POST.get('link', False)
        if link:
            new.killID = link.split("/")[-2]
            if SRPRequest.objects.filter(killID=new.killID).exists():
                error = True
                return render(request, "submit.html", c)
            shipID, shipName, pilot, corp, value = getKillInformation(
                new.killID)
        if not link or not shipID:
            error = True
        else:
            new.value = int(float(value))
            new.shipID = shipID
            new.fc = request.POST.get('fc', '')
            new.aar = request.POST.get('aar', '')
            new.learned = request.POST.get('learned', '')
            new.suggestions = request.POST.get('suggestions', '')
            new.pilot = pilot
            new.corp = corp
            new.ship = shipName
            new.save()
            c["message"] = "Successfully added kill #" + new.killID
            finance = Group.objects.filter(name="Finance").first()
            note = Notification(cssClass="info")
            note.content = "New <a href='" + reverse(
                'srp:viewsrp', kwargs={"killID": new.killID}
            ) + "'>SRP request for a " + shipName + "</a> added by <a href='" + reverse(
                'core:playerProfile',
                kwargs={"profileName": slugify(request.user.userprofile)
                        }) + "'>" + unicode(request.user.userprofile) + "</a>."
            note.save()
            note.targetGroup.add(finance)

        c["error"] = error

    return render(request, "submit.html", c)
예제 #12
0
def ticketSubmit(request):
    if not isDropbears(request.user):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a member.'
        })
    c = {}
    if request.method == "POST":
        error = False
        new = Ticket()
        anonymous = request.POST.get("anonymous") == "on"
        new.author = None if anonymous else request.user.userprofile

        new.title = request.POST.get('title', '')
        new.text = request.POST.get('text', '')
        new.category = int(request.POST.get('category', 0))
        sample = string.lowercase + string.digits
        new.token = ''.join(random.sample(sample, 8))
        new.save()
        c["message"] = "Successfully added <a href='" + reverse(
            'helpdesk:viewticket', kwargs={"token": new.token}
        ) + "'>Ticket #" + str(
            new.id
        ) + " \"" + new.title + "\"</a>. If you chose to submit anonymously, save this link as it's your only way to access it."

        director = Group.objects.filter(name="Director").first()
        note = Notification(cssClass="info")
        if anonymous:
            note.content = "Someone added a new Ticket: <a href='" + reverse(
                'helpdesk:viewticket',
                kwargs={"token": new.token}) + "'>\"" + new.title + "\"</a>"
        else:
            note.content = "<a href='" + reverse(
                'core:playerProfile',
                kwargs={"profileName": slugify(request.user.userprofile)}
            ) + "'>" + unicode(
                new.author) + "</a> added a new Ticket: <a href='" + reverse(
                    'helpdesk:viewticket', kwargs={
                        "token": new.token
                    }) + "'>\"" + new.title + "\"</a>"
        note.save()
        note.targetGroup.add(director)

        c["error"] = error

    c["users"] = Group.objects.filter(name="Director").first().user_set.all()

    return render(request, "ticketsubmit.html", c)
예제 #13
0
def notifications_job(request):
    data = None
    log = ''
    try:
        match_search = ItemsMatchView()
        pre_reg_items = PreRegisteredItem.objects.filter(lost=True)

        log += "<p>=========================</p>"
        log += "<p>======= START JOB =======</p>"

        for item in pre_reg_items:
            log += "<p>== Searching matches for item:</p>"
            log += "<p>______Title: " + item.title + "</p>"
            log += "<p>______Category: " + item.category + "</p>"
            log += "<p>______Created on: " + str(item.created_at) + "</p>"
            t = request.GET.copy()
            t.update({'q': string.replace(item.tags, ' ', '+')})
            t.update({'category': item.category})
            t.update({'unique_id': item.unique_id})
            t.update({'start_date': str(item.created_at).split(' ')[0]})
            request.GET = t
            match_results = match_search.get(request)
            for match in match_results:
                if not Notification.objects.filter(notification_type="MATCH",
                                                   match=item,
                                                   topic=match.object):
                    log += "<p>== Creating notification for match:</p>"
                    log += "<p>______Title: " + match.object.title + "</p>"
                    log += "<p>______Category: " + match.object.category + "</p>"
                    log += "<p>______Created on: " + str(
                        match.object.date_field) + "</p>"

                    notification = Notification()
                    notification.receiver = item.owner
                    notification.notification_type = "MATCH"
                    notification.message = "This item matched your lost "
                    notification.topic = match.object
                    notification.match = item
                    notification.save()

                    log += "<p>== Notification Created</p>"
                    log += "<p>=======================</p>"
        log += "<p><p>========= END JOB =======</p>"
        log += "<p>=========================</p>"

    except Exception, e:
        traceback.print_exc()
예제 #14
0
def notifications_job(request):
  data = None
  log =''
  try:
    match_search = ItemsMatchView()
    pre_reg_items = PreRegisteredItem.objects.filter(lost=True)

    log += "<p>=========================</p>"
    log += "<p>======= START JOB =======</p>"

    for item in pre_reg_items:
      log+= "<p>== Searching matches for item:</p>"
      log+= "<p>______Title: "+item.title+"</p>"
      log+= "<p>______Category: "+item.category+"</p>"
      log+= "<p>______Created on: "+str(item.created_at)+"</p>"
      t= request.GET.copy()
      t.update({'q': string.replace(item.tags,' ','+')})
      t.update({'category': item.category})
      t.update({'unique_id': item.unique_id})
      t.update({'start_date': str(item.created_at).split(' ')[0]})
      request.GET = t
      match_results = match_search.get(request)
      for match in match_results:
        if not Notification.objects.filter(notification_type="MATCH", match=item, topic=match.object):
          log+= "<p>== Creating notification for match:</p>"
          log+= "<p>______Title: "+match.object.title+"</p>"
          log+= "<p>______Category: "+match.object.category+"</p>"
          log+= "<p>______Created on: "+str(match.object.date_field)+"</p>"

          notification = Notification()
          notification.receiver = item.owner
          notification.notification_type = "MATCH"
          notification.message = "This item matched your lost "
          notification.topic = match.object
          notification.match = item
          notification.save()
         
          log += "<p>== Notification Created</p>"
          log += "<p>=======================</p>"
    log += "<p><p>========= END JOB =======</p>"
    log += "<p>=========================</p>"

  except Exception, e:
      traceback.print_exc()
예제 #15
0
def repatriate_item(request):
  response_data = {}
  if request.method=='POST':
    try:
     item_id = request.POST.get('item_id')
     item = Item.objects.filter(pk=item_id)[0]
     item.status = "PREREPATRIATED"
     item.save()

     notification = Notification()
     notification.sender = item.found_by_user
     notification.receiver = item.lost_by_user
     notification.message = item.found_by_user.username + ' wants to mark this item (subject of this conversation) as "Repatriated". If you agreed with the finder on a metting, then please accept his request.'

     notification.topic = item
     notification.notification_type = 'ACCEPT'
     notification.save()
     response_data['result'] = 'OK'
    except Exception, e:
      traceback.print_exc()
      response_data['result'] = 'ERROR'
예제 #16
0
def repatriate_item(request):
    response_data = {}
    if request.method == 'POST':
        try:
            item_id = request.POST.get('item_id')
            item = Item.objects.filter(pk=item_id)[0]
            item.status = "PREREPATRIATED"
            item.save()

            notification = Notification()
            notification.sender = item.found_by_user
            notification.receiver = item.lost_by_user
            notification.message = item.found_by_user.username + ' wants to mark this item (subject of this conversation) as "Repatriated". If you agreed with the finder on a metting, then please accept his request.'

            notification.topic = item
            notification.notification_type = 'ACCEPT'
            notification.save()
            response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
예제 #17
0
def createIssue(request):
    try:
        order = Order.objects.get(id=request.data.get('order'))
        if checkExistingIssue(order):
            raise ValueError("Issue Already exists")
        user = request.user
        profile = Profile.objects.get(user=user)
        chat = createChat(order)
        issueSerializer = IssueProtectedSerializer(data=request.data)
        if issueSerializer.is_valid():
            request.data['profile'] = profile
            request.data['order'] = order
            request.data['chat'] = chat
            issue = issueSerializer.create(request.data)
            issue.save()

            issueNotification = Notification()
            issueNotification.alert = True
            if profile == order.profile:
                issueNotification.user = issue.order.service.profile.user
                alertText = "User %s opened an issue" % issue.order.profile.user.username
            else:
                issueNotification.user = issue.order.profile.user
                alertText = "User %s opened an issue" % issue.order.service.profile.user.username
            issueLink = "%sissue/%d" % (
                issueNotification.getEmailLinkBaseUrl(),
                issue.id
            )
            issueNotification.alertData = "%s|%s|%d" % (alertText, "/issue", issue.id)
            issueNotification.save()

            return Response({'success': True, 'issueId': issue.id},
                            status=status.HTTP_201_CREATED)
        else:
            return Response({'success': False, 'errors': issueSerializer.errors})
    except Profile.DoesNotExist:
        return Response({'success': False, 'error': 'profile.notfound'})
    except Exception as e:
        return Response({'success': False, 'errors': e.message})
예제 #18
0
    def test_for_notification_get_when_no_unread_notification_for_that_user(
            self):
        """
        Unit test for notification get api for no unread notification
        """

        # Setup
        notification = Notification(user=self.user,
                                    event=self.event,
                                    message="test message",
                                    has_read=True)
        notification.save()

        # Run
        response = self.client.get("/core/notification/",
                                   content_type="application/json",
                                   HTTP_AUTHORIZATION="Bearer {}".format(
                                       self.token))

        # Assert
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['data'], [])
예제 #19
0
    def test_notification_api_patch_for_valid_data(self):
        """
        Unit test for notification patch api with valid data
        """

        # Setup
        json_content = {"notification_ids": [1]}
        notification = Notification(user=self.user,
                                    event=self.event,
                                    message="test message",
                                    has_read=False)
        notification.save()

        # Run
        response = self.client.patch("/core/notification/",
                                     data=json_content,
                                     content_type="application/json",
                                     HTTP_AUTHORIZATION="Bearer {}".format(
                                         self.token))

        # Assert
        self.assertEqual(response.status_code, 200)
예제 #20
0
    def test_for_notification_get_data_when_unread_notification(self):
        """
        Unit test for notification get api for unread notification
        """

        # Setup
        notification = Notification(user=self.user,
                                    event=self.event,
                                    message="test message",
                                    has_read=False)
        notification.save()

        # Run
        response = self.client.get("/core/notification/",
                                   content_type="application/json",
                                   HTTP_AUTHORIZATION="Bearer {}".format(
                                       self.token))

        # Assert
        self.assertEqual(response.data['data'][0]['message'],
                         notification.message)
        self.assertEqual(response.data['data'][0]['id'], notification.id)
예제 #21
0
def adminAjaxPostChatMessage(request):
    r = {'success': False, 'chat': None}
    adminUser = User.objects.get(username="******")  #EMULATE ADMIN USER
    try:
        chatId = int(request.POST['chatId'])
        chat = Chat.objects.get(id=chatId)
        message = request.POST['message']
        chatMessage = ChatMessage(sender=adminUser, text=message, chat=chat)
        chatMessage.save()

        issue = Issue.objects.get(chat=chat)

        issueNotificationBuyer = Notification()
        issueNotificationBuyer.alert = True
        issueNotificationBuyer.user = issue.order.profile.user
        alertText = "Admin sent a new message"
        issueLink = "%sissue/%d" % (
            issueNotificationBuyer.getEmailLinkBaseUrl(), issue.id)
        issueNotificationBuyer.alertData = "%s|%s" % (alertText, issueLink)
        issueNotificationBuyer.save()

        issueNotificationForwarder = Notification()
        issueNotificationForwarder.alert = True
        issueNotificationForwarder.user = issue.order.service.profile.user
        alertText = "Admin sent a new message"
        issueLink = "%sissue/%d" % (
            issueNotificationForwarder.getEmailLinkBaseUrl(), issue.id)
        issueNotificationForwarder.alertData = "%s|%s" % (alertText, issueLink)
        issueNotificationForwarder.save()

        chatSerializer = ChatSerializer(chat, context={'request': request})
        chatMessageSerializer = ChatMessageSerializer(
            chatMessage, context={'request': request})
        r['chat'] = chatSerializer.data
        r['message'] = chatMessageSerializer.data
        r['success'] = True
    except Exception, ex:
        r['error'] = "%s" % (traceback.format_exc())
예제 #22
0
def forwardedDelivered(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), service__profile=profile)
        if order.service.type == settings.SERVICE_TYPES[0][0]:
            order.state = ORDER_STATUS['forwarded']
            order.forwardedDate = django.utils.timezone.now()
        if order.service.type == settings.SERVICE_TYPES[1][0]:
            order.state = ORDER_STATUS['delivered']
        order.save()
        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})

        # Notification to buyer
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.profile.user
        orderLink = "%sorders/buyer/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order %s" % (order.state),
            "notifications/email/buyer_order_change_status.html",
            {
                'order': order,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d changed status to %s" % (order.id, order.state)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
예제 #23
0
def respond_to_repatriation(request):

    response_data = {}
    if request.method == 'POST':
        try:
            notification = Notification.objects.filter(
                pk=request.POST.get('notification_id'))[0]

            response = request.POST.get('response')

            notification = Notification.objects.filter(
                pk=request.POST.get('notification_id'))[0]
            item = Item.objects.filter(pk=notification.topic.pk)[0]
            notification.notification_type = "CLAIM"

            new_notification = Notification()
            new_notification.sender = request.user
            new_notification.receiver = notification.sender
            if response == 'true':
                new_notification.message = "Congratulations!! " + notification.topic.title + " has been repatriated."
                new_notification.notification_type = 'CLAIM'
                item.status = "REPATRIATED"
                item.save()
            else:
                new_notification.message = request.user.username + " and you have to agree how the repatriation will occur. Once this is done, you can request a 'Repatriated' status change on " + notification.topic.title
                new_notification.notification_type = 'CLAIM'
                item.status = "CLAIMED"
                item.save()
            new_notification.topic = item
            new_notification.notification_type = 'CLAIM'
            new_notification.save()
            response_data['message'] = new_notification.message
            notification.save()
            response_data['result'] = 'OK'
        except Exception, e:
            traceback.print_exc()
            response_data['result'] = 'ERROR'
예제 #24
0
def orderPayment(request):
    try:
        order = Order.objects.get(id=request.data.get("orderId"))
        inWalletId = order.profile.wallet.id
        outWalletId = order.service.profile.wallet.id

        feePercentage = Configuration().getConfiguration(
            "forwarding_fee_percentage_level_1")

        TransactionManager.createPaymentTransaction(
            amount=order.totalPrice,
            order=order,
            inWalletId=inWalletId,
            outWalletId=outWalletId,
            feePercentage=feePercentage)

        # Notification to forwarder
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.service.profile.user
        orderLink = "%sorders/forwarder/%s" % (
            orderNotification.getEmailLinkBaseUrl(), order.id)
        orderNotification.setEmailData(
            "New LWF Order",
            "notifications/email/forwarder_order_new_status.html", {
                'order': order,
                'orderLink': orderLink
            })
        alertText = "Order #%d has been paid" % order.id
        orderNotification.alertData = "%s|%s|%d" % (
            alertText, "/orders/forwarder", order.id)
        orderNotification.save()

        return Response({'success': True})
    except Exception as e:
        return Response({'success': False, 'errors': e.message})
예제 #25
0
def reply_to_notification(request):

  if request.method=='POST':
    try:
      old_notification = Notification.objects.filter(pk=request.POST.get('notification_pk'))[0]
      sender = request.user
      if old_notification.sender == sender:
        receiver = old_notification.receiver
      else:
        receiver = old_notification.sender
      response_data = {}

      message = request.POST.get('message')
      notification = Notification()
      notification.sender = sender
      notification.receiver = receiver
      notification.notification_type = "CLAIM"
      notification.message = message
      notification.topic = old_notification.topic
      notification.save()
      response_data['result'] = 'OK'
    except Exception, e:
      traceback.print_exc()
      response_data['result'] = 'ERROR'
예제 #26
0
def respond_to_repatriation(request):

  response_data = {}
  if request.method=='POST':
    try:
      notification = Notification.objects.filter(pk=request.POST.get('notification_id'))[0]

      response = request.POST.get('response')

      
      notification = Notification.objects.filter(pk=request.POST.get('notification_id'))[0]
      item = Item.objects.filter(pk=notification.topic.pk)[0]
      notification.notification_type = "CLAIM"

      new_notification = Notification()
      new_notification.sender = request.user
      new_notification.receiver = notification.sender
      if response == 'true':
        new_notification.message = "Congratulations!! "+notification.topic.title + " has been repatriated."
        new_notification.notification_type = 'CLAIM'
        item.status = "REPATRIATED"
        item.save()
      else:
        new_notification.message = request.user.username + " and you have to agree how the repatriation will occur. Once this is done, you can request a 'Repatriated' status change on "+notification.topic.title
        new_notification.notification_type = 'CLAIM'
        item.status = "CLAIMED"
        item.save()
      new_notification.topic = item
      new_notification.notification_type = 'CLAIM'
      new_notification.save()      
      response_data['message'] = new_notification.message
      notification.save()
      response_data['result'] = 'OK'
    except Exception, e:
      traceback.print_exc()
      response_data['result'] = 'ERROR'
예제 #27
0
def application(request, app):
    if not isRecruiter(request.user):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a recruiter.'
        })

    hr = isHR(request.user)
    app = Application.objects.filter(token=app).first()

    if app.status == Application.ACCEPTED and not hr:
        return render(
            request, 'error.html', {
                'title':
                '403 - Forbidden',
                'description':
                'For privacy reasons, only HR officers can view accepted applications.'
            })

    if request.method == "POST":
        if request.POST.get('newComment'):
            c = Comment()
            c.text = request.POST.get('commentbody')
            c.author = request.user.userprofile
            c.date = datetime.utcnow()
            c.auto_generated = False
            c.app = app
            c.save()
            recruiter = Group.objects.filter(name="Recruiter").first()
            note = Notification(cssClass="info")
            note.content = "<a href='" + reverse(
                'core:playerProfile',
                kwargs={"profileName": slugify(
                    request.user.userprofile)}) + "'>" + unicode(
                        c.author) + "</a> commented on <a href='" + reverse(
                            'applications:viewapp',
                            kwargs={"app": app.token}) + "'>" + unicode(
                                app.applicantProfile) + "'s Application</a>."
            note.save()
            note.targetGroup.add(recruiter)
        if request.POST.get('updatestatus'):
            newStatus = int(request.POST.get('status'))
            newTag = int(request.POST.get('tag'))
            if app.status != newStatus and app.STATUS_CHOICES[newStatus]:
                c = Comment(auto_generated=True,
                            date=datetime.utcnow(),
                            app=app,
                            author=request.user.userprofile)
                oldstatus = app.get_status_display()
                app.status = newStatus
                c.text = "changed Status from '" + oldstatus + "' to '" + app.get_status_display(
                ) + "'"
                c.save()
                if newStatus == Application.ACCEPTED:
                    Group.objects.get(name='Member').user_set.add(
                        app.applicantProfile.user)
                else:
                    Group.objects.get(name='Member').user_set.remove(
                        app.applicantProfile.user)
            if app.tag != newTag and app.TAG_CHOICES[newTag]:
                c = Comment(auto_generated=True,
                            date=datetime.utcnow(),
                            app=app,
                            author=request.user.userprofile)
                oldtag = app.get_tag_display()
                app.tag = newTag
                c.text = "changed Tag from '" + oldtag + "' to '" + app.get_tag_display(
                ) + "'"
                c.save()
            app.save()

    profile = app.applicantProfile
    keys = profile.apikey_set.all()
    characters = profile.character_set.all()
    answers = app.answer_set.all()

    r = getFlyable(profile)
    c = {
        "app": app,
        "profile": profile,
        "keys": keys,
        "answers": answers,
        "ships": r,
        "skills": compareSkillplans(profile.mainChar)
    }
    return render(request, "application.html", c)
예제 #28
0
def createOrderNote(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        file = request.data.get('noteImage')
        description = request.data.get('noteText')
        orderId = int(request.data.get('orderId'))
        query = Q(profile=profile) | Q(service__profile=profile)
        order = Order.objects.get(query, id=orderId)
        maxOrderNotes = int(Configuration.objects.get(
            key__iexact='max_order_notes'
        ).value)
        if len(order.notes) >= maxOrderNotes:
            return Response({'success': False, 'error': 'maxOrderNotesReached'})
        if file:
            if file.find("http://") > -1 or file.find("https://") > -1:
                imgstr = base64.b64encode(requests.get(file).content)
                ext = file.split('/')[-1].split(".")[-1]
                noteImageName = "%d.%s" % (user.id, ext)
                data = ContentFile(base64.b64decode(imgstr), name=noteImageName)
                if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                    return Response({'success': False, 'error':'file.toobig'}, 500)
            elif request.data.get('noteImage').find(';base64,') > -1:
                format, imgstr = request.data.get('noteImage').split(';base64,')
                ext = format.split('/')[-1]
                noteImageName = "%d.%s" % (user.id, ext)
                data = ContentFile(base64.b64decode(imgstr), name=noteImageName)
                if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                    return Response({'success': False, 'error':'file.toobig'}, 500)
            else:
                data = None

            newOrderNote = OrderNote()
            newOrderNote.profile = profile
            newOrderNote.order = order
            newOrderNote.orderStatus = order.state
            if data:
                if data.size < settings.MAX_IMAGE_SIZE_UPLOAD:
                    newOrderNote.document = data
            newOrderNote.description = description
            newOrderNote.save()
            order = Order.objects.get(id=orderId)

            if order.state == ORDER_STATUS['paid'] \
                    or order.state == ORDER_STATUS['new'] \
                    or order.state == ORDER_STATUS['refused']:
                orderSerializer = OrderProtectedSerializer(
                    order,
                    context={'request': request}
                )
            else:
                orderSerializer = OrderWithAddressesSerializer(
                    order,
                    context={'request': request},
                )

            # Notification to buyer or Forwarder
            orderNotification = Notification()
            orderNotification.email = True
            orderNotification.alert = True
            alertText = "Order #%d has new note" % (order.id)
            if user.id == order.profile.user.id:
                orderNotification.user = order.service.profile.user
                notificationProfile = order.service.profile
                orderLink = "%sorders/forwarder/%s" % (
                    orderNotification.getEmailLinkBaseUrl(),
                    order.id
                )
                orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/forwarder/", order.id)
            else:
                orderNotification.user = order.profile.user
                notificationProfile = order.profile
                orderLink = "%sorders/buyer/%s" % (
                    orderNotification.getEmailLinkBaseUrl(),
                    order.id
                )
                orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
            orderNotification.setEmailData(
                "LWF Order Has New Note",
                "notifications/email/order_note_new.html",
                {
                    'order': order,
                    'profile': notificationProfile,
                    'orderLink': orderLink
                }
            )
            orderNotification.save()

            return Response({'success': True, 'order': orderSerializer.data})
        else:
            return Response({'success': False, 'error': 'nofile'})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
예제 #29
0
def viewsrp(request, killID):
    kill = SRPRequest.objects.get(killID=killID)
    f = isFinance(request.user)
    if not (f or request.user.userprofile == kill.owner):
        return render(request, 'error.html', {
            'title': '403 - Forbidden',
            'description': 'You are not a member.'
        })

    if request.method == "POST":
        if request.POST.get('newComment', False):
            c = SRPComment()
            c.text = request.POST.get('commentbody')
            c.author = request.user.userprofile
            c.date = datetime.utcnow()
            c.request = kill
            c.save()
            finance = Group.objects.filter(name="Finance").first()
            note = Notification(cssClass="info")
            note.content = "<a href='" + reverse(
                'core:playerProfile',
                kwargs={"profileName": slugify(
                    request.user.userprofile)}) + "'>" + unicode(
                        c.author) + "</a> commented on <a href='" + reverse(
                            'srp:viewsrp',
                            kwargs={"killID": kill.killID}) + "'>" + unicode(
                                kill.owner
                            ) + "'s SRP Request for a " + kill.ship + "</a>"
            note.save()
            note.targetGroup.add(finance)
            note.targetUsers.add(kill.owner.user)
        elif request.POST.get('approve', False) and kill.status != 1 and f:
            kill.status = 1
            kill.approver = request.user.userprofile
            n = Notification(
                cssClass='success',
                content='Your <a href="' + reverse("srp:srplist") +
                '">SRP request</a> for a ' + kill.ship + ' has been accepted.')
            n.save()
            n.targetUsers.add(kill.owner.user)
        elif request.POST.get('deny', False) and kill.status != 2 and f:
            kill.status = 2
            kill.approver = request.user.userprofile
            n = Notification(
                cssClass='danger',
                content='Your <a href="' + reverse("srp:srplist") +
                '">SRP request</a> for a ' + kill.ship + ' has been denied.')
            n.save()
            n.targetUsers.add(kill.owner.user)
        elif request.POST.get('pending', False) and kill.status != 0 and f:
            kill.status = 0
            kill.approver = None
            n = Notification(
                cssClass='warning',
                content='Your <a href="' + reverse("srp:srplist") +
                '">SRP request</a> for a ' + kill.ship + ' has been reset.')
            n.save()
            n.targetUsers.add(kill.owner.user)
        kill.save()

    if not Character.objects.filter(charName=kill.pilot).exists():
        apiwarning = True
    else:
        apiwarning = False

    if not kill:
        return render(
            request, 'error.html', {
                'title': '404 - Not Found',
                'description': 'There is no kill with that ID in the database.'
            })
    c = {"kill": kill, "apiwarning": apiwarning, "admin": f}
    return render(request, "srpdetails.html", c)
예제 #30
0
def viewTicket(request, token):
    ticket = Ticket.objects.get(token=token)
    f = isDirector(request.user)
    if not (f or not ticket.author
            or request.user.userprofile == ticket.author):
        return render(
            request, 'error.html', {
                'title': '403 - Forbidden',
                'description': 'You do not have permission to view this page.'
            })

    if request.method == "POST":

        director = Group.objects.filter(name="Director").first()
        oldstatus = ticket.get_status_display()

        if request.POST.get('newComment', False):

            c = Comment()
            c.text = request.POST.get('commentbody')
            c.author = request.user.userprofile
            c.date = datetime.utcnow()
            c.ticket = ticket
            c.private = request.POST.get('private') == "on"
            c.save()

            note = Notification(cssClass="info")
            note.content = "<a href='" + reverse(
                'core:playerProfile',
                kwargs={
                    "profileName": slugify(request.user.userprofile)
                }) + "'>" + unicode(
                    c.author) + "</a> commented on <a href='" + reverse(
                        'helpdesk:viewticket',
                        kwargs={"token": ticket.token}) + "'>Ticket #" + str(
                            ticket.id) + " \"" + ticket.title + "\"</a>"
            note.save()
            note.targetGroup.add(director)
            if ticket.author and not c.private:
                note.targetUsers.add(ticket.author.user)

        elif request.POST.get('inprogress',
                              False) and ticket.status != 1 and f:
            ticket.status = 1
            n = Notification(
                cssClass='success',
                content="<a href='" + reverse('helpdesk:viewticket',
                                              kwargs={"token": ticket.token}) +
                "'>Ticket #" + str(ticket.id) + " \"" + ticket.title +
                "\"</a> has been set to \"In Progress\" by <a href='" +
                reverse('core:playerProfile',
                        kwargs={
                            "profileName": slugify(request.user.userprofile)
                        }) + "'>" + unicode(request.user.userprofile) + "</a>")
            n.save()
            if ticket.author:
                n.targetUsers.add(ticket.author.user)
            n.targetGroup.add(director)

        elif request.POST.get('resolved', False) and ticket.status != 2 and f:
            ticket.status = 2
            n = Notification(
                cssClass='success',
                content="<a href='" + reverse('helpdesk:viewticket',
                                              kwargs={"token": ticket.token}) +
                "'>Ticket #" + str(ticket.id) + " \"" + ticket.title +
                "\"</a> has been set to \"Resolved\" by <a href='" + reverse(
                    'core:playerProfile',
                    kwargs={"profileName": slugify(request.user.userprofile)})
                + "'>" + unicode(request.user.userprofile) + "</a>")
            n.save()
            if ticket.author:
                n.targetUsers.add(ticket.author.user)
            n.targetGroup.add(director)

        elif request.POST.get('new', False) and ticket.status != 0 and f:
            ticket.status = 0
            n = Notification(
                cssClass='warning',
                content="<a href='" + reverse('helpdesk:viewticket',
                                              kwargs={"token": ticket.token}) +
                "'>Ticket #" + str(ticket.id) + " \"" + ticket.title +
                "\"</a> has been set to \"New\" by <a href='" + reverse(
                    'core:playerProfile',
                    kwargs={"profileName": slugify(request.user.userprofile)})
                + "'>" + unicode(request.user.userprofile) + "</a>")
            n.save()
            if ticket.author:
                n.targetUsers.add(ticket.author.user)
            n.targetGroup.add(director)

        if oldstatus != ticket.get_status_display():
            c = Comment(auto_generated=True)
            c.text = "changed Satus from \"" + oldstatus + "\" to \"" + ticket.get_status_display(
            ) + "\""
            c.author = request.user.userprofile
            c.date = datetime.utcnow()
            c.ticket = ticket
            c.private = False
            c.save()

        ticket.save()

    if not ticket:
        return render(request, 'error.html', {
            'title': '404 - Not Found',
            'description': 'Ticket not found.'
        })

    comments = Comment.objects.filter(
        ticket=ticket) if f else Comment.objects.filter(ticket=ticket).filter(
            private=False)

    c = {"ticket": ticket, "admin": f, "comments": comments}
    return render(request, "ticketdetails.html", c)
예제 #31
0
def createIssueChatMessage(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        file = request.data.get('messageImage')
        text = request.data.get('messageText')
        chatId = int(request.data.get('chatId'))
        query = Q(profile=profile) | Q(order__buyer=profile) | Q(
            order__courier=profile)
        issue = InstantDeliveryOrderIssue.objects.get(
            query, state=issueStatus['OPEN'], chat__id=chatId)
        chatMessage = ChatMessage()
        if file:
            if file.find("http://") > -1 or file.find("https://") > -1:
                imgstr = base64.b64encode(requests.get(file).content)
                ext = file.split('/')[-1].split(".")[-1]
                noteImageName = "%d.%s" % (user.id, ext)
                data = ContentFile(base64.b64decode(imgstr),
                                   name=noteImageName)
                if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                    return Response({
                        'success': False,
                        'error': 'file.toobig'
                    }, 500)
            else:
                format, imgstr = request.data.get('messageImage').split(
                    ';base64,')
                ext = format.split('/')[-1]
                noteImageName = "%d.%s" % (user.id, ext)
                data = ContentFile(base64.b64decode(imgstr),
                                   name=noteImageName)
                if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                    return Response({
                        'success': False,
                        'error': 'file.toobig'
                    }, 500)
            chatMessage.image = data

        chatMessage.chat = issue.chat
        chatMessage.sender = profile.user
        chatMessage.text = text
        chatMessage.save()
        issue = InstantDeliveryOrderIssue.objects.get(query, chat__id=chatId)
        issueSerializer = IssueSerializer(issue, context={'request': request})

        issueNotification = Notification()
        issueNotification.alert = True
        if profile == issue.order.courier:
            issueNotification.user = issue.order.courier.user
            alertText = "User %s sent a new message" % issue.order.courier.user.username
        else:
            issueNotification.user = issue.order.buyer.user
            alertText = "User %s sent a new message" % issue.order.buyer.user.username
        issueLink = "%sissue/%d" % (issueNotification.getEmailLinkBaseUrl(),
                                    issue.id)
        issueNotification.alertData = "%s|%s|%d" % (alertText, "/issue",
                                                    issue.id)
        issueNotification.save()

        return Response({'success': True, 'issue': issueSerializer.data})
    except Profile.DoesNotExist:
        return Response({'success': False, 'error': 'profile.notfound'})
    except Exception as e:
        return Response({'success': False, 'errors': e.message})
예제 #32
0
def push(user, text, link):
    notification = Notification(user=user.userprofile, text=text, link=link)

    notification.save()
예제 #33
0
 def notification_save(title, description, notification_type, date_time, is_deleted, is_read, role, user_id, session_id):
     notification_obj = Notification(title=title, description=description, notification_type=notification_type, date_time=date_time, is_deleted=is_deleted, is_read=is_read, role=role, user_id=user_id, session_id=session_id)
     notification_obj.save(using='session_db')
예제 #34
0
파일: views.py 프로젝트: anidem/ggv-py
    def get(self, request, *args, **kwargs):
        course = Course.objects.get(slug=self.kwargs['crs_slug'])
        is_instructor = 'instructor' in get_perms(self.request.user, course)
        is_student = 'access' in get_perms(self.request.user, course)
        """ User has previously completed or is staff. No viewing restrictions enforced. """
        if self.request.user.is_staff or is_instructor or self.completion_status.count(
        ):

            if not self.next_question:
                """ No more questions. Show student user the worksheet completion page. """
                if is_student and not is_instructor:
                    user_ws_status = UserWorksheetStatus.objects.filter(
                        user=self.request.user).get(
                            completed_worksheet=self.worksheet)
                    return HttpResponseRedirect(
                        reverse('worksheet_completed',
                                args=(self.kwargs['crs_slug'],
                                      user_ws_status.id)))

                return HttpResponseRedirect(
                    reverse('worksheet_user_report',
                            args=(self.kwargs['crs_slug'], self.worksheet.id,
                                  self.request.user.id)))

            return super(QuestionResponseView,
                         self).get(request, *args, **kwargs)
        """ User is not staff but viewing restrictions are not enforced if response not required. """
        if self.next_question:
            if not self.next_question['question'].response_required:
                return super(QuestionResponseView,
                             self).get(request, *args, **kwargs)
        """ Viewing restrictions enforced. """
        self.next_question = self.worksheet.get_next_question(
            self.request.user)
        """ If user's response queue is empty, user has completed worksheet, write completion status.
            Send user to worksheet report.
        """
        if not self.next_question:
            if not self.completion_status:
                user_ws_status = UserWorksheetStatus(
                    user=self.request.user,
                    completed_worksheet=self.worksheet,
                    score=self.worksheet.get_user_score(self.request.user))
                user_ws_status.save()
                self.completion_status = True

                logpath = reverse('worksheet_report',
                                  args=(
                                      self.kwargs['crs_slug'],
                                      self.worksheet.id,
                                  ))

                msg = '<a href="%s">%s</a>' % (logpath, self.worksheet.title)
                msg_detail = self.worksheet.lesson.title
                logged = ActivityLog(user=self.request.user,
                                     action='completed-worksheet',
                                     message=msg,
                                     message_detail=msg_detail)
                logged.save()
                """ Create notification for instructor(s) that the user has completed the worksheet """
                for i in course.instructor_list():
                    notification = Notification(
                        user_to_notify=i,
                        context='worksheet',
                        event=self.worksheet.notify_text(
                            crs_slug=course.slug, user=self.request.user))
                    notification.save()
                """ Send email to instructor(s) that the user has completed the worksheet. """
                SendWorksheetNotificationEmailToInstructors(
                    self.request, course, self.worksheet)

                return HttpResponseRedirect(
                    reverse('worksheet_completed',
                            args=(self.kwargs['crs_slug'], user_ws_status.id)))
        """
        Request parameter <j> is potentially overidden by next unanswered question
        in user's response queue.
        """
        if str(self.next_question['index']) != self.kwargs['j']:
            return HttpResponseRedirect(
                reverse('question_response',
                        args=(self.kwargs['crs_slug'], self.worksheet.id,
                              self.next_question['index'])))

        return super(QuestionResponseView, self).get(request, *args, **kwargs)