#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from datetime import datetime, timedelta
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.mail import send_mail
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.core import validators
class FuncionarioManager(BaseUserManager):
def create_user(self, username, matricula, email, horario_inicial_entrada, horario_final_saida, password=None, **extra_fields):
"""
Creates and saves an EmailUser with the given email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
funcionario = FuncionarioManager.normalize_email(email)
user = self.model(username=username, matricula=matricula, email=email, horario_inicial_entrada=horario_inicial_entrada, horario_final_saida=horario_final_saida, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, matricula, email, horario_inicial_entrada, horario_final_saida, password, **extra_fields):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(username, matricula, email, password, **extra_fields)
user.is_admin = True
user.is_staff = True
user.is_active = True
user.is_superuser = True
user.save(using=self._db)
return user
class AbstractFuncionario(AbstractBaseUser, PermissionsMixin):
"""
Abstract User with the same behaviour as Django's default User but
without a username field. Uses email as the USERNAME_FIELD for
authentication.
Use this if you need to extend EmailUser.
Inherits from both the AbstractBaseUser and PermissionMixin.
The following attributes are inherited from the superclasses:
* password
* last_login
* is_superuser
"""
username = models.CharField(_('username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')])
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
matricula = models.CharField(verbose_name="Matrícula", max_length=20, help_text="Matrícula do funcionário.", blank=False, null=False, unique=True)
horario_inicial_entrada = models.TimeField(verbose_name="Horário Inicial de Entrada", max_length=20, help_text="Este é o horário inicial que começam a contar as horas trabalhadas do funcionário.", blank=False, null=False)
horario_final_saida = models.TimeField(verbose_name="Horário Final de Saída", max_length=20, help_text="Este é o horário final encerra a contagenm das horas trabalhadas do funcionário.", blank=False, null=False)
email = models.EmailField(_('email address'), max_length=255, unique=True, db_index=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['matricula']
class Meta:
abstract = True
verbose_name = 'Funcionário'
verbose_name_plural = 'Funcionários'
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
def __unicode__(self):
return "%s %s" %(self.first_name, self.last_name)
class Funcionario(AbstractFuncionario):
"""
Concrete class of AbstractEmailUser.
Use this if you don't need to extend EmailUser.
"""
objects = FuncionarioManager()
class Meta(AbstractBaseUser.Meta):
swappable = 'AUTH_USER_MODEL'
class BatidaPonto(models.Model):
funcionario = models.ForeignKey(Funcionario, verbose_name="Funcionário", help_text="Funcionário a quem esta batida de ponto se refere.", blank=False, null=False)
momento_batidaponto = models.DateTimeField(verbose_name="Momento da Batida de Ponto", help_text="Data e hora de quando o ponto foi batido.", blank=False, null=False, unique=True)
def __unicode__(self):
return unicode(self.momento_batidaponto)
class Meta:
verbose_name = "Batida de Ponto"
verbose_name_plural = "Batidas de Ponto"
unique_together = ('funcionario', 'momento_batidaponto')
def momento_batidaponto_formatado(self):
meses = ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
dia_formatado = "%d" %(self.momento_batidaponto.day)
if self.momento_batidaponto.day < 10:
dia_formatado = "0%d" %(self.momento_batidaponto.day)
horas_formatadas = ""
minutos_formatados = ""
segundos_formatados = ""
if self.momento_batidaponto.hour < 10:
horas_formatadas = "0%d" %(self.momento_batidaponto.hour)
else:
horas_formatadas = str(self.momento_batidaponto.hour)
if self.momento_batidaponto.minute < 10:
minutos_formatados = "0%d" %(self.momento_batidaponto.minute)
else:
minutos_formatados = str(self.momento_batidaponto.minute)
if self.momento_batidaponto.second < 10:
segundos_formatados = "0%d" %(self.momento_batidaponto.second)
else:
segundos_formatados = str(self.momento_batidaponto.second)
semana = "%s de %s de %d, às %s:%s:%s" %(dia_formatado, meses[self.momento_batidaponto.month -1], self.momento_batidaponto.year, horas_formatadas, minutos_formatados, segundos_formatados)
return semana
class Sincronizacao(models.Model):
data_hora = models.DateTimeField(verbose_name="Momento da Última Sincronização", help_text="Data e hora de quando a última sincronização foi realizada.", blank=False, null=False)
def __unicode__(self):
return unicode(self.data_hora)
class Meta:
verbose_name = "Sincronização"
verbose_name_plural = "Sincronizações"
class Comentario(models.Model):
funcionario = models.ForeignKey(Funcionario, verbose_name="Funcionário", help_text="Funcionário a quem esta batida de ponto se refere.", blank=False, null=False)
data = models.DateField(verbose_name="Data", help_text="Data do comentário.", blank=False, null=False)
texto = models.TextField(verbose_name="Texto do Comentário", help_text="Data do comentário.", max_length="500", blank=False, null=False)
def __unicode__(self):
return unicode(self.data)
class Meta:
verbose_name = "Comentário"
verbose_name_plural = "Comentários"