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