Add Book.ancestor m2m.
[wolnelektury.git] / apps / 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.urlresolvers import reverse
6 from django.http import Http404
7 from django.shortcuts import redirect, get_object_or_404
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                 self.object = get_object_or_404(Offer.public(), slug=slug)
82             else:
83                 self.object = Offer.current()
84                 if self.object is None:
85                     raise Http404
86         return super(OfferDetailView, self).dispatch(request, slug)
87
88     def get_form(self, form_class):
89         if self.request.method == 'POST':
90             return form_class(self.object, self.request.POST)
91         else:
92             return form_class(self.object, initial={'amount': app_settings.DEFAULT_AMOUNT})
93
94     def get_context_data(self, *args, **kwargs):
95         ctx = super(OfferDetailView, self).get_context_data(*args, **kwargs)
96         ctx['object'] = self.object
97         if self.object.is_current():
98             ctx['funding_no_show_current'] = True
99         return ctx
100
101     def form_valid(self, form):
102         funding = form.save()
103         # Skip getpaid.forms.PaymentMethodForm, go directly to the broker.
104         payment = Payment.create(funding, self.backend)
105         gateway_url_tuple = payment.get_processor()(payment).get_gateway_url(self.request)
106         payment.change_status('in_progress')
107         return redirect(gateway_url_tuple[0])
108
109
110 class CurrentView(OfferDetailView):
111     @csrf_exempt
112     def dispatch(self, request, slug=None):
113         self.object = Offer.current()
114         if self.object is None:
115             return redirect(reverse('funding'))
116         elif slug != self.object.slug:
117             return redirect(reverse('funding_current', args=[self.object.slug]))
118         return super(CurrentView, self).dispatch(request, slug)
119
120
121 class OfferListView(ListView):
122     queryset = Offer.public()
123
124     def get_context_data(self, *args, **kwargs):
125         ctx = super(OfferListView, self).get_context_data(*args, **kwargs)
126         ctx['funding_no_show_current'] = True
127         return ctx
128
129
130 class ThanksView(TemplateView):
131     template_name = "funding/thanks.html"
132
133     def get_context_data(self, *args, **kwargs):
134         ctx = super(ThanksView, self).get_context_data(*args, **kwargs)
135         ctx['offer'] = Offer.current()
136         ctx['funding_no_show_current'] = True
137         return ctx
138
139
140 class NoThanksView(TemplateView):
141     template_name = "funding/no_thanks.html"
142
143
144 class DisableNotifications(TemplateView):
145     template_name = "funding/disable_notifications.html"
146
147     @csrf_exempt
148     def dispatch(self, request):
149         self.object = get_object_or_404(Funding,
150             email=request.GET.get('email'), notify_key=request.GET.get('key'))
151         return super(DisableNotifications, self).dispatch(request)
152
153     def post(self, *args, **kwargs):
154         self.object.disable_notifications()
155         return redirect(self.request.get_full_path())