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