315c3da49431973c18aa7d6e2fcaa28978a6d720
[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 import club.payu.views
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
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.request, self.object, self.request.POST)
96         else:
97             return form_class(self.request, 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         return redirect(funding.put())
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     template_name = 'funding/offer_list.html'
125     
126     def get_context_data(self, **kwargs):
127         ctx = super(OfferListView, self).get_context_data(**kwargs)
128         ctx['funding_no_show_current'] = True
129         return ctx
130
131
132 class ThanksView(TemplateView):
133     template_name = "funding/thanks.html"
134
135     def get_context_data(self, **kwargs):
136         ctx = super(ThanksView, self).get_context_data(**kwargs)
137         ctx['offer'] = Offer.current()
138         ctx['funding_no_show_current'] = True
139         return ctx
140
141
142 class NoThanksView(TemplateView):
143     template_name = "funding/no_thanks.html"
144
145
146 class DisableNotifications(TemplateView):
147     template_name = "funding/disable_notifications.html"
148
149     @csrf_exempt
150     def dispatch(self, request):
151         self.object = get_object_or_404(Funding, email=request.GET.get('email'), notify_key=request.GET.get('key'))
152         return super(DisableNotifications, self).dispatch(request)
153
154     def post(self, *args, **kwargs):
155         self.object.disable_notifications()
156         return redirect(self.request.get_full_path())
157
158
159 @login_required
160 def claim(request, key):
161     funding = get_object_or_404(Funding, notify_key=key)
162     if funding.user is None:
163         funding.user = request.user
164         funding.save()
165     return HttpResponseRedirect(
166         funding.offer.book.get_absolute_url() if funding.offer.book is not None
167         else funding.offer.get_absolute_url()
168     )
169
170
171 class PayUNotifyView(club.payu.views.NotifyView):
172     order_model = Funding
173