# -*- coding: utf-8 -*-
#
# CDR-Stats License
# http://www.cdr-stats.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2015 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <info@star2billing.com>
#

from celery.task import PeriodicTask
from cdr.import_cdr_asterisk import import_cdr_asterisk
from django_lets_go.only_one_task import only_one
from datetime import timedelta

# Note: if you import a lot of CDRs the first time you can have an issue here
# we need to make sure the user import their CDR before starting Celery
# for now we will increase the lock limit to 1 hours
LOCK_EXPIRE = 60 * 60 * 1  # Lock expires in 1 hours


class sync_cdr_pending(PeriodicTask):

    """
    A periodic task that checks for pending CDR to import
    """
    run_every = timedelta(seconds=30)

    @only_one(ikey="sync_cdr_pending", timeout=LOCK_EXPIRE)
    def run(self, **kwargs):
        logger = self.get_logger()
        logger.info('TASK :: sync_cdr_pending')

        # Import from Asterisk
        import_cdr_asterisk()

        return True

@@ -407,16 +407,49 @@
 com%3E%0A#%0A%0A
+from django.db import connection%0A
 from cel
@@ -477,16 +477,16 @@
 dicTask%0A
-
 from cdr
@@ -911,17 +911,16 @@
 cTask):%0A
-%0A
     %22%22%22%0A
@@ -1228,16 +1228,16 @@
 sterisk%0A
-
         
@@ -1279,8 +1279,646 @@
 rn True%0A
+%0A%0Aclass refresh_materialized_views(PeriodicTask):%0A    %22%22%22%0A    A periodic task that refresh the materialized views%0A    %22%22%22%0A    run_every = timedelta(minutes=15)%0A%0A    def run(self, **kwargs):%0A        logger = self.get_logger()%0A        logger.info('TASK :: refresh_materialized_views')%0A%0A        # Refresh matv_voip_cdr_aggr_hour%0A        with connection.cursor() as cursor:%0A            cursor.execute(%22REFRESH MATERIALIZED VIEW matv_voip_cdr_aggr_hour;%22)%0A%0A        # Refresh matv_voip_cdr_aggr_min%0A        with connection.cursor() as cursor:%0A            cursor.execute(%22REFRESH MATERIALIZED VIEW matv_voip_cdr_aggr_min;%22)%0A%0A        return True%0A

add celery task to refresh materialized views