Beispiel #1
0
def ticket_create(request):
    if request.method == 'POST':
        form = TicketForm(request.POST)
        if form.is_valid():
            ticket = Ticket(
                author=request.user,
                user=form.cleaned_data.get('user'),
                department=form.cleaned_data.get('department'),
                title=form.cleaned_data.get('title'),
                description=form.cleaned_data.get('description'),
                priority=form.cleaned_data.get('priority'),
                due_date=form.cleaned_data.get('due_date')
            )
            ticket.save()

            attachment_list = request.FILES.getlist('attachments')
            for attachment in attachment_list:
                ta = TicketAttachment(
                    user=request.user,
                    ticket=ticket,
                    attachment=attachment,
                )
                ta.save()

            messages.success(request, 'Successfully created ticket.')
            return redirect('dashboard')
    else:
        initial = {'priority': Ticket.SOON_PRIORITY, 'user': request.user}
        if request.user.department:
            initial.update({'department': request.user.department})
        form = TicketForm(initial=initial)

    dict_context = {'form': form}

    return render(request, 'tickets/create.html', dict_context)
Beispiel #2
0
    def test_order_txn(self):
        order = Order(full_name='Test',
                      phone_number='012345',
                      country='gb',
                      postcode='ab123')
        order.save()
        user = User(email='*****@*****.**', first_name='Test', last_name='Case')
        user.save()
        ticket = Ticket(requester=user, title='Title')
        ticket.save()
        transaction = OrderTransaction(order=order, ticket=ticket, cost=2.2)
        transaction.save()

        print('TestCheckoutModels: OrderTransaction - test_order_txn \n \
               Expected: {0}, Actual: {1} \n \
               Expected: {2}, Actual: {3} \n \
               Expected: {4}, Actual: {5} \n \
               Expected: {6}, Actual: {7} \n \
               Expected: {8}, Actual: {9}'.format(
            'Test', transaction.order.full_name, '012345',
            transaction.order.phone_number, user, transaction.ticket.requester,
            'Title', transaction.ticket.title, '2.2', transaction.cost))

        self.assertEqual(transaction.order.full_name, 'Test')
        self.assertEqual(transaction.order.phone_number, '012345')
        self.assertEqual(transaction.ticket.requester, user)
        self.assertEqual(transaction.ticket.title, 'Title')
        self.assertEqual(transaction.cost, 2.2)
Beispiel #3
0
 def test_bar_charts(self):
      """
      Tests popularity charts data
      """
      ticket0 = Ticket(variety='B', issue='ticket0', verified = True, 
      date_verified=datetime.date.today(), date_start_dev=datetime.date.today())
      ticket0.save()
      ticket1 = Ticket.objects.create(
           variety = "F",
           issue = "ticket1",
           verified = True,
           upvotes=10
      )
      ticket2 = Ticket.objects.create(
           variety='B', 
           issue='ticket2',
           upvotes=5
           )
      ticket3 = Ticket.objects.create(
           variety='F', 
           issue='ticket3',
           upvotes=80
           )
      f_chart = FPopularityBarChart()
      b_chart = BPopularityBarChart()
      
      assert(f_chart.get_data()=={'ticket1': 10, 'ticket3': 80})
      assert(b_chart.get_data()=={'ticket2': 5, 'ticket0': 0})
Beispiel #4
0
def post_ticket(request):
    try :
        content = request.POST['content']
        title = request.POST['ticket_title']
    except KeyError:
        return HttpResponseRedirect('/')
    admins = User.objects.filter(is_staff=True)
    try :
        admin = choice(admins)
    except IndexError:
        return HttpResponseRedirect('/')
    ticket = Ticket(
        title=title,
        admin=admin,
        author=request.user,
        pub_date=timezone.now(),
        mod_date=timezone.now()
    )
    ticket.save()
    message = Message(
        ticket=ticket,
        author=request.user,
        content=content,
        pub_date=timezone.now()
    )
    message.save()
    url = reverse('tickets:ticket', kwargs={'pk' : ticket.id})
    return HttpResponseRedirect(url)
    def test_ticket_time(self):
        #Test if a new ticket_time object can be created

        user = User.objects.create_user(username='******',
                                        first_name='test',
                                        last_name='tester',
                                        password='******',
                                        email='*****@*****.**')
        user.save()

        ticket = Ticket(title='test',
                        author=user,
                        username=user.username,
                        description='test',
                        ticket_type=2,
                        status=1,
                        comment_num=0,
                        upvotes=0)
        ticket.save()

        time = Ticket_Time(ticket=ticket, match_ticket_id=ticket.id)
        time.save()

        self.assertEqual(time.ticket, ticket)
        self.assertEqual(time.match_ticket_id, ticket.id)
