Fundraising in PDF.
[wolnelektury.git] / src / funding / migrations / 0013_missing_spent.py
1 # Generated by Django 4.0.8 on 2024-02-21 11:55
2
3 from django.db import migrations, models
4
5
6 def populate_spent(apps, schema_editor):
7     Offer = apps.get_model('funding', 'Offer')
8     Spent = apps.get_model('funding', 'Spent')
9     Book = apps.get_model('catalogue', 'Book')
10     for o in Offer.objects.all():
11         if Spent.objects.filter(book__slug=o.slug).exists():
12             continue
13         s = o.funding_set.exclude(completed_at=None).aggregate(s=models.Sum('amount'))['s'] or 0
14         if s >= o.target:
15             try:
16                 book = Book.objects.get(slug=o.slug)
17                 link = ''
18             except Book.DoesNotExist:
19                 book = None
20                 link = o.slug
21             Spent.objects.create(
22                 book=book,
23                 link=link,
24                 amount=o.target,
25                 timestamp=o.end,
26                 annotation='auto'
27             )
28
29
30 class Migration(migrations.Migration):
31
32     dependencies = [
33         ('funding', '0012_spent_annotation_spent_link_alter_spent_book'),
34     ]
35
36     operations = [
37         migrations.RunPython(
38             populate_spent,
39             migrations.RunPython.noop
40         )
41     ]