# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2019-01-09 13:53
from __future__ import unicode_literals

from django.db import migrations


def forwards(apps, schema_editor):
    BillingLog = apps.get_model("crm", "BillingLog")

    for log in BillingLog.objects.all().exclude(log_type='create_note'):
        try:
            pk, year = log.invoice.invoice_number.split('-')
        except ValueError:
            print('Skipping {}'.format(log.invoice.invoice_number))
            continue

        if year != log.invoice_year:
            if len(year) != 4:
                print('Skipping {}'.format(log.invoice.invoice_number))
                continue

            print('Updated Log year #{} from {} to {} for Invoice: {}'.format(log.pk, log.invoice_year, year,
                                                                              log.invoice.invoice_number))
            log.invoice_year = year
            log.save()


class Migration(migrations.Migration):
    dependencies = [
        ('crm', '0008_set_billing_type_1320'),
    ]

    operations = [
        migrations.RunPython(forwards, hints={'target_db': 'default'}),
    ]

Fix invoice years