Fundraising in PDF.
[wolnelektury.git] / src / funding / views.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. 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             o.wlfund = o.sum()
55             if o.wlfund > 0:
56                 offers.append(o)
57         amount = sum(o.wlfund for o in offers) - sum(o.amount for o in Spent.objects.all())
58
59         ctx['amount'] = amount
60         ctx['log'] = add_total(amount, mix(
61             (Spent.objects.all().select_related(), lambda x: x.timestamp, 'spent'),
62             (offers, lambda x: x.end, 'offer'),
63         ))
64         return ctx
65
66
67 class OfferDetailView(FormView):
68     form_class = FundingForm
69     template_name = 'funding/offer_detail.html'
70
71     @csrf_exempt
72     def dispatch(self, request, slug=None):
73         if getattr(self, 'object', None) is None:
74             if slug:
75                 if request.user.is_staff:
76                     offers = Offer.objects.all()
77                 else:
78                     offers = Offer.public()
79                 self.object = get_object_or_404(offers, slug=slug)
80             else:
81                 self.object = Offer.current()
82                 if self.object is None:
83                     raise Http404
84         return super(OfferDetailView, self).dispatch(request, slug)
85
86     def get_form(self, form_class=None):
87         if form_class is None:
88             form_class = self.get_form_class()
89         if self.request.method == 'POST':
90             return form_class(self.request, self.object, self.request.POST)
91         else:
92             return form_class(self.request, self.object, initial={'amount': app_settings.DEFAULT_AMOUNT})
93
94     def get_context_data(self, **kwargs):
95         ctx = super(OfferDetailView, self).get_context_data(**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         return redirect(funding.put())
104
105
106 class CurrentView(OfferDetailView):
107     @csrf_exempt
108     def dispatch(self, request, slug=None):
109         self.object = Offer.current()
110         if self.object is None:
111             return redirect(reverse('funding'))
112         elif slug != self.object.slug:
113             return redirect(reverse('funding_current', args=[self.object.slug]))
114         return super(CurrentView, self).dispatch(request, slug)
115
116
117 class OfferListView(ListView):
118     queryset = Offer.public()
119     template_name = 'funding/offer_list.html'
120     
121     def get_context_data(self, **kwargs):
122         ctx = super(OfferListView, self).get_context_data(**kwargs)
123         ctx['funding_no_show_current'] = True
124         return ctx
125
126
127 class ThanksView(TemplateView):
128     template_name = "funding/thanks.html"
129
130     def get_context_data(self, **kwargs):
131         ctx = super(ThanksView, self).get_context_data(**kwargs)
132         ctx['offer'] = Offer.current()
133         ctx['funding_no_show_current'] = True
134         return ctx
135
136
137 class NoThanksView(TemplateView):
138     template_name = "funding/no_thanks.html"
139
140
141 class DisableNotifications(TemplateView):
142     template_name = "funding/disable_notifications.html"
143
144     @csrf_exempt
145     def dispatch(self, request):
146         self.object = get_object_or_404(Funding, email=request.GET.get('email'), notify_key=request.GET.get('key'))
147         return super(DisableNotifications, self).dispatch(request)
148
149     def post(self, *args, **kwargs):
150         self.object.disable_notifications()
151         return redirect(self.request.get_full_path())
152
153
154 @login_required
155 def claim(request, key):
156     funding = get_object_or_404(Funding, notify_key=key)
157     if funding.user is None:
158         funding.user = request.user
159         funding.save()
160     return HttpResponseRedirect(
161         funding.offer.book.get_absolute_url() if funding.offer.book is not None
162         else funding.offer.get_absolute_url()
163     )
164
165
166 class PayUNotifyView(club.payu.views.NotifyView):
167     order_model = Funding
168