Beispiel #6
0
 def test_ActivityChartdata(self):
      """
      Tests updates chart data
      """
      ticket0 = Ticket(variety='B', issue='ticket0', verified = True, 
      date_verified=datetime.date.today(), date_start_dev=datetime.date.today())
      ticket0.save()
      ticket1 = Ticket.objects.create(
           variety = "F",
           issue = "ticket1",
           verified = True,
           date_verified=datetime.date.today(),
           date_start_dev=datetime.date.today(),
            date_done=datetime.date.today()
      )
      ticket2 = Ticket.objects.create(
           variety='B', 
           issue='ticket2',
           verified = True,
           date_verified=datetime.date.today()
           )
          
      chart = ActivityLineChart()
      
      assert(chart.get_data() == 
      {'ticket0': [datetime.date.today(), datetime.date.today(), None], 
      'ticket2': [datetime.date.today(), None, None], 
      'ticket1': [datetime.date.today(), datetime.date.today(), datetime.date.today()]
           
      })
def add_ticket(request, requested):
    layout = request.GET.get('layout')
    if not layout:
        layout = 'vertical'
    if request.method == 'POST':
        form = AddTicketForm(request.POST)
        if (int(requested) == int(request.user.pk)):
            if form.is_valid():
                redirect_url = '/user/' + str(request.user.pk)
                new_comment = form.process()
                ticket_user = User.objects.get(id=request.user.pk)
                t = Ticket(status = 'in_queue', pub_date = timezone.now(), comment = new_comment, created_by = ticket_user)
                t.save()
                return HttpResponseRedirect(redirect_url)
        else:
            context = {
                'requested': request.user.pk
            }
            return render_to_response('tickets/restricted_access.html', context)
    else:
        form = AddTicketForm()
        args = {}
        args.update(csrf(request))
        args['form'] = form
        context = {
        'requested': requested,
        'form': form,
        }
        return render_to_response('tickets/create_ticket.html', context, RequestContext(request, {
	       'form': form,
	       'layout': layout,
        }))
Beispiel #8
0
 def test_removing_from_cart(self):
     ticket = Ticket(variety='F', issue='some extra feature')
     ticket.save()
     cart = Cart(self.request)
     cart.add(ticket)
     cart.remove(ticket)
     self.assertEqual(len(cart), 0)
     self.assertEqual(cart.get_total(), 0)
Beispiel #9
0
 def test_create_donation(self):
     user = User(email='*****@*****.**')
     user.save()
     ticket = Ticket(title='Test', description='My description')
     ticket.save()
     donation = Donation(ticket=ticket, user=user, amount=100)
     donation.save()
     self.assertEqual(donation.amount, 100)
Beispiel #10
0
 def entries(self):
 	user=User.objects.get(id=8)
 	flight=Flight.objects.get(flight_id=3)
 	
 	for i in range(1,10):
 		unique_id = get_random_string(length=10)
 		p = Ticket(buyer=user, passenger = unique_id, flightID=flight, travelClass='EC', buyPrLine=True, buyVIP = False, buyFood = 'EN', buyWaitRoom = False)
 		p.save()
Beispiel #11
0
    def test_user_detail_page_does_not_contain_ticket_when_user_is_not_submitter_or_developer(
            self):
        ticket3 = Ticket(title='title3', description='d1')

        # now we save and check that ticket1 is part of response:
        ticket3.save()
        self.response = self.client.get(self.url)
        self.assertNotContains(self.response, 'title3')
Beispiel #12
0
 def test_updating_cart(self):
     ticket = Ticket(variety='F', issue='some extra feature')
     ticket.save()
     cart = Cart(self.request)
     cart.add(ticket)
     cart.add(ticket, donation=15, update=True)
     self.assertEqual(len(cart), 1)
     self.assertEqual(cart.get_total(), 15)
Beispiel #13
0
class TicketTestCase(TestCase):

    def setUp(self):
        """"
        Set up superuser
        """
        self.super_admin = User.objects.create_superuser(
            username='******',
            password='******',
            email='*****@*****.**'
        )
        data = dict(
            username='******',
            password='******'
        )
        self.create_category = Category.objects.create(
            name='Premium',
            slug='CreditCard'
        )
        self.get_user = User.objects.get(
            username='******'
        )
        self.category = Category.objects.get(
            name='Premium'
        )
        response = client.post('/api/token/', data=data, format='json')
        self.access_token = (json.loads(response.content))['access']
        self.url = '/api/tickets/'


    def test_create_ticket(self):
        """
        Test user can create ticket
        """

        self.ticket = Ticket(
            title='Python Ticket',
            user=self.get_user,
            content='The Beginning of Python',
            category=self.category
        )
        self.ticket.save()
        response = client.get(
            self.url,
            HTTP_AUTHORIZATION="Bearer {}".format(self.access_token),
            format='json'
        )
        self.assertEqual((json.loads(response.content)['results'][0]['title']),
                        'Python Ticket')
        self.assertIn(self.ticket.content,
                        json.loads(response.content)['results'][0]['content'])

    def test_ticket_list(self):
        """
        Ensure we can view list of tickets.
        """
        response = client.get(self.url, format='json')
        self.assertEqual(response.status_code, 200)
