Some preparation for upgrade.
[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.core.paginator import Paginator, InvalidPage
5 from django.http import Http404
6 from django.shortcuts import get_object_or_404, redirect, render
7 from django.urls import reverse
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 ssify import ssi_included
12 from ssify.utils import ssi_cache_control
13 from . import app_settings
14 from .forms import FundingForm
15 from .models import Offer, Spent, Funding
16
17
18 def mix(*streams):
19     substreams = []
20     for stream, read_date, tag in streams:
21         iterstream = iter(stream)
22         try:
23             item = next(iterstream)
24         except StopIteration:
25             pass
26         else:
27             substreams.append([read_date(item), item, iterstream, read_date, tag])
28     while substreams:
29         i, substream = max(enumerate(substreams), key=lambda x: x[1][0])
30         yield substream[4], substream[1]
31         try:
32             item = next(substream[2])
33         except StopIteration:
34             del substreams[i]
35         else:
36             substream[0:2] = [substream[3](item), item]
37
38
39 class WLFundView(TemplateView):
40     template_name = "funding/wlfund.html"
41
42     def get_context_data(self):
43         def add_total(total, it):
44             for tag, e in it:
45                 e.total = total
46                 if tag == 'spent':
47                     total += e.amount
48                 else:
49                     total -= e.wlfund
50                 yield tag, e
51
52         ctx = super(WLFundView, self).get_context_data()
53         offers = []
54
55         for o in Offer.past():
56             if o.is_win():
57                 o.wlfund = o.sum() - o.target
58                 if o.wlfund > 0:
59                     offers.append(o)
60             else:
61                 o.wlfund = o.sum()
62                 if o.wlfund > 0:
63                     offers.append(o)
64         amount = sum(o.wlfund for o in offers) - sum(o.amount for o in Spent.objects.all())
65
66         ctx['amount'] = amount
67         ctx['log'] = add_total(amount, mix(
68             (offers, lambda x: x.end, 'offer'),
69             (Spent.objects.all().select_related(), lambda x: x.timestamp, 'spent'),
70         ))
71         return ctx
72
73
74 class OfferDetailView(FormView):
75     form_class = FundingForm
76     template_name = "funding/offer_detail.html"
77     backend = 'getpaid.backends.payu'
78
79     @csrf_exempt
80     def dispatch(self, request, slug=None):
81         if getattr(self, 'object', None) is None:
82             if slug:
83                 self.object = get_object_or_404(Offer.public(), slug=slug)
84             else:
85                 self.object = Offer.current()
86                 if self.object is None:
87                     raise Http404
88         return super(OfferDetailView, self).dispatch(request, slug)
89
90     def get_form(self, form_class=None):
91         if form_class is None:
92             form_class = self.get_form_class()
93         if self.request.method == 'POST':
94             return form_class(self.object, self.request.POST)
95         else:
96             return form_class(self.object, initial={'amount': app_settings.DEFAULT_AMOUNT})
97
98     def get_context_data(self, **kwargs):
99         ctx = super(OfferDetailView, self).get_context_data(**kwargs)
100         ctx['object'] = self.object
101         ctx['page'] = self.request.GET.get('page', 1)
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())
160
161
162 def offer_bar(offer, link=False, closeable=False, show_title=True, show_title_calling=True, add_class=""):
163     if offer:
164         offer_sum = offer.sum()
165     else:
166         return {}
167     return {
168         'offer': offer,
169         'sum': offer_sum,
170         'is_current': offer.is_current(),
171         'is_win': offer_sum >= offer.target,
172         'missing': offer.target - offer_sum,
173         'percentage': 100 * offer_sum / offer.target,
174         'link': link,
175         'closeable': closeable,
176         'show_title': show_title,
177         'show_title_calling': show_title_calling,
178         'add_class': add_class,
179     }
180
181
182 def render_offer_bar(request, pk, link=False, closeable=False, show_title=True, show_title_calling=True, add_class=""):
183     offer = get_object_or_404(Offer, pk=pk)
184     return render(request, "funding/includes/funding.html",
185                   offer_bar(offer, link, closeable, show_title, show_title_calling, add_class))
186
187
188 @ssi_included(patch_response=[ssi_cache_control(must_revalidate=True)])
189 def top_bar(request, pk):
190     return render_offer_bar(request, pk, link=True, closeable=True, add_class="funding-top-header")
191
192
193 @ssi_included(patch_response=[ssi_cache_control(must_revalidate=True)])
194 def list_bar(request, pk):
195     return render_offer_bar(request, pk, link=True, show_title_calling=False)
196
197
198 @ssi_included(patch_response=[ssi_cache_control(must_revalidate=True)])
199 def detail_bar(request, pk):
200     return render_offer_bar(request, pk, show_title=False)
201
202
203 @ssi_included(patch_response=[ssi_cache_control(must_revalidate=True)])
204 def offer_status(request, pk):
205     offer = get_object_or_404(Offer, pk=pk)
206     return render(request, "funding/includes/offer_status.html", {'offer': offer})
207
208
209 @ssi_included(patch_response=[ssi_cache_control(must_revalidate=True)])
210 def offer_status_more(request, pk):
211     offer = get_object_or_404(Offer, pk=pk)
212     return render(request, "funding/includes/offer_status_more.html", {'offer': offer})
213
214
215 @ssi_included(patch_response=[ssi_cache_control(must_revalidate=True)])
216 def offer_fundings(request, pk, page):
217     offer = get_object_or_404(Offer, pk=pk)
218     fundings = offer.funding_payed()
219     paginator = Paginator(fundings, 10, 2)
220     try:
221         page_obj = paginator.page(int(page))
222     except InvalidPage:
223         raise Http404
224     return render(request, "funding/includes/fundings.html", {
225         "paginator": paginator,
226         "page_obj": page_obj,
227         "fundings": page_obj.object_list,
228     })