fixes
[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
75     def get_template_names(self):
76         if self.request.EXPERIMENTS['layout'].value:
77             return 'funding/2022/offer_detail.html'
78         else:
79             return "funding/offer_detail.html"
80
81     @csrf_exempt
82     def dispatch(self, request, slug=None):
83         if getattr(self, 'object', None) is None:
84             if slug:
85                 if request.user.is_staff:
86                     offers = Offer.objects.all()
87                 else:
88                     offers = Offer.public()
89                 self.object = get_object_or_404(offers, slug=slug)
90             else:
91                 self.object = Offer.current()
92                 if self.object is None:
93                     raise Http404
94         return super(OfferDetailView, self).dispatch(request, slug)
95
96     def get_form(self, form_class=None):
97         if form_class is None:
98             form_class = self.get_form_class()
99         if self.request.method == 'POST':
100             return form_class(self.request, self.object, self.request.POST)
101         else:
102             return form_class(self.request, self.object, initial={'amount': app_settings.DEFAULT_AMOUNT})
103
104     def get_context_data(self, **kwargs):
105         ctx = super(OfferDetailView, self).get_context_data(**kwargs)
106         ctx['object'] = self.object
107         if self.object.is_current():
108             ctx['funding_no_show_current'] = True
109         return ctx
110
111     def form_valid(self, form):
112         funding = form.save()
113         return redirect(funding.put())
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_template_names(self):
131         if self.request.EXPERIMENTS['layout'].value:
132             return 'funding/2022/offer_list.html'
133         return 'funding/offer_list.html'
134     
135     def get_context_data(self, **kwargs):
136         ctx = super(OfferListView, self).get_context_data(**kwargs)
137         ctx['funding_no_show_current'] = True
138         return ctx
139
140
141 class ThanksView(TemplateView):
142     template_name = "funding/thanks.html"
143
144     def get_context_data(self, **kwargs):
145         ctx = super(ThanksView, self).get_context_data(**kwargs)
146         ctx['offer'] = Offer.current()
147         ctx['funding_no_show_current'] = True
148         return ctx
149
150
151 class NoThanksView(TemplateView):
152     template_name = "funding/no_thanks.html"
153
154
155 class DisableNotifications(TemplateView):
156     template_name = "funding/disable_notifications.html"
157
158     @csrf_exempt
159     def dispatch(self, request):
160         self.object = get_object_or_404(Funding, email=request.GET.get('email'), notify_key=request.GET.get('key'))
161         return super(DisableNotifications, self).dispatch(request)
162
163     def post(self, *args, **kwargs):
164         self.object.disable_notifications()
165         return redirect(self.request.get_full_path())
166
167
168 @login_required
169 def claim(request, key):
170     funding = get_object_or_404(Funding, notify_key=key)
171     if funding.user is None:
172         funding.user = request.user
173         funding.save()
174     return HttpResponseRedirect(
175         funding.offer.book.get_absolute_url() if funding.offer.book is not None
176         else funding.offer.get_absolute_url()
177     )
178
179
180 class PayUNotifyView(club.payu.views.NotifyView):
181     order_model = Funding
182