Language menu move.
[wolnelektury.git] / src / funding / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django.http import Http404
5 from django.shortcuts import get_object_or_404, redirect, render
6 from django.urls import reverse
7 from django.views.decorators.csrf import csrf_exempt
8 from django.views.generic import TemplateView, FormView, ListView
9 from getpaid.models import Payment
10 from . import app_settings
11 from .forms import FundingForm
12 from .models import Offer, Spent, Funding
13
14
15 def mix(*streams):
16     substreams = []
17     for stream, read_date, tag in streams:
18         iterstream = iter(stream)
19         try:
20             item = next(iterstream)
21         except StopIteration:
22             pass
23         else:
24             substreams.append([read_date(item), item, iterstream, read_date, tag])
25     while substreams:
26         i, substream = max(enumerate(substreams), key=lambda x: x[1][0])
27         yield substream[4], substream[1]
28         try:
29             item = next(substream[2])
30         except StopIteration:
31             del substreams[i]
32         else:
33             substream[0:2] = [substream[3](item), item]
34
35
36 class WLFundView(TemplateView):
37     template_name = "funding/wlfund.html"
38
39     def get_context_data(self):
40         def add_total(total, it):
41             for tag, e in it:
42                 e.total = total
43                 if tag == 'spent':
44                     total += e.amount
45                 else:
46                     total -= e.wlfund
47                 yield tag, e
48
49         ctx = super(WLFundView, self).get_context_data()
50         offers = []
51
52         for o in Offer.past():
53             if o.is_win():
54                 o.wlfund = o.sum() - o.target
55                 if o.wlfund > 0:
56                     offers.append(o)
57             else:
58                 o.wlfund = o.sum()
59                 if o.wlfund > 0:
60                     offers.append(o)
61         amount = sum(o.wlfund for o in offers) - sum(o.amount for o in Spent.objects.all())
62
63         ctx['amount'] = amount
64         ctx['log'] = add_total(amount, mix(
65             (offers, lambda x: x.end, 'offer'),
66             (Spent.objects.all().select_related(), lambda x: x.timestamp, 'spent'),
67         ))
68         return ctx
69
70
71 class OfferDetailView(FormView):
72     form_class = FundingForm
73     template_name = "funding/offer_detail.html"
74     backend = 'getpaid.backends.payu'
75
76     @csrf_exempt
77     def dispatch(self, request, slug=None):
78         if getattr(self, 'object', None) is None:
79             if slug:
80                 self.object = get_object_or_404(Offer.public(), slug=slug)
81             else:
82                 self.object = Offer.current()
83                 if self.object is None:
84                     raise Http404
85         return super(OfferDetailView, self).dispatch(request, slug)
86
87     def get_form(self, form_class=None):
88         if form_class is None:
89             form_class = self.get_form_class()
90         if self.request.method == 'POST':
91             return form_class(self.object, self.request.POST)
92         else:
93             return form_class(self.object, initial={'amount': app_settings.DEFAULT_AMOUNT})
94
95     def get_context_data(self, **kwargs):
96         ctx = super(OfferDetailView, self).get_context_data(**kwargs)
97         ctx['object'] = self.object
98         if self.object.is_current():
99             ctx['funding_no_show_current'] = True
100         return ctx
101
102     def form_valid(self, form):
103         funding = form.save()
104         # Skip getpaid.forms.PaymentMethodForm, go directly to the broker.
105         payment = Payment.create(funding, self.backend)
106         gateway_url_tuple = payment.get_processor()(payment).get_gateway_url(self.request)
107         payment.change_status('in_progress')
108         return redirect(gateway_url_tuple[0])
109
110
111 class CurrentView(OfferDetailView):
112     @csrf_exempt
113     def dispatch(self, request, slug=None):
114         self.object = Offer.current()
115         if self.object is None:
116             return redirect(reverse('funding'))
117         elif slug != self.object.slug:
118             return redirect(reverse('funding_current', args=[self.object.slug]))
119         return super(CurrentView, self).dispatch(request, slug)
120
121
122 class OfferListView(ListView):
123     queryset = Offer.public()
124
125     def get_context_data(self, **kwargs):
126         ctx = super(OfferListView, self).get_context_data(**kwargs)
127         ctx['funding_no_show_current'] = True
128         return ctx
129
130
131 class ThanksView(TemplateView):
132     template_name = "funding/thanks.html"
133
134     def get_context_data(self, **kwargs):
135         ctx = super(ThanksView, self).get_context_data(**kwargs)
136         ctx['offer'] = Offer.current()
137         ctx['funding_no_show_current'] = True
138         return ctx
139
140
141 class NoThanksView(TemplateView):
142     template_name = "funding/no_thanks.html"
143
144
145 class DisableNotifications(TemplateView):
146     template_name = "funding/disable_notifications.html"
147
148     @csrf_exempt
149     def dispatch(self, request):
150         self.object = get_object_or_404(Funding, email=request.GET.get('email'), notify_key=request.GET.get('key'))
151         return super(DisableNotifications, self).dispatch(request)
152
153     def post(self, *args, **kwargs):
154         self.object.disable_notifications()
155         return redirect(self.request.get_full_path())