summaryrefslogtreecommitdiffstats
path: root/combo/apps/lingo/views.py
blob: 80362a1a7c8b4d7bd918ee7cca6485f4a44c1552 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
# -*- coding: utf-8 -*-
# lingo - basket and payment system
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from decimal import Decimal, ROUND_HALF_UP
import json
import logging
import requests

from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest
from django.http import HttpResponseForbidden, Http404, JsonResponse
from django.template.response import TemplateResponse
from django.utils import timezone, dateparse, six
from django.utils.encoding import force_text
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View, DetailView, ListView, TemplateView
from django.conf import settings
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from django.db.transaction import atomic
from django.utils.encoding import smart_text

import eopayment

from combo.data.models import Page
from combo.utils import check_request_signature, aes_hex_decrypt, DecryptionError
from combo.profile.utils import get_user_from_name_id

from .models import (Regie, BasketItem, Transaction, TransactionOperation,
                     LingoBasketCell, SelfDeclaredInvoicePayment, PaymentBackend)

def get_eopayment_object(request, regie_or_payment_backend):
    payment_backend = regie_or_payment_backend
    if isinstance(regie_or_payment_backend, Regie):
        payment_backend = regie_or_payment_backend.payment_backend
    options = payment_backend.service_options
    options.update({
        'automatic_return_url': request.build_absolute_uri(
                reverse('lingo-callback-payment-backend',
                        kwargs={'payment_backend_pk': payment_backend.id})),
        'normal_return_url': request.build_absolute_uri(
                reverse('lingo-return-payment-backend',
                        kwargs={'payment_backend_pk': payment_backend.id})),
    })
    return eopayment.Payment(payment_backend.service, options)


def get_basket_url():
    basket_cell = LingoBasketCell.objects.filter(page__snapshot__isnull=True).first()
    if basket_cell:
        return basket_cell.page.get_online_url()
    return '/'


def lingo_check_request_signature(request):
    keys = []
    if getattr(settings, 'LINGO_API_SIGN_KEY', None):
        keys = [settings.LINGO_API_SIGN_KEY]
    return check_request_signature(request, keys=keys)


class LocaleDecimal(Decimal):
    # accept , instead of . for French users comfort
    def __new__(cls, value="0", *args, **kwargs):
        if isinstance(value, six.string_types) and settings.LANGUAGE_CODE.startswith('fr-'):
            value = value.replace(',', '.')
        return super(LocaleDecimal, cls).__new__(cls, value, *args, **kwargs)


class RegiesApiView(ListView):
    model = Regie

    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='application/json')
        data = {'data': [x.as_api_dict() for x in self.get_queryset()]}
        json_str = json.dumps(data)
        if 'jsonpCallback' in request.GET:
            json_str = '%s(%s);' % (request.GET['jsonpCallback'], json_str)
        response.write(json_str)
        return response