Beispiel #14
0
 def test_view_add(self):
     ticket = Ticket(variety='F', issue='some feature')
     ticket.save()
     response = self.client.get(
         reverse('cart:add_to_cart', args=(ticket.id, )))
     # redirecting
     self.assertEqual(response.status_code, 302)
     self.assertEqual(
         dict(response.items())['Location'], '/cart/cart_detail')
Beispiel #15
0
def ticket_purchase(request, id_article):
    article = Article.objects.select_related('event').get(pk=id_article)
    assert article.is_active(), "Este tipo de entrada no está ya disponible."
    event = article.event
    if request.method == 'POST':
        email = request.POST['stripeEmail']
        name = request.POST['name']
        surname = request.POST['surname']
        phone = request.POST.get('phone', None)
        token = request.POST['stripeToken']
        stripe.api_key = settings.STRIPE_SECRET_KEY
        try:
            customer = stripe.Customer.create(
                email=email,
                source=token,
                description='{}, {}'.format(surname, name),
            )
            charge = stripe.Charge.create(customer=customer.id,
                                          amount=article.price_in_cents,
                                          currency='EUR',
                                          description='{}/{}, {}'.format(
                                              event.hashtag,
                                              surname,
                                              name,
                                          ))
            if charge.paid:
                ticket = Ticket(
                    article=article,
                    customer_name=name,
                    customer_surname=surname,
                    customer_email=email,
                    customer_phone=phone,
                    payment_id=charge.id,
                )
                ticket.save()
                send_ticket.delay(ticket)
                return redirect(links.article_bought(article.pk))
            else:
                return stripe_payment_declined(request, charge)
        except stripe.error.StripeError as err:
            logger.error('Error de stripe')
            logger.error(str(err))
            return stripe_payment_error(request, err)
        except Exception as err:
            logger.error('Error en el pago por stripe')
            logger.error(str(err))
            messages.add_message(request, messages.ERROR, 'Hello world.')
            from django.http import HttpResponse
            return HttpResponse("Something goes wrong\n{}".format(err))
    else:
        return render(
            request, 'events/buy-article.html', {
                'event': event,
                'article': article,
                'stripe_public_key': settings.STRIPE_PUBLIC_KEY,
            })
Beispiel #16
0
 def _create_ticket_item(self, ticket_id, ticket_request, price):
     ticket = Ticket(
         id=ticket_id,
         email=ticket_request.email,
         movieDate_id=ticket_request.movieDateId,
         nrOfSeats=ticket_request.nrOfSeats,
         status=TICKET_STATUS_CREATED,
         ticketRequestData=JsonSerializer().serialize(ticket_request),
         price=price)
     ticket.save()
Beispiel #17
0
def test_ticket_of(database):
    event = Event.create(price=2500, title='METZ', description='at Logo')
    purchase = Purchase.create(email='*****@*****.**', event=event)
    tickets = purchase.create_tickets(2)

    selected = Ticket.of(tickets[0].id, tickets[0].secret)
    assert selected.event.id == event.id

    with pytest.raises(Ticket.DoesNotExist):
        Ticket.of(42, 'notsosecret')
Beispiel #18
0
    def test_can_create_read_update_ticket(self):
        # create a ticket record
        ticket = Ticket(**self.ticket)
        ticket.save()
        self.assertIsNotNone(ticket.id, None)

        # test that a ticket record has been added
        ticket = Ticket.objects.get(id=ticket.id)
        self.assertIsNotNone(ticket.id)

        # update a ticket record
        new_ticket_id = "898273499823hiuh32898w"
        ticket = Ticket.objects.get(id=ticket.id)
        ticket.ticket_id = new_ticket_id
        ticket.save()

        # update deal title for next test
        self.ticket['ticket_id'] = new_ticket_id
        self.assertEquals(ticket.ticket_id, new_ticket_id)

        # delete a ticket record
        ticket = Ticket.objects.get(id=ticket.id)
        Ticket.delete(ticket)
        with self.assertRaises(Ticket.DoesNotExist) as context:
            Ticket.objects.get(**self.ticket)
        self.assertTrue("does not exist" in context.exception.message)
