#!/usr/bin/env python
# coding: utf-8
import  sys
import datetime
sys.path.append('../../')
sys.path.append('../')
from django.core.management import setup_environ
from globalhome import settings
setup_environ(settings)
# from globalhome.data_centr.models import Zakazy, Tariff, Price_connection, Status_zakaza, Service_type, OS, CPU, RAM, HDD
# from globalhome.data_centr.views import formation_check, send_mail_check, cost_dc
# from globalhome.account.models import Profile
# from globalhome.content.models import Check
# from globalhome.externalnumbers.models import ExternalNumber
# from globalhome.billing.models import BillserviceAccount
# from django.contrib.auth.models import User
# from django.db.models import Q
import calendar
import psycopg2
from settings import DATABASES
from dateutil.relativedelta import relativedelta

conn = psycopg2.connect("dbname='%(NAME)s' user='%(USER)s' host='%(HOST)s' password='%(PASSWORD)s'" % DATABASES['billing'])
cur = conn.cursor()
cur.connection.set_isolation_level(1)
cur.connection.commit()

cur.execute("""SELECT DISTINCT ON (account_id, createdate) account_id, createdate, nas_int_id  FROM (SELECT account_id, date_trunc('day', date_start) as createdate, nas_int_id FROM  radius_activesession WHERE date_start>='2014-06-01' and framed_protocol='HotSpot') as a""")
users = cur.fetchall()
for user in users:
    cur.execute("SELECT * FROM billservice_transaction  WHERE type_id='HOTSPOT_PAY' and account_id=%s and created>=%s and created<%s::date + interval '1 day'", (user[0], user[1], user[1]))
    r = cur.fetchall()
    if r:
        # print r
        continue
    cur.execute("""INSERT INTO billservice_transaction(bill, account_id, type_id, approved, tarif_id, summ, description, created)
          select 'Абонентская плата за HotSpot', %s, 'HOTSPOT_PAY', True, null, -cost, 'Оплата за HotSpot', %s  from data_centr_price where id=
          (select price_id_id from data_centr_tariff where id=(select data_centr_tarif_id from nas_nas where id=%s))""", (user[0], user[1], user[2]))
    print "insert for user=%s date=%s, nas=%s" % user
cur.connection.commit()