class AddBasketItemApiView(View):
    http_method_names = ['post', 'options']

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(AddBasketItemApiView, self).dispatch(*args, **kwargs)

    def get_amount(self, amount):
        if isinstance(amount, list):
            d = Decimal(sum([LocaleDecimal(a) for a in amount]))
        else:
            d = LocaleDecimal(amount)
        return d.quantize(Decimal('0.01'), ROUND_HALF_UP)

    def post(self, request, *args, **kwargs):
        if not lingo_check_request_signature(request):
            return HttpResponseForbidden()

        request_body = json.loads(force_text(self.request.body))
        extra = request_body.get('extra', {})

        if not 'amount' in request.GET and not 'amount' in request_body and \
                not 'amount' in extra:
            raise Exception('missing amount parameter')

        item = BasketItem(amount=0)
        try:
            item.amount = self.get_amount(request.GET.getlist('amount'))
        except ArithmeticError:
            return HttpResponseBadRequest('invalid value for "amount" in query string')

        if request_body.get('amount'):
            try:
                item.amount += self.get_amount(request_body['amount'])
            except ArithmeticError:
                return HttpResponseBadRequest('invalid value for "amount" in payload')

        if extra.get('amount'):
            try:
                item.amount += self.get_amount(extra['amount'])
            except ArithmeticError:
                return HttpResponseBadRequest('invalid value for "amount" in extra payload')

        if 'extra' in request_body:
            item.request_data = request_body.get('extra')
        else:
            item.request_data = request_body

        try:
            if request.GET.get('NameId'):
                user = get_user_from_name_id(request.GET.get('NameId'), raise_on_missing=True)
            elif request.GET.get('email'):
                user = User.objects.get(email=request.GET.get('email'))
            else:
                raise Exception('no user specified')
        except User.DoesNotExist:
            raise Exception('unknown user')

        item.user = user
        if request.GET.get('regie_id'):
            try:
                item.regie = Regie.objects.get(slug=request.GET.get('regie_id'))
            except Regie.DoesNotExist:
                try:
                    item.regie = Regie.objects.get(id=int(request.GET.get('regie_id')))
                except (ValueError, Regie.DoesNotExist):
                    return HttpResponseBadRequest('Unknown regie')
        else:
            try:
                item.regie = Regie.objects.get(is_default=True)
            except Regie.DoesNotExist:
                # if there's no default regie, use the first one we get from
                # the database...
                item.regie = Regie.objects.all()[0]

        if request.GET.get('cancellable') == 'no':
            item.user_cancellable = False

        item.subject = request_body.get('display_name')
        item.source_url = request_body.get('url') or ''

        if 'capture_date' in request_body:
            try:
                # parse_date returns None when the string format is invalid
                capture_date_err = False
                item.capture_date = dateparse.parse_date(request_body['capture_date'])
            except TypeError:
                capture_date_err = True
            if item.capture_date is None or capture_date_err:
                return HttpResponseBadRequest(
                    'Bad format for capture date, it should be yyyy-mm-dd.')

        item.save()
        item.regie.compute_extra_fees(user=item.user)

        payment_url = reverse('basket-item-pay-view', kwargs={'item_id': item.id})
        return JsonResponse({'result': 'success', 'id': str(item.id),
                             'payment_url': request.build_absolute_uri(payment_url)})


