# Generated by Django 2.0.6 on 2018-08-08 15:41

from django.db import migrations


SQL_CREATE = """
CREATE OR REPLACE FUNCTION fix_expired() RETURNS TRIGGER AS $$
  BEGIN
    IF NEW.deadline_at <= CURRENT_TIMESTAMP AND NEW.status = 210 THEN
      NEW."status" := 220;
    ELSIF NEW.deadline_at > CURRENT_TIMESTAMP AND NEW.status = 220 THEN
      NEW."status" := 210;
    END IF;
    RETURN NEW;
  END;
$$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS trigger_update_fix_expired ON api_quote;
CREATE TRIGGER trigger_update_fix_expired
BEFORE UPDATE OR INSERT ON api_quote
FOR EACH ROW
EXECUTE PROCEDURE fix_expired();
"""


SQL_DROP = """
DROP FUNCTION IF EXISTS fix_expired() CASCADE;
"""


class Migration(migrations.Migration):

    dependencies = [('api', '0003_sql_enquiry_status')]

    operations = [
        migrations.RunSQL(sql=SQL_CREATE, reverse_sql=SQL_DROP, elidable=False)
    ]