Beispiel #19
0
 def test_cart_detail_view_content(self):
     """
       Tests if order total is rendered as expected, and if Checkout button is visible
       """
     ticket = Ticket(variety='F', issue='some feature')
     ticket.save()
     response = self.client.get(
         reverse('cart:add_to_cart', args=(ticket.id, )))
     response = self.client.get(reverse('cart:cart_detail'))
     self.assertIn('Your Order Total is', str(response.content))
     self.assertIn('Checkout', str(response.content))
Beispiel #20
0
 def buy_tickets(self, quantity, session_obj):
     # update profile.total_cost
     self.total_cost += (quantity * session_obj.price)
     self.save()
     # update session.available_seats
     session_obj.available_seats -= quantity
     session_obj.update()
     # create ticket objects
     for q in range(quantity):
         ticket = Ticket(buyer=self.user, session=session_obj)
         ticket.save()
Beispiel #21
0
def ticket_qrcode(ticket_id):
    secret = request.args.get('secret')
    try:
        Ticket.of(ticket_id, secret)
    except Ticket.DoesNotExist:
        abort(404)

    qr = pyqrcode.create(secret)
    out = BytesIO()
    qr.svg(out, scale=4)
    out.seek(0)
    return send_file(out, mimetype='image/svg+xml')
Beispiel #22
0
 def test_search_(self):
     user = User.objects.create_user(username='******',
                                     password='******')
     self.client.login(username='******', password='******')
     ticket = Ticket(ticketName="Test Ticket",
                     description='test-content',
                     author=user)
     ticket.save()
     self.client.post
     page = self.client.get("/search/?query=unicorn", follow=True)
     self.assertEqual(page.status_code, 200)
     self.assertTemplateUsed(page, "search_results.html")
Beispiel #23
0
    def _move_ticket(cls,
                     ticket: Ticket,
                     previous_ticket_id: Optional[int],
                     new_category_id: int,
                     save: bool = False):
        if not previous_ticket_id:
            new_priority = 0
        else:
            previous_ticket = Ticket.objects.filter(
                id=previous_ticket_id).first()
            if not previous_ticket:
                raise TicketNotFoundException

            if ticket.category_id == new_category_id:
                if ticket.priority > previous_ticket.priority:
                    new_priority = previous_ticket.priority + 1
                else:
                    new_priority = previous_ticket.priority
            else:
                new_priority = previous_ticket.priority + 1

        if ticket.category_id == new_category_id:
            if ticket.priority < new_priority:
                Ticket.objects \
                    .filter(
                        category_id=ticket.category_id,
                        priority__gt=ticket.priority,
                        priority__lte=new_priority,
                    ) \
                    .update(priority=F('priority') - 1)
            else:
                Ticket.objects \
                    .filter(
                        category_id=ticket.category_id,
                        priority__lt=ticket.priority,
                        priority__gte=new_priority,
                    ) \
                    .update(priority=F('priority') + 1)
        else:
            Ticket.objects \
                .update(
                    priority=Case(
                        When(category_id=new_category_id, priority__gte=new_priority, then=F('priority') + 1),
                        When(category_id=ticket.category_id, priority__gt=ticket.priority, then=F('priority') - 1),
                        default=F('priority'),
                    )
                )

        ticket.category_id = new_category_id
        ticket.priority = new_priority

        if save:
            ticket.save(update_fields=('priority', 'category_id'))
Beispiel #24
0
    def test_get_request_and_pay_anonymously(self):
        """
          Automated test for what happens if user is authenticated
          """
        stripe.api_key = settings.STRIPE_SECRET

        data = {
            'full_name': "test_from_profile",
            'phone_number': "test_from_profile",
            'country': "test_from_profile",
            'postcode': "test_from_profile",
            'town_or_city': "test_from_profile",
            'street_address1': "test_from_profile",
            'county': "test_from_profile"
        }

        token = stripe.Token.create(
            card={
                'number': '4242424242424242',
                'exp_month': '6',
                'exp_year': str(datetime.today().year + 1),
                'cvc': '123',
            })
        ticket = Ticket(variety='F', issue='some feature')
        ticket.save()
        self.client.get(reverse('cart:add_to_cart', args=(ticket.id, )))
        session = self.client.session
        response = self.client.post(reverse('checkout:order_create'),
                                    data=data)
        order = get_object_or_404(Order, pk=1)
        self.assertFalse(order.paid)
        token = {'stripeToken': token.id}
        ticket_not_upvoted = get_object_or_404(Ticket, pk=1)
        # still 0 upvotes
        self.assertEqual(str(ticket_not_upvoted),
                         'Ticket #1, type: F, to do, 0 upvotes')
        # success, transaction visible on my stripe account
        response = self.client.post(reverse('checkout:order_pay',
                                            args=(order.id, )),
                                    data=token)
        ticket_upvoted = get_object_or_404(Ticket, pk=1)
        order = get_object_or_404(Order, pk=1)
        self.assertTrue(order.paid)
        order_item = get_object_or_404(OrderItem, pk=1)
        self.assertNotEqual(str(ticket_upvoted),
                            'Ticket #1, type: F, to do, 0 upvotes')
        self.assertEqual(str(ticket_upvoted),
                         'Ticket #1, type: F, to do, 1 upvotes')
        self.assertEqual(str(order),
                         'Order #1, for 1 item(s), total cost of 5.00.')
        self.assertEqual(str(order_item),
                         "order id is 1, ticket's id is 1 - some feature")