class RemoveBasketItemApiView(View):
    http_method_names = ['post', 'options']

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(RemoveBasketItemApiView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        if not lingo_check_request_signature(request):
            return HttpResponseForbidden()

        request_body = json.loads(force_text(self.request.body))

        if not 'basket_item_id' in request_body:
            raise Exception('missing basket_item_id parameter')

        try:
            if request.GET.get('NameId'):
                user = get_user_from_name_id(request.GET.get('NameId'), raise_on_missing=True)
                if user is None:
                    raise User.DoesNotExist()
            elif request.GET.get('email'):
                user = User.objects.get(email=request.GET.get('email'))
            else:
                raise Exception('no user specified')
        except User.DoesNotExist:
            raise Exception('unknown user')

        item = BasketItem.objects.get(id=request_body.get('basket_item_id'),
                user=user, cancellation_date__isnull=True)
        notify_origin = bool(request_body.get('notify', 'false') == 'true')
        item.notify_cancellation(notify_origin=notify_origin)

        response = HttpResponse(content_type='application/json')
        response.write(json.dumps({'result': 'success'}))
        return response


class ValidateTransactionApiView(View):
    http_method_names = ['post', 'options']

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(ValidateTransactionApiView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        if not lingo_check_request_signature(request):
            return HttpResponseForbidden()

        logger = logging.getLogger(__name__)
        try:
            transaction = Transaction.objects.get(id=request.GET['transaction_id'])
        except Transaction.DoesNotExist:
            logger.warning(u'received validate request for unknown transaction %s',
                           request.GET['transaction_id'])
            raise Http404

        payment = get_eopayment_object(request, transaction.regie)
        amount = LocaleDecimal(request.GET['amount'])

        logger.info(u'validating amount %s for transaction %s', amount, smart_text(transaction.id))
        try:
            result = payment.backend.validate(amount, transaction.bank_data)
        except eopayment.ResponseError as e:
            logger.error(u'failed in validation operation: %s', e)
            response = HttpResponse(content_type='application/json')
            response.write(json.dumps({'err': 1, 'e': force_text(e)}))
            return response

        logger.info(u'bank validation result: %r', result)
        operation = TransactionOperation(transaction=transaction,
                kind='validation', amount=amount, bank_result=result)
        operation.save()

        response = HttpResponse(content_type='application/json')
        response.write(json.dumps({'err': 0, 'extra': result}))
        return response


class CancelTransactionApiView(View):
    http_method_names = ['post', 'options']

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(CancelTransactionApiView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        if not lingo_check_request_signature(request):
            return HttpResponseForbidden()

        logger = logging.getLogger(__name__)
        try:
            transaction = Transaction.objects.get(id=request.GET['transaction_id'])
        except Transaction.DoesNotExist:
            logger.warning(u'received validate request for unknown transaction %s',
                           request.GET['transaction_id'])
            raise Http404

        payment = get_eopayment_object(request, transaction.regie)
        amount = LocaleDecimal(request.GET['amount'])

        logger.info(u'cancelling amount %s for transaction %s', amount, smart_text(transaction.id))
        try:
            result = payment.backend.cancel(amount, transaction.bank_data)
        except eopayment.ResponseError as e:
            logger.error(u'failed in cancel operation: %s', e)
            response = HttpResponse(content_type='application/json')
            response.write(json.dumps({'err': 1, 'e': force_text(e)}))
            return response

        logger.info(u'bank cancellation result: %r', result)
        operation = TransactionOperation(transaction=transaction,
                kind='cancellation', amount=amount, bank_result=result)
        operation.save()

        response = HttpResponse(content_type='application/json')
        response.write(json.dumps({'err': 0, 'extra': result}))
        return response


class PayMixin(object):
    @atomic
    def handle_payment(self, request, regie, items, remote_items, next_url='/', email=''):
        if remote_items:
            total_amount = sum([x.amount for x in remote_items])
        else:
            total_amount = sum([x.amount for x in items])

        if total_amount < regie.payment_min_amount:
            messages.warning(request, _(u'Minimal payment amount is %s €.') % regie.payment_min_amount)
            return HttpResponseRedirect(next_url)

        for item in items:
            if item.regie != regie:
                messages.error(request, _(u'Invalid grouping for basket items.'))
                return HttpResponseRedirect(next_url)
        user = request.user if request.user.is_authenticated() else None
        transaction = Transaction()
        if user:
            transaction.user = user
            email = user.email
            firstname = user.first_name
            lastname = user.last_name
        else:
            transaction.user = None
            firstname = ''
            lastname = ''

        transaction.save()
        transaction.regie = regie
        transaction.items = items
        transaction.remote_items = ','.join([x.id for x in remote_items])
        transaction.status = 0
        transaction.amount = total_amount

        payment = get_eopayment_object(request, regie)
        kwargs = {
            'email': email, 'first_name': firstname, 'last_name': lastname
        }
        if items:
            capture_date = items[0].capture_date
            if capture_date:
                kwargs['capture_date'] = capture_date
        if regie.transaction_options:
            kwargs.update(regie.transaction_options)
        (order_id, kind, data) = payment.request(total_amount, **kwargs)
        logger = logging.getLogger(__name__)
        logger.info(u'emitted payment request with id %s', smart_text(order_id), extra={
            'eopayment_order_id': smart_text(order_id), 'eopayment_data': repr(data)})
        transaction.order_id = order_id
        transaction.save()

        # store the next url in session in order to be able to redirect to
        # it if payment is canceled
        request.session.setdefault('lingo_next_url',
                                   {})[order_id] = request.build_absolute_uri(next_url)
        request.session.modified = True

        if kind == eopayment.URL:
            return HttpResponseRedirect(data)
        elif kind == eopayment.FORM:
            return TemplateResponse(request, 'lingo/payment_form.html', {'form': data})

        raise NotImplementedError()


class PayView(PayMixin, View):
    def post(self, request, *args, **kwargs):
        regie_id = request.POST.get('regie')
        next_url = request.POST.get('next_url') or '/'
        user = request.user if request.user.is_authenticated() else None
        remote_items = []
        items = []
        if regie_id and Regie.objects.get(pk=regie_id).is_remote():
            regie = Regie.objects.get(pk=regie_id)
            # get all items data from regie webservice
            for item_id in request.POST.getlist('item'):
                remote_items.append(regie.get_invoice(user, item_id))
        else:
            if user is None:
                messages.error(request, _(u'Payment requires to be logged in.'))
                return HttpResponseRedirect(next_url)

            if not regie_id:
                # take all items but check they're from the same regie
                items = BasketItem.get_items_to_be_paid(user=user)
                regie_id = items[0].regie_id
                for item in items:
                    if item.regie_id != regie_id:
                        messages.error(request, _(u'Invalid grouping for basket items.'))
                        return HttpResponseRedirect(next_url)

            regie = Regie.objects.get(id=regie_id)
            regie.compute_extra_fees(user=user)
            items = BasketItem.get_items_to_be_paid(user=user).filter(regie=regie)

        if items:
            capture_date = items[0].capture_date
            for item in items:
                if item.capture_date != capture_date:
                    messages.error(
                        request,
                        _(u'Invalid grouping for basket items: different capture dates.'))
                    return HttpResponseRedirect(next_url)

        if not user and not request.POST.get('email'):
            messages.warning(request, _(u'You must give an email address.'))
            return HttpResponseRedirect(request.POST.get('item_url'))
        email = request.POST.get('email')

        # XXX: mark basket items as being processed (?)
        return self.handle_payment(request, regie, items, remote_items, next_url, email)


class BasketItemPayView(PayMixin, View):
    def get(self, request, *args, **kwargs):
        next_url = request.GET.get('next_url') or '/'
        if not (request.user and request.user.is_authenticated()):
            return HttpResponseForbidden(_('No item payment allowed for anonymous users.'))

        item = BasketItem.objects.get(pk=kwargs['item_id'])
        regie = item.regie
        if regie.extra_fees_ws_url:
            return HttpResponseForbidden(_('No item payment allowed as extra fees set.'))

        if item.user != request.user:
            return HttpResponseForbidden(_('Wrong item: payment not allowed.'))

        return self.handle_payment(request, regie, [item], [], next_url)


class PaymentException(Exception):
    pass


class UnsignedPaymentException(PaymentException):
    pass


class UnknownPaymentException(PaymentException):
    pass


class PaymentView(View):
    def handle_response(self, request, backend_response, **kwargs):
        if 'regie_pk' in kwargs:
            payment_backend = Regie.objects.get(id=kwargs['regie_pk']).payment_backend
        elif 'payment_backend_pk' in kwargs:
            payment_backend = PaymentBackend.objects.get(id=kwargs['payment_backend_pk'])
        else:
            raise Exception("A payment backend or regie primary key must be specified")

        payment = get_eopayment_object(request, payment_backend)
        logger = logging.getLogger(__name__)
        logger.info(u'received payment response: %r', backend_response)
        try:
            payment_response = payment.response(backend_response)
        except eopayment.ResponseError as e:
            logger.error(u'failed to process payment response: %s', e,
                         extra={'eopayment_raw_response': repr(backend_response)})
            raise PaymentException('Failed to process payment response')

        extra_info = {
            'eopayment_order_id': smart_text(payment_response.order_id),
            'eopayment_response': repr(payment_response),
        }
        for k, v in payment_response.bank_data.items():
            extra_info['eopayment_bank_data_' + k] = smart_text(v)
        if not payment_response.signed and not payment_response.result == eopayment.CANCELLED:
            # we accept unsigned cancellation requests as some platforms do
            # that :/
            logger.warning(u'received unsigned payment response with id %s',
                           smart_text(payment_response.order_id), extra=extra_info)
            raise UnsignedPaymentException('Received unsigned payment response')

        try:
            transaction = Transaction.objects.get(order_id=payment_response.order_id)
        except Transaction.DoesNotExist:
            logger.warning(u'received unknown payment response with id %s',
                           smart_text(payment_response.order_id), extra=extra_info)
            raise UnknownPaymentException('Received unknown payment response')
        else:
            extra_info['lingo_transaction_id'] = transaction.pk
            if transaction.user:
                # let hobo logger filter handle the extraction of user's infos
                extra_info['user'] = transaction.user
            logger.info(u'received known payment response with id %s',
                           smart_text(payment_response.order_id), extra=extra_info)

        if transaction.status == payment_response.result:
            # return early if transaction status didn't change (it means the
            # payment service sent the response both as server to server and
            # via the user browser and we already handled one).
            return transaction

        if transaction.status and transaction.status != payment_response.result:
            logger.info(u'received payment notification on existing transaction '
                            '(status: %s, new status: %s)' % (
                        transaction.status, payment_response.result))

        # check if transaction belongs to right regie
        if not transaction.regie.payment_backend == payment_backend:
            logger.warning(u'received payment for inappropriate payment backend '
                            '(expecteds: %s, received: %s)' % (
                                transaction.regie.payment_backend, payment_backend))
            raise PaymentException('Invalid payment regie')

        transaction.status = payment_response.result
        transaction.bank_transaction_id = payment_response.transaction_id
        transaction.bank_data = payment_response.bank_data
        transaction.end_date = timezone.now()
        transaction.save()

        if payment_response.result == eopayment.WAITING:
            # mark basket items as waiting for payment confirmation
            transaction.items.all().update(waiting_date=timezone.now())
            return transaction

        if payment_response.result == eopayment.CANCELLED:
            # mark basket items as no longer waiting so the user can restart a
            # payment.
            transaction.items.all().update(waiting_date=None)
            return transaction

        if payment_response.result not in (eopayment.PAID, eopayment.ACCEPTED):
            return transaction

        transaction.items.update(payment_date=transaction.end_date)

        for item in transaction.items.all():
            try:
                item.notify_payment()
            except:
                # ignore errors, it will be retried later on if it fails
                logger.exception('error in sync notification for basket item %s', item.id)

        if transaction.remote_items:
            transaction.first_notify_remote_items_of_payments()

        return transaction


class CallbackView(PaymentView):
    def handle_callback(self, request, backend_response, **kwargs):
        try:
            self.handle_response(request, backend_response, **kwargs)
        except UnknownPaymentException as e:
            raise Http404(force_text(e))
        except PaymentException as e:
            return HttpResponseBadRequest(force_text(e))
        return HttpResponse()

    def get(self, request, *args, **kwargs):
        return self.handle_callback(request, request.environ['QUERY_STRING'], **kwargs)

    def post(self, request, *args, **kwargs):
        return self.handle_callback(request, request.body, **kwargs)

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(CallbackView, self).dispatch(*args, **kwargs)


class ReturnView(PaymentView):
    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(ReturnView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        if not request.environ['QUERY_STRING']:
            return HttpResponseBadRequest('Missing query string')
        return self.handle_return(request, request.environ['QUERY_STRING'], **kwargs)

    def post(self, request, *args, **kwargs):
        return self.handle_return(request, request.body, **kwargs)

    def handle_return(self, request, backend_response, **kwargs):
        transaction = None
        try:
            transaction = self.handle_response(request, backend_response, **kwargs)
        except UnsignedPaymentException as e:
            # some payment backends do not sign return URLs, don't mark this as
            # an error, they will provide a notification to the callback
            # endpoint.
            pass
        except PaymentException as e:
            messages.error(request, _('We are sorry but the payment service '
                                      'failed to provide a correct answer.'))
            return HttpResponseRedirect(get_basket_url())

        if transaction and transaction.status in (eopayment.PAID, eopayment.ACCEPTED):
            messages.info(request, transaction.regie.get_text_on_success())

        if transaction and request.session.get('lingo_next_url'):
            redirect_url = request.session['lingo_next_url'].get(transaction.order_id)
            if redirect_url:
                return HttpResponseRedirect(redirect_url)

        # return to basket page if there are still items to pay
        if request.user.is_authenticated():
            remaining_basket_items = BasketItem.get_items_to_be_paid(
                user=self.request.user).count()
            if remaining_basket_items:
                return HttpResponseRedirect(get_basket_url())
        return HttpResponseRedirect('/')


class ItemDownloadView(View):
    http_method_names = [u'get']

    def get(self, request, *args, **kwargs):
        try:
            regie = Regie.objects.get(pk=kwargs['regie_id'])
        except Regie.DoesNotExist:
            raise Http404()

        try:
            item_id = aes_hex_decrypt(settings.SECRET_KEY, kwargs['item_crypto_id'])
        except DecryptionError:
            raise Http404()

        try:
            data = regie.get_invoice_pdf(request.user, item_id)
        except PermissionDenied:
            return HttpResponseForbidden()
        except DecryptionError as e:
            return Http404(str(e))

        if data.status_code != 200:
            logging.error('failed to retrieve invoice (%r)', data.status_code)
            messages.error(request, _('We are sorry but an error occured when retrieving the invoice.'))
            if self.request.META.get('HTTP_REFERER'):
                return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
            return HttpResponseRedirect('/')

        r = HttpResponse(data, content_type='application/pdf')
        r['Content-Disposition'] = 'attachment; filename="%s.pdf"' % item_id
        return r


class ItemView(TemplateView):
    http_method_names = [u'get']

    def get_context_data(self, **kwargs):
        ret = {'item_url': self.request.get_full_path()}

        try:
            regie = Regie.objects.get(pk=kwargs['regie_id'])
        except Regie.DoesNotExist:
            raise Http404()

        try:
            item_id = aes_hex_decrypt(settings.SECRET_KEY, kwargs['item_crypto_id'])
        except DecryptionError:
            raise Http404()

        item = regie.get_invoice(self.request.user, item_id)
        if not item:
            raise Http404(_('No item was found.'))
        if self.request.GET.get('page'):
            try:
                ret['page'] = Page.objects.get(pk=self.request.GET['page'])
            except (Page.DoesNotExist, ValueError):
                pass
        ret.update({'item': item, 'regie': regie})
        return ret

    def get_template_names(self):
        if self.request.is_ajax:
            return ['lingo/combo/item.html']
        return ['lingo/combo/invoice_fullpage.html']


class CancelItemView(DetailView):
    model = BasketItem
    template_name = 'lingo/combo/cancel-item.html'

    def get_context_data(self, **kwargs):
        context = super(CancelItemView, self).get_context_data(**kwargs)
        context['basket_url'] = get_basket_url()
        return context

    def get_queryset(self):
        user = self.request.user if self.request.user.is_authenticated() else None
        return BasketItem.get_items_to_be_paid(user=user)

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            messages.error(request, _('An error occured when removing the item. '
                                      '(no authenticated user)'))
            return HttpResponseRedirect(get_basket_url())
        if not self.get_object().user_cancellable:
            messages.error(request, _('This item cannot be removed.'))
            return HttpResponseRedirect(get_basket_url())
        try:
            self.get_object().notify_cancellation(notify_origin=True)
        except requests.exceptions.HTTPError:
            messages.error(request, _('An error occured when removing the item.'))
        return HttpResponseRedirect(get_basket_url())


class SelfInvoiceView(View):
    http_method_names = ['get',  'options']

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(SelfInvoiceView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        try:
            obj = SelfDeclaredInvoicePayment.objects.get(id=kwargs['cell_id'])
        except SelfDeclaredInvoicePayment.DoesNotExist:
            raise Http404()
        invoice_id = request.GET.get('invoice-number', '')
        invoice_amount = request.GET.get('invoice-amount', '')
        msg = None
        url = None
        try:
            invoice_amount = LocaleDecimal(invoice_amount)
        except ArithmeticError:
            invoice_amount = '-'
            msg = _('Sorry, the provided amount is invalid.')
        else:
            for regie in obj.get_regies():
                try:
                    invoice = regie.get_invoice(None, invoice_id, log_errors=False)
                except ObjectDoesNotExist:
                    continue
                if invoice.total_amount != invoice_amount:
                    continue
                url = reverse('view-item', kwargs={
                    'regie_id': regie.id, 'item_crypto_id': invoice.crypto_id})
                break
            else:
                msg = _('Sorry, no invoice were found with that number and amount.')
        if request.GET.get('ajax') == 'on':
            response = HttpResponse(content_type='application/json')
            response.write(json.dumps({'url': url, 'msg': msg and force_text(msg)}))
            return response
        if url:
            return HttpResponseRedirect(url)
        messages.warning(request, msg)
        return HttpResponseRedirect(request.GET.get('page_path') or '/')