class TipoEdital(models.ModelPlus): nome = models.CharField('Nome', max_length=255, unique=True) class Meta: verbose_name = u'Tipo do Edital' verbose_name_plural = u'Tipos de Editais' def __str__(self): return self.nome
class ModeloPPC(ArquivoGoogleDocs): nome = models.CharField(verbose_name='Nome', max_length=255, unique=True) class Meta: verbose_name = u'Modelo de PPC' verbose_name_plural = u'Modelos de PPCs' def __str__(self): return self.nome
class SituacaoPPC(models.ModelPlus): nome = models.CharField(verbose_name='Nome', max_length=50, unique=True) impeditiva = models.BooleanField(verbose_name='Impeditiva', default=False, blank=True) ativa = models.BooleanField(verbose_name='Ativa', default=True, blank=True) class Meta: verbose_name = u'Situação no PPC' verbose_name_plural = u'Situações dos PPCs' def __str__(self): return self.nome
class Atributo(ModelPlus): nome_campo = models.CharFieldPlus(verbose_name=u'Nome do Campo', max_length=30) tipo_campo = models.CharFieldPlus(verbose_name=u'Tipo do campo', max_length=30, choices=escolhas.items(), default=escolhas.get('Texto')) obrigatorio = models.BooleanField(verbose_name=u'Obrigatorio', default=False) unico = models.BooleanField(verbose_name=u'È unico', default=False) valor = models.CharField(verbose_name=u'Valor', max_length=50) categoria_instancia = models.ForeignKey('systi.Categoria', verbose_name=u'Instancia') class Meta: verbose_name = u'Campo Adicional' verbose_name_plural = u'Campos Adicionais'
class GoogleCloudCredential(models.ModelPlus): service_name = models.CharField(verbose_name='Service name', max_length=255, unique=True) client_secret = EncryptedTextField(verbose_name='Client Secret', null=True) credentials_content = EncryptedTextField( verbose_name='Credentials Content', null=True, blank=True) def create_credentials(self): flow = InstalledAppFlow.from_client_config( json.loads(self.client_secret), [MANGAE_OWNER_SCOPE]) creds = flow.run_console() self.credentials_content = json.dumps({ 'token': creds.token, 'refresh_token': creds.refresh_token, 'token_uri': creds.token_uri, 'client_id': creds.client_id, 'client_secret': creds.client_secret, 'scopes': creds.scopes, }) @cached_property def credentials(self): if not self.credentials_content: raise CredentialsError() info = json.loads(self.credentials_content) credentials = Credentials(**info) if not credentials.valid: if credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: raise CredentialsError() return credentials @cached_property def service(self): return build('docs', 'v1', credentials=self.credentials) @cached_property def service_drive(self): return build('drive', 'v3', credentials=self.credentials)
class Documento(models.ModelPlus): nome = models.CharField('Nome do documento', max_length=255, unique=True) url = models.URLField(verbose_name='URL', blank=True, null=True) arquivo = DocumentFileField(verbose_name='Arquivo', size=2, format=['pdf', 'doc', 'docx'], blank=True, null=True, upload_to=UploadToGenerator( ['editais_ppc', 'documentos']), storage=MinioMediaStorage()) class Meta: verbose_name = u'Documento' verbose_name_plural = u'Documentos' def __str__(self): return self.nome
class ArquivoGoogleDocs(models.ModelPlus): url = models.URLField(blank=True, verbose_name='Link para o Documento') google_id = models.CharField(verbose_name='ID do documento', max_length=1024) @cached_property def google_cloud(self): gcc = GoogleCloudCredential.objects.last() return gcc def adicionar_permissao(self, email, role): self.google_cloud.service_drive.permissions().create( fileId=self.google_id, body={ 'role': role, 'type': 'user', 'emailAddress': email }).execute() def atualizar_permissao(self, email, role): permissions = self.listar_permissoes() for perm in permissions['permissions']: if perm['emailAddress'] == email: self.google_cloud.service_drive.permissions().update( fileId=self.google_id, permissionId=perm['id'], body={ 'role': role }).execute() def atualizar_permissao_por_id(self, permission_id, role): self.google_cloud.service_drive.permissions().update( fileId=self.google_id, permissionId=permission_id, body={ 'role': role }).execute() def remover_permissao(self, email): permissions = self.listar_permissoes() for perm in permissions['permissions']: if perm['emailAddress'] == email: self.google_cloud.service_drive.permissions().delete( fileId=self.google_id, permissionId=perm['id'], ).execute() def remover_permissoes(self): permissions = self.listar_permissoes() for perm in permissions['permissions']: if not perm['role'] == 'owner': self.google_cloud.service_drive.permissions().delete( fileId=self.google_id, permissionId=perm['id'], ).execute() def atualizar_permissoes(self, role): permissions = self.listar_permissoes() for perm in permissions['permissions']: if not perm['role'] == 'owner': self.google_cloud.service_drive.permissions().update( fileId=self.google_id, permissionId=perm['id'], body={ 'role': role }).execute() @cached_method def listar_permissoes(self): permissions = self.google_cloud.service_drive.permissions().list( fileId=self.google_id, fields='*').execute() return permissions def verificar_permissao(self, email, nivel_acesso): for permissao in self.listar_permissoes()['permissions']: if email == permissao[ 'emailAddress'] and nivel_acesso == permissao['role']: return True return False def clonar(self, nome): response = self.google_cloud.service_drive.files().copy( fileId=self.google_id, body={ 'name': nome }).execute() return ArquivoGoogleDocs.objects.create( google_id=response.get('id'), url='https://docs.google.com/document/d/{}'.format( response.get('id'))) def download(self): gc = self.google_cloud request = gc.service_drive.files().export_media( fileId=self.google_id, mimeType='application/pdf') fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() return fh.getvalue() class Meta: verbose_name = u'Arquivo Google Docs' verbose_name_plural = u'Arquivos Google Docs' def __str__(self): return self.google_id
class Edital(models.ModelPlus): nome = models.CharField(verbose_name='Nome', max_length=1024) numero = models.PositiveIntegerField(verbose_name='Número do edital') ano = models.PositiveIntegerField(verbose_name='Ano') tipo = models.ForeignKey(TipoEdital, verbose_name='Tipo do Edital', related_name='editais', on_delete=models.PROTECT) quantidade_avaliadores = models.PositiveIntegerField( verbose_name='Quantidade de avaliadores', help_text='Quantidade de avaliadores por PPC') avaliadores = models.ManyToManyFieldPlus('rh.Servidor', related_name='editais_ppc') arquivo = DocumentFileField(verbose_name='Arquivo do Edital', size=2, format=['pdf'], upload_to=UploadToGenerator( ['editais_ppc', 'editais']), storage=MinioMediaStorage()) documentos = models.ManyToManyFieldPlus(Documento, verbose_name='Documentos', related_name='editais', blank=True) modelo_ppc = models.ForeignKey(ModeloPPC, verbose_name='Modelo PPC', related_name='editais', on_delete=models.PROTECT) inicio_inscricao = models.DateFieldPlus( verbose_name='Data inicial para a inscrição no edital') fim_inscricao = models.DateFieldPlus( verbose_name='Data final para a inscrição no edital') inicio_analise = models.DateFieldPlus( verbose_name='Data inicial para a análise dos PPCs') fim_analise = models.DateFieldPlus( verbose_name='Data final para a análise dos PPCs') inicio_ajuste = models.DateFieldPlus( verbose_name='Data inicial para ajustes nos PPCs') fim_ajuste = models.DateFieldPlus( verbose_name='Data final para ajustes nos PPCs') data_resultado = models.DateFieldPlus( verbose_name='Data final para o resultado nos PPCs') objects = querysets.EditalQuerySet.as_manager() def get_absolute_url(self): return reverse('editais_ppc:edital_ppc', args=[self.pk]) def em_periodo_inscricao(self): today = datetime.date.today() return self.inicio_inscricao <= today <= self.fim_inscricao def em_periodo_analise(self): today = datetime.date.today() return self.inicio_analise <= today <= self.fim_analise def em_periodo_ajuste(self): today = datetime.date.today() return self.inicio_ajuste <= today <= self.fim_ajuste def em_periodo_pre_ajuste(self): today = datetime.date.today() return self.fim_analise < today < self.inicio_ajuste def em_periodo_pos_ajuste(self): today = datetime.date.today() return self.fim_ajuste < today def em_data_resultado(self): today = datetime.date.today() return self.data_resultado == today class Meta: verbose_name = u'Edital' verbose_name_plural = u'Editais' def __str__(self): return '{self.nome} - {self.numero}/{self.ano}'.format(self=self)