Beispiel #25
0
def createTicket(request):
    if request.method == "POST":
        title = request.POST.get('title')
        content = request.POST.get('content')
        author = request.POST.get('author')
        ticket_save = Ticket(title=title, content=content, author=author)
        ticket_save.save()
        print("ticket created")
        last_saved_ticket = Ticket.objects.last()
        messages.success(
            request,
            f'Ticket: {last_saved_ticket.tno} has been created successfully!')
    return redirect(f'/tickets/{last_saved_ticket.tno}')
Beispiel #26
0
 def test_simple_rendering(self):
     """
       This automated test is checking page rendering
       """
     ticket = Ticket(variety='F', issue='some feature')
     ticket.save()
     self.client.get(reverse('cart:add_to_cart', args=(ticket.id, )))
     session = self.client.session
     response = self.client.get(reverse('checkout:order_create'))
     self.assertEqual(response.status_code, 200)
     self.assertTemplateUsed('create_oder.html')
     self.assertIn('Payment Details', str(response.content))
     self.assertIn('Back to cart', str(response.content))
Beispiel #27
0
    def test_user_detail_page_contains_ticket_when_user_is_submitter(self):
        ticket2 = Ticket(
            title='title2',
            description='d1',
            developer=self.user,
        )
        # ticket is not saved, so currently user is not developerr of ticket
        self.assertNotContains(self.response, 'title2')

        # now we save and check that ticket1 is part of response:
        ticket2.save()
        self.response = self.client.get(self.url)
        self.assertContains(self.response, 'title2')
Beispiel #28
0
 def handle(self, *args, **options):
     user = User.objects.get(id=1)
     flight = Flight.objects.get(flight_id=3)
     for _ in range(options['users']):
         unique_id = get_random_string(length=10)
         p = Ticket(buyer=user,
                    passenger=unique_id,
                    flightID=flight,
                    travelClass='EC',
                    buyPrLine=True,
                    buyVIP=False,
                    buyFood='EN',
                    buyWaitRoom=False)
         p.save()
