Move excessive funds to WLF
[wolnelektury.git] / apps / funding / views.py
index 05bf398..c14cee3 100644 (file)
@@ -1,4 +1,8 @@
-# Create your views here.
+# -*- coding: utf-8 -*-
+# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+#
+from django.conf import settings
 from django.core.urlresolvers import reverse
 from django.shortcuts import redirect, get_object_or_404
 from django.views.generic import TemplateView, FormView, DetailView
@@ -17,7 +21,7 @@ def mix(*streams):
         else:
             substreams.append([read_date(item), item, iterstream, read_date, tag])
     while substreams:
-        i, substream = max(enumerate(substreams), key=lambda x: x[0])
+        i, substream = max(enumerate(substreams), key=lambda x: x[1][0])
         yield substream[4], substream[1]
         try:
             item = next(substream[2])
@@ -37,12 +41,21 @@ class WLFundView(TemplateView):
                 if tag == 'spent':
                     total += e.amount
                 else:
-                    total -= e.sum()
+                    total -= e.wlfund
                 yield tag, e
 
         ctx = super(WLFundView, self).get_context_data()
-        offers = [o for o in Offer.objects.all() if o.state() == 'lose' and o.sum()]
-        amount = sum(o.sum() for o in offers) - sum(o.amount for o in Spent.objects.all())
+        offers = []
+        for o in Offer.objects.all():
+            if o.state() == 'lose':
+                o.wlfund = o.sum()
+                if o.wlfund > 0:
+                    offers.append(o)
+            elif o.state() == 'win':
+                o.wlfund = o.sum() - o.target
+                if o.wlfund > 0:
+                    offers.append(o)
+        amount = sum(o.wlfund for o in offers) - sum(o.amount for o in Spent.objects.all())
         print offers
 
         ctx['amount'] = amount
@@ -65,7 +78,7 @@ class OfferDetailView(FormView):
         if self.request.method == 'POST':
             return form_class(self.object, self.request.POST)
         else:
-            return form_class(self.object)
+            return form_class(self.object, initial={'amount': settings.FUNDING_DEFAULT})
 
     def get_context_data(self, *args, **kwargs):
         ctx = super(OfferDetailView, self).get_context_data(*args, **kwargs)