Funding offer staff preview.
[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                 if request.user.is_staff:
81                     offers = Offer.objects.all()
82                 else:
83                     offers = Offer.public()
84                 self.object = get_object_or_404(offers, slug=slug)
85             else:
86                 self.object = Offer.current()
87                 if self.object is None:
88                     raise Http404
89         return super(OfferDetailView, self).dispatch(request, slug)
90
91     def get_form(self, form_class=None):
92         if form_class is None:
93             form_class = self.get_form_class()
94         if self.request.method == 'POST':
95             return form_class(self.object, self.request.POST)
96         else:
97             return form_class(self.object, initial={'amount': app_settings.DEFAULT_AMOUNT})
98
99     def get_context_data(self, **kwargs):
100         ctx = super(OfferDetailView, self).get_context_data(**kwargs)
101         ctx['object'] = self.object
102         if self.object.is_current():
103             ctx['funding_no_show_current'] = True
104         return ctx
105
106     def form_valid(self, form):
107         funding = form.save()
108         # Skip getpaid.forms.PaymentMethodForm, go directly to the broker.
109         payment = Payment.create(funding, self.backend)
110         gateway_url_tuple = payment.get_processor()(payment).get_gateway_url(self.request)
111         payment.change_status('in_progress')
112         return redirect(gateway_url_tuple[0])
113
114
115 class CurrentView(OfferDetailView):
116     @csrf_exempt
117     def dispatch(self, request, slug=None):
118         self.object = Offer.current()
119         if self.object is None:
120             return redirect(reverse('funding'))
121         elif slug != self.object.slug:
122             return redirect(reverse('funding_current', args=[self.object.slug]))
123         return super(CurrentView, self).dispatch(request, slug)
124
125
126 class OfferListView(ListView):
127     queryset = Offer.public()
128
129     def get_context_data(self, **kwargs):
130         ctx = super(OfferListView, self).get_context_data(**kwargs)
131         ctx['funding_no_show_current'] = True
132         return ctx
133
134
135 class ThanksView(TemplateView):
136     template_name = "funding/thanks.html"
137
138     def get_context_data(self, **kwargs):
139         ctx = super(ThanksView, self).get_context_data(**kwargs)
140         ctx['offer'] = Offer.current()
141         ctx['funding_no_show_current'] = True
142         return ctx
143
144
145 class NoThanksView(TemplateView):
146     template_name = "funding/no_thanks.html"
147
148
149 class DisableNotifications(TemplateView):
150     template_name = "funding/disable_notifications.html"
151
152     @csrf_exempt
153     def dispatch(self, request):
154         self.object = get_object_or_404(Funding, email=request.GET.get('email'), notify_key=request.GET.get('key'))
155         return super(DisableNotifications, self).dispatch(request)
156
157     def post(self, *args, **kwargs):
158         self.object.disable_notifications()
159         return redirect(self.request.get_full_path())