Beispiel #29
0
    def get(self, request, *args, **kwargs):
        """
        Handles get request to the 'download_ticket' named route

        Returns:
            A PDF response containing the ticket
        """
        user = request.user
        deal_id = kwargs['deal_id']
        deal = Deal.objects.get(pk=deal_id)
        quantity = int(request.GET.get('qty'))
        price = quantity * deal.price
        qr_img, unique_id = self.generate_unique_code(deal, user)
        logo_url = deal.advertiser.logo_image_url()

        # add ticket to database
        ticket = Ticket(
            user=user, item=deal, quantity=quantity,
            advertiser=deal.advertiser, ticket_id=unique_id
        )
        ticket.save()

        context = {
            'deal': deal,
            'logo_url': logo_url,
            'qr_img': qr_img,
            'issue_date': ticket.date_created,
            'quantity': quantity,
            'price': price,
            'user': user
        }
        html_template = get_template('tickets/ticket.html')
        rendered_html = html_template.render(
            RequestContext(request, context)).encode(encoding="UTF-8")
        styles = [
            CSS(string='.well-print { background-color: grey !important }'),
            CSS(
                settings.STATIC_ROOT + '/bootstrap/dist/css/bootstrap.min.css'
            ),
            CSS(settings.STATIC_ROOT + '/css/base_styles.css'),
        ]
        pdf_file = HTML(
            string=rendered_html,
            base_url=request.build_absolute_uri()
        ).write_pdf(stylesheets=styles)

        http_response = HttpResponse(pdf_file, content_type='application/pdf')
        http_response['Content-Disposition'] = ('attachment; '
                                                'filename=%s') % deal.slug
        return http_response
    def test_no_comments_returns_total_comments(self):
        '''
        Test the no_comments property returns a count of all comments on an Ticket.
        '''
        test_ticket_comments = Ticket(user=self.test_user,
                                      title='Test Comments',
                                      content='Test content')
        test_ticket_comments.save()

        test_ticket_wo_comments = Ticket(user=self.test_user,
                                         title='Test Comments',
                                         content='Test content')
        test_ticket_wo_comments.save()

        comment1 = Comment(user=self.test_user,
                           ticket=test_ticket_comments,
                           content='Test comment 1')
        comment1.save()

        comment2 = Comment(user=self.test_user,
                           ticket=test_ticket_comments,
                           content='Test comment 2')
        comment2.save()

        reply1 = Comment(user=self.test_user,
                         ticket=test_ticket_comments,
                         reply_to=comment2,
                         content='Test comment 3')
        reply1.save()

        self.assertEqual(0, test_ticket_wo_comments.no_comments)
        self.assertEqual(3, test_ticket_comments.no_comments)
    def test_no_votes_returns_correct_numbers(self):
        '''
        Test the no_votes property returns the correct number of votes.
        '''
        test_ticket_bug = Ticket(user=self.test_user,
                                 title='Bug Votes',
                                 content='Test content')
        test_ticket_bug.save()

        test_ticket_feature = Ticket(user=self.test_user,
                                     title='Feature Votes',
                                     content='Test content')
        test_ticket_feature.save()

        for number in range(3):
            voter = User.objects.create_user(
                username='******'.format(number),
                email='test{}@test.com'.format(number),
                password='******')
            bug_vote = Vote(user=voter, ticket=test_ticket_bug)
            bug_vote.save()
            feature_vote = Vote(user=voter,
                                ticket=test_ticket_feature,
                                count=3)
            feature_vote.save()

        ticket_zero_votes = Ticket.objects.get(id=self.bug_ticket.id)
        self.assertEqual(0, ticket_zero_votes.no_votes)
        ticket_three_votes = Ticket.objects.get(id=test_ticket_bug.id)
        self.assertEqual(3, ticket_three_votes.no_votes)
        ticket_nine_votes = Ticket.objects.get(id=test_ticket_feature.id)
        self.assertEqual(9, ticket_nine_votes.no_votes)
    def test_no_views_returns_correct_numbers(self):
        '''
        Test the no_views property returns the correct number of views.
        '''
        test_ticket = Ticket(user=self.test_user,
                             title='Views',
                             content='Test content')
        test_ticket.save()

        test_ticket = Ticket.objects.get(id=test_ticket.id)
        self.assertEqual(0, test_ticket.no_views)

        self.client.get(str(test_ticket.get_absolute_url()))
        test_ticket = Ticket.objects.get(id=test_ticket.id)
        self.assertEqual(1, test_ticket.no_views)
Beispiel #33
0
 def test_updating_cart_view(self):
     ticket = Ticket(variety='F', issue='some feature')
     ticket.save()
     self.client.get(reverse('cart:add_to_cart', args=(ticket.id, )))
     page = self.client.post(reverse('cart:add_to_cart',
                                     args=(str(ticket.id))),
                             data={
                                 "donation": 20,
                                 'update': True
                             })
     session = self.client.session
     self.assertEqual(session[settings.CART_SESSION_ID],
                      {'1': {
                          'donation': '20'
                      }})
Beispiel #34
0
 def create_ticket(self, doge_user, user):
     admins = User.objects.filter(is_staff=True)
     new_ticket = Ticket(
         author=doge_user,
         title=self.cleaned_data.get('title'),
         priority=self.cleaned_data.get('priority'),
         assigned_to=choice(admins),
         pub_date=datetime.datetime.now(),
     )
     new_ticket.save()
     new_response = Response(
         author=user,
         linked_to=new_ticket,
         response=self.cleaned_data.get('problem'),
         pub_date=datetime.datetime.now(),
     )
     new_response.save()
     return new_ticket
Beispiel #35
0
 def create_moderation_ticket(self):
     ticket = Ticket()
     ticket.title = 'Moderate sound %s' % self.original_filename
     ticket.source = TICKET_SOURCE_NEW_SOUND
     ticket.status = TICKET_STATUS_NEW
     ticket.queue = Queue.objects.get(name='sound moderation')
     ticket.sender = self.user
     lc = LinkedContent()
     lc.content_object = self
     lc.save()
     ticket.content = lc
     ticket.save()
     tc = TicketComment()
     tc.sender = self.user
     tc.text = "I've uploaded %s. Please moderate!" % self.original_filename
     tc.ticket = ticket
     tc.save()
Beispiel #36
0
def describe_sounds(request):
    sounds_to_process = []
    sounds = request.session.get('describe_sounds', False)
    selected_license = request.session.get('describe_license', False)
    selected_pack = request.session.get('describe_pack', False)

    # This is to prevent people browsing to the /home/describe/sounds page
    # without going through the necessary steps.
    # selected_pack can be False, but license and sounds have to be picked at least
    if not (sounds):
        msg = 'Please pick at least one sound.'
        messages.add_message(request, messages.WARNING, msg)
        return HttpResponseRedirect(reverse('accounts-describe'))

    # So SOUNDS_PER_DESCRIBE_ROUND is available in the template
    sounds_per_round = SOUNDS_PER_DESCRIBE_ROUND
    sounds_to_describe = sounds[0:sounds_per_round]
    forms = []
    request.session['describe_sounds_number'] = len(request.session.get('describe_sounds'))

    # If there are no files in the session redirect to the first describe page
    if len(sounds_to_describe) <= 0:
        msg = 'You have finished describing your sounds.'
        messages.add_message(request, messages.WARNING, msg)
        return HttpResponseRedirect(reverse('accounts-describe'))

    if request.method == 'POST':
        # first get all the data
        for i in range(len(sounds_to_describe)):
            prefix = str(i)
            forms.append({})
            forms[i]['sound'] = sounds_to_describe[i]
            forms[i]['description'] = SoundDescriptionForm(request.POST, prefix=prefix)
            forms[i]['geotag'] = GeotaggingForm(request.POST, prefix=prefix)
            forms[i]['pack'] = PackForm(Pack.objects.filter(user=request.user),
                                        request.POST,
                                        prefix=prefix)
            forms[i]['license'] = NewLicenseForm(request.POST, prefix=prefix)
        # validate each form
        for i in range(len(sounds_to_describe)):
            for f in ['license', 'geotag', 'pack', 'description']:
                if not forms[i][f].is_valid():
                    return render_to_response('accounts/describe_sounds.html',
                                              locals(),
                                              context_instance=RequestContext(request))
        # all valid, then create sounds and moderation tickets
                
        dirty_packs = []
        for i in range(len(sounds_to_describe)):
            sound = Sound()
            sound.user = request.user
            sound.original_filename = forms[i]['description'].cleaned_data['name']
            sound.original_path = forms[i]['sound'].full_path
            sound.filesize = os.path.getsize(sound.original_path)

            try:
                sound.md5 = md5file(forms[i]['sound'].full_path)
            except IOError:
                messages.add_message(request, messages.ERROR, 'Something went wrong with accessing the file %s.' % sound.original_path)
                continue
            sound.type = get_sound_type(sound.original_path)
            # check if file exists or not
            try:
                existing_sound = Sound.objects.get(md5=sound.md5)
                msg = 'The file %s is already part of freesound and has been discarded, see <a href="%s">here</a>' % \
                    (forms[i]['sound'].name, reverse('sound', args=[existing_sound.user.username, existing_sound.id]))
                messages.add_message(request, messages.WARNING, msg)
                os.remove(forms[i]['sound'].full_path)
                continue
            except Sound.DoesNotExist, e:
                pass

            # set the license
            sound.license = forms[i]['license'].cleaned_data['license']
            sound.save()
            # now move the original
            orig = os.path.splitext(os.path.basename(sound.original_filename))[0]
            sound.base_filename_slug = "%d__%s__%s" % (sound.id, slugify(sound.user.username), slugify(orig))
            new_original_path = sound.locations("path")
            if sound.original_path != new_original_path:
                try:
                    os.makedirs(os.path.dirname(new_original_path))
                except OSError:
                    pass
                try:
                    shutil.move(sound.original_path, new_original_path)
                    #shutil.copy(sound.original_path, new_original_path)
                except IOError, e:
                    logger.info("failed to move file from %s to %s" % (sound.original_path, new_original_path), e)
                logger.info("moved original file from %s to %s" % (sound.original_path, new_original_path))
                sound.original_path = new_original_path
                sound.save()

            # set the pack (optional)
            pack = forms[i]['pack'].cleaned_data.get('pack', False)
            new_pack = forms[i]['pack'].cleaned_data.get('new_pack', False)
            if not pack and new_pack:
                pack, created = Pack.objects.get_or_create(user=request.user, name=new_pack)
            if pack:
                sound.pack = pack
                dirty_packs.append(sound.pack)
            # set the geotag (if 'lat' is there, all fields are)
            data = forms[i]['geotag'].cleaned_data
            if not data.get('remove_geotag') and data.get('lat'):
                geotag = GeoTag(user=request.user,
                                lat=data.get('lat'),
                                lon=data.get('lon'),
                                zoom=data.get('zoom'))
                geotag.save()
                sound.geotag = geotag
            # set the tags and descriptions
            data = forms[i]['description'].cleaned_data
            sound.description = data.get('description', '')
            sound.set_tags(data.get('tags'))
            sound.save()
            # remember to process the file
            sounds_to_process.append(sound)
            if request.user.profile.is_whitelisted:
                sound.moderation_state = 'OK'
                sound.save()
                messages.add_message(request, messages.INFO,
                                     'File <a href="%s">%s</a> has been described and has been added to freesound.' % \
                                     (sound.get_absolute_url(), forms[i]['sound'].name))
            else:
                # create moderation ticket!
                ticket = Ticket()
                ticket.title = 'Moderate sound %s' % sound.original_filename
                ticket.source = TICKET_SOURCE_NEW_SOUND
                ticket.status = TICKET_STATUS_NEW
                ticket.queue = Queue.objects.get(name='sound moderation')
                ticket.sender = request.user
                lc = LinkedContent()
                lc.content_object = sound
                lc.save()
                ticket.content = lc
                ticket.save()
                tc = TicketComment()
                tc.sender = request.user
                tc.text = "I've uploaded %s. Please moderate!" % sound.original_filename
                tc.ticket = ticket
                tc.save()
                # add notification that the file was described successfully
                messages.add_message(request, messages.INFO,
                                     'File <a href="%s">%s</a> has been described and is awaiting moderation.' % \
                                     (sound.get_absolute_url(), forms[i]['sound'].name))
            # compute crc
            # TEMPORARY
            try:
                sound.compute_crc()
            except:
                pass
