Changeset View
Changeset View
Standalone View
Standalone View
looper/migrations/0060_add_refunded_to_order.py
- This file was added.
| # Generated by Django 3.0.4 on 2021-06-24 17:28 | |||||
| from django.db import migrations, models | |||||
| import looper.models | |||||
| def get_total_refunded(order): | |||||
| """Copy of the Order.get_total_refunded which is inaccessible at this stage of the migration.""" | |||||
| from looper.money import Money | |||||
| result = order.transaction_set.all().aggregate(models.Sum('amount_refunded')) | |||||
| # Prevent None, which happens when an order has no transactions. | |||||
| refunded_sum = result['amount_refunded__sum'] or 0 | |||||
| return Money(order.currency, refunded_sum) | |||||
| def get_tax_refunded(order): | |||||
| """Copy of the Order.get_tax_refunded which is inaccessible at this stage of the migration.""" | |||||
| from looper.money import Money | |||||
| if order.tax._cents == 0: | |||||
| return Money(order.currency, 0) | |||||
| total_refunded = order.refunded | |||||
| if total_refunded._cents == 0: | |||||
| return Money(order.currency, 0) | |||||
| amount = round(total_refunded._cents * order.tax_rate / 100) | |||||
| return Money(order.currency, amount) | |||||
| def set_refunded_values(apps, schema_editor): | |||||
| Transaction = apps.get_model('looper', 'Transaction') | |||||
| Order = apps.get_model('looper', 'Order') | |||||
| to_update = [] | |||||
| transactions_with_refunds = Transaction.objects.select_related( | |||||
| 'order').filter(amount_refunded__gt=0) | |||||
| if not transactions_with_refunds.count(): | |||||
| return | |||||
| for trans in transactions_with_refunds: | |||||
| # Update order's refunded amount | |||||
| order = trans.order | |||||
| order.refunded = get_total_refunded(order) | |||||
| order.tax_refunded = get_tax_refunded(order) | |||||
| order.refunded_at = trans.refunded_at | |||||
| to_update.append(order) | |||||
| Order.objects.bulk_update(to_update, ['refunded', 'tax_refunded', 'refunded_at'], batch_size=100) | |||||
| class Migration(migrations.Migration): | |||||
| dependencies = [ | |||||
| ('looper', '0059_add_number_and_legacy_flags'), | |||||
| ] | |||||
| operations = [ | |||||
| migrations.AddField( | |||||
| model_name='order', | |||||
| name='refunded', | |||||
| field=looper.models.MoneyField(blank=True, currency_field='currency', default=0, help_text='Refunded total, if any.'), | |||||
| ), | |||||
| migrations.AddField( | |||||
| model_name='order', | |||||
| name='refunded_at', | |||||
| field=models.DateTimeField(help_text='Date of latest refund, if any.', null=True), | |||||
| ), | |||||
| migrations.AddField( | |||||
| model_name='order', | |||||
| name='tax_refunded', | |||||
| field=looper.models.MoneyField(blank=True, currency_field='currency', default=0, help_text='Refunded tax, if any.'), | |||||
| ), | |||||
| migrations.RunPython(set_refunded_values, reverse_code=migrations.RunPython.noop) | |||||
| ] | |||||