Untitled

mail@pastecode.io avatar
unknown
python
2 months ago
5.7 kB
1
Indexable
Never
# -.- coding: utf-8 -.-
from django.core.management.base import BaseCommand, CommandError
from rh.ferias.models import *
from optparse import make_option
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import User
from contrib.middleware import set_current_user, StartupLoader
from contrib.utils import DateUtils
from rh.utils import send_mail_and_notify
from rh.ac import load_custom_fixtures
from rh.ac.models import DayActivity, MonthActivity, Ticket, Authorization
from rh.models import Servidor

class Command(BaseCommand):
    verbose = 'False'
    help = u"""Este comando cria as autorização de acumulo automática
    """

    option_list = BaseCommand.option_list + (
        make_option('-a', '--all', action='store_true', dest="all", help=u"autorizar acumulos"),
    )

    def __init__(self, *args, **kargs):
        self.log = getLogger(self.__class__.__name__)
        BaseCommand.__init__(self, *args, **kargs)

    def handle(self, *args, **options):
        if options['all']:
            self.created_authorization_accumlation()

    def conf(self):
        StartupLoader().doLoad()
        set_current_user(User.objects.get(username='athenas'))
    
    def get_types_employee_accumulation__automatic(self,month,year):
        cfg = Configuration.get_configs(date(year ,month,1))
        siglas = [c.cvalue for c in cfg.types_by_possession_accumulation_aut.all()]
        return siglas


    def get_all_days_not_accumulate(self):
        # MESES EM ABERTO
        months = MonthActivity.objects.filter(is_changeable=False).values_list('month','year').distinct()
        days = None
        mes_atual = datetime.now().date().month
        ano_atual = datetime.now().date().year

        for month in months:
            # verificando se o mes nao é do futuro
            
            # tipo de servidores que podem ter autorizacao automatica
            if not(ano > ano_atual or (ano == ano_atual and mes > mes_atual)):
                types = self.get_types_employee_accumulation__automatic(month[0],month[1])
                query_days = DayActivity.objects.filter(month_activity__is_changeable=False)
                query_days = query_days.filter(accumulation__gt=F('authorized_accumulation'))
                query_days = query_days.filter(month_activity__month=month[0],month_activity__year=month[1])
                query_days = query_days.filter(employee__type_by_possession__in=types)
                days = days | query_days if days != None else query_days

        return days
    
    def add_authrorization_days_not_accumulate(self):
        days = get_all_days_not_accumulate():
        for day in days:
            self.add_authorization_day(day,employee,day.date)

    #ESSE METODO GARANTE QUE TODOS DIAS ESTAO SENDO RECALCULADOS PARA EVITAR SALDO INCORRETOS
    def recalculate_monthly(self,data):
        mas = MonthActivity.objects.filter(year=date.year,month=date.month,is_changeable=False)
        for ma in mas:
            try:
                ma.recalculate_days()
            except Exception as e:
                print(u">>> [%s] Não Foi recalculado movimento mes  >>>>>>>>>>>>>" % ma.__unicode__())
                print(u">>> [%s] Erro:  >>>>>>>>>>>>>" % e)
    
    def generate_missing_day_activity(self,servidor,date):
        # pagando o dayactivity
        if DayActivity.objects.filter(date=date,employee=servidor).exists():
            da = DayActivity.objects.get(date=date,employee=servidor)
        else:
            ma,created = MonthActivity.objects.get_or_create(month=date.month,year=date.year,employee=servidor)

            try:
                ma.pos_save()
            except Exception as e:
                print(u">>> [%s] Não Foi recalculado movimento mes  >>>>>>>>>>>>>" % ma.__unicode__())
                print(u">>> [%s] Erro:  >>>>>>>>>>>>>" % e)

    def add_authorization_day(self,servidor,date):
        
        if DayActivity.objects.filter(date=date,employee=servidor).exists():
            da = DayActivity.objects.get(date=date,employee=servidor)
            
            if da and len(da.ac_tickets.all()) > 0:
                try:
                    authorizacao = da.add_authorization(1)
                except Exception as e:
                    print(u">>> [%s] Não Foi recalculado movimento dia  >>>>>>>>>>>>>" % da.__unicode__())
                    print(u">>> [%s] Erro:  >>>>>>>>>>>>>" % e)

    def created_authorization_accumlation(self):

        self.conf()
        date_process = datetime.now() 
        date = datetime.now().date()
        date -= relativedelta(days=+1)
        servidores = Authorization.get_employees_automatic_accumulation(date)
        
        # RECALCULANDO TODOS DIAS DOS MOVIMENTOS MESES
        self.recalculate_monthly(date)
                
        print(u">>> [%s] Iniciando a importacao de autorizacao de acumulos  >>>>>>>>>>>>>" % DateUtils.datetime_to_str(date_process))
        for servidor in servidores:
            
            # CRIANDO DAY ACTIVITY CASO ELA NAO EXISTA AINDA
            self.generate_missing_day_activity(servidor,date)
            
            # CRIANDO AUTORIZACAO DE ACUMULO NO DIA
            self.add_authorization_day(servidor,date)

        # AUTORIZAR ACUMULOS ANTERIORES
        days_not_autorized = self.get_all_days_not_accumulate()
        for day in days_not_autorized:
            self.add_authorization_day(day.employee,day.date)       

                    
        date_process = datetime.now()
        print u">>> [%s] Finalizando a importacao de autorizacao de acumulos  >>>>>>>>>>>>>" % DateUtils.datetime_to_str(date_process)

Leave a Comment