Beispiel #37
0
def profile_tickets(request, username):
    # Look up the user record who corresponds to this profile
    profile = UserProfile.get_user_profile_from_username(username)
    if profile:
        user = profile.user
    else:
        raise Http404('The username {} does not exist'.format(username))

    # If the user looking at this profile is its owner, then we want to render a couple edit buttons
    if request.user == user:
        is_owner = True
    else:
        is_owner = False

    user_location = user.location

    most_recent_review = user.most_recent_review()

    user_info = {'name': user,
                 'age': user.age(),
                 'city': user_location.city,
                 'state': user_location.state,
                 'rating': user.rating,
                 'username': username,
                 }

    try:
        user_info['profile_picture'] = user.profile_picture
    except ObjectDoesNotExist:
        pass

    if most_recent_review:
        reviewer_location = most_recent_review.reviewer.location
        reviewer_city, reviewer_state = reviewer_location.city, reviewer_location.state
        most_recent_review_info = {'name': most_recent_review.reviewer.get_short_name(),
                                   'age': most_recent_review.reviewer.age(),
                                   'city': reviewer_city,
                                   'state': reviewer_state,
                                   'contents': most_recent_review.contents,
                                   'rating': most_recent_review.rating
                                   }
    else:
        most_recent_review_info = None

    # Grab every ticket that this user has posted or has bid on
    upcoming_tickets = Ticket.upcoming_tickets(user)
    available_tickets = Ticket.available_tickets(user)
    in_progress_tickets = Ticket.in_progress_ticket(user)
    past_tickets = Ticket.past_tickets(user)

    return render(request,
                  'user_profile/profile_tickets.html',
                  {'user_info': user_info,
                   'is_owner': is_owner,
                   'upcoming_tickets': upcoming_tickets,
                   'available_tickets': available_tickets,
                   'in_progress_tickets': in_progress_tickets,
                   'past_tickets': past_tickets,
                   'most_recent_review_info': most_recent_review_info,
                   'form_settings': profile_answer_form_settings,
                   },
                  content_type='text/html',
                  )
Beispiel #38
0
    sound.set_tags(sound_fields['tags'])
    #sound.set_tags([t.lower() for t in sound_fields['tags'].split(" ") if t])

    # 8.5 set uploaded apiv2 client
    sound.uploaded_with_apiv2_client = apiv2_client

    # 9 save!
    sound.save()

    # 10 create moderation tickets if needed
    if user.profile.is_whitelisted:
        sound.moderation_state = 'OK'
        sound.save()
    else:
        # create moderation ticket!
        ticket = Ticket()
        ticket.title = 'Moderate sound %s' % sound.original_filename
        ticket.source = TICKET_SOURCE_NEW_SOUND
        ticket.status = TICKET_STATUS_NEW
        ticket.queue = Queue.objects.get(name='sound moderation')
        ticket.sender = user
        lc = LinkedContent()
        lc.content_object = sound
        lc.save()
        ticket.content = lc
        ticket.save()
        tc = TicketComment()
        tc.sender = user
        tc.text = "I've uploaded %s. Please moderate!" % sound.original_filename
        tc.ticket = ticket
        tc.save()