class User(AbstractUser): email = models.EmailField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Primeiro nome') last_name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Segundo nome') data_nascimento = models.DateField(blank=False, null=False, verbose_name='Data de nascimento') telefone = models.CharField(max_length=15, blank=False, null=False, verbose_name="Telefone") cpf = BRCPFField("CPF",unique=True, blank=False, null=False) is_staff = models.BooleanField('Membro da equipe', default=True) is_superuser = models.BooleanField('Super user', default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'first_name', 'last_name', 'data_nascimento', 'telefone', 'cpf', 'is_superuser' ] def __str__(self): return self.email @property def formt_nome(self): return '{} {}'.format(self.first_name, self.last_name) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) objects = UsuarioManager()
class Order(TimeStampedModel): cpf = BRCPFField("CPF") name = models.CharField("Nome Completo", max_length=250) email = models.EmailField() postal_code = BRPostalCodeField("CEP") address = models.CharField("Endereço", max_length=250) number = models.CharField("Número", max_length=250) complement = models.CharField("Complemento", max_length=250, blank=True) district = models.CharField("Bairro", max_length=250) state = BRStateField("Estado") city = models.CharField("Cidade", max_length=250) paid = models.BooleanField(default=False) class Meta: ordering = ("-created",) def __str__(self): return f"Pedido {self.id}" def get_total_price(self): total_cost = sum(item.get_total_price() for item in self.items.all()) return total_cost def get_description(self): return ", ".join( [f"{item.quantity}x {item.product.title}" for item in self.items.all()] )
class ApprovedCPF(models.Model): cpf = BRCPFField('CPF', unique=True) reseller = models.OneToOneField(Reseller, on_delete=models.CASCADE, **bnull) description = models.TextField('Descrição', **bnull) @property def reseller_name(self): return self.reseller.full_name
class Pacientes(models.Model): cpf = BRCPFField("cpf", blank=False, unique=True, null=False, primary_key=True) email = models.EmailField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=20, blank=False, null=False) last_name = models.CharField(max_length=20, blank=False, null=False) telefone = models.CharField(max_length=15, null=True, blank=True) cod_endereco = models.ForeignKey(Endereco_pacientes, on_delete=models.CASCADE, blank=True, null=True) cod_sociodemografico = models.ForeignKey(Dados_sociodemagraficos, on_delete=models.CASCADE, blank=True, null=True) cod_clinico = models.ForeignKey(Dados_clinicos, on_delete=models.CASCADE, blank=True, null=True) cod_diag_enfermagem = models.ForeignKey(Diag_enfermagem, on_delete=models.CASCADE, blank=True, null=True) cod_diag_enfermagem_resultado = models.ForeignKey( Diag_enfermagem_resultado, on_delete=models.CASCADE, blank=True, null=True)
class Reseller(User): cpf = BRCPFField('CPF', unique=True) full_name = models.CharField('Nome Completo', max_length=70) objects = ResellerManager() def _get_purchase_total(self): from apps.purchase import models as md sum = \ md.Purchase.objects.filter(reseller_id=self.id).aggregate(models.Sum('purchase_value'))[ 'purchase_value__sum'] return locale.currency(sum, grouping=True, symbol=None) def _get_purchase_pending(self): from apps.purchase import models as md sum = \ md.Purchase.objects.filter(reseller_id=self.id, status='EM_AVALIACAO').aggregate(models.Sum('purchase_value'))[ 'purchase_value__sum'] return locale.currency(sum, grouping=True, symbol=None) purchase_pending = property(_get_purchase_pending) purchase_total = property(_get_purchase_total) def __str__(self): return self.full_name class Meta: verbose_name = 'Revendedor' verbose_name_plural = 'Revendedores'
class Customers(models.Model): name = models.CharField('Nome', max_length=200) cpf = BRCPFField('CPF', max_length=11, unique=True) phone = PhoneNumberField('Telefone', max_length=15) email = models.EmailField('E-mail', max_length=100, unique=True) cep = models.CharField('CEP', max_length=8) address = models.CharField('Endereço', max_length=200, default='') number = models.IntegerField('Número', null=True, blank=True) complement = models.CharField(max_length=50, blank=True) neighborhood = models.CharField('Bairro', max_length=100, default='') city = models.CharField('Cidade', max_length=100, default='') uf = models.CharField('UF', max_length=2, default='') def __str__(self): return self.name
class User(AbstractBaseUser, PermissionsMixin): cpf = BRCPFField(unique=True, max_length=11) full_name = models.CharField(max_length=255, blank=False, null=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) email = models.EmailField(unique=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["cpf", "full_name"] objects = UserManager() def __str__(self): return self.email
class Order(TimeStampedModel): cpf = BRCPFField("CPF") name = models.CharField("Nome Completo", max_length=250) email = models.EmailField() postal_code = BRPostalCodeField("CEP") address = models.CharField("Endereço", max_length=250) number = models.CharField("Número", max_length=250) complement = models.CharField("Complemento", max_length=250, blank=True) district = models.CharField("Bairro", max_length=250) state = BRStateField("Estado") city = models.CharField("Cidade", max_length=250) paid = models.BooleanField(default=False) class Meta: ordering = ("-created", ) def __str__(self): return f"Pedido {self.id}"
class User(AbstractBaseUser, PermissionsMixin): cpf = BRCPFField(verbose_name='CPF', primary_key=True, db_index=True) email = models.EmailField('email address', unique=True) fullname = models.CharField('full name', max_length=30, blank=False) date_joined = models.DateTimeField('date joined', auto_now_add=True) is_active = models.BooleanField('active', default=True) is_staff = models.BooleanField('staff', default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname', 'cpf'] def __str__(self): return self.email class Meta: verbose_name = 'user' verbose_name_plural = 'users'
class User(AbstractUser): """User model customizado. Usa email em vez de username para autenticar""" username = models.CharField( "Usuário", max_length=30, unique=True, validators=[ validators.RegexValidator( re.compile("^[\w.@+-]+$"), "Informe um nome de usuário válido. " "Este valor deve conter apenas letras, números " "e os caracteres: @/./+/_ .", "invalid", ) ], help_text= "Um nome curto que será usado para identificá-lo de forma única.", ) email = models.EmailField("Email", max_length=150, unique=True) cpf = BRCPFField("CPF", blank=True) cnpj = BRCNPJField("CNPJ", blank=True) postal_code = BRPostalCodeField("CEP", blank=True) address = models.CharField("Endereço", max_length=250, blank=True) district = models.CharField("Bairro", max_length=250, blank=True) state = BRStateField("Estado", blank=True) city = models.CharField("Cidade", max_length=250, blank=True) created = models.DateTimeField("Criado", auto_now_add=True) modified = models.DateTimeField("Modificado", auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] class Meta: verbose_name = "Usuário" verbose_name_plural = "Usuários" ordering = [ "-created", ] def _str_(self): self.name or self.email
class Profile(models.Model): CIVIL_CHOICES = [(0, 'Solteiro (a)'), (1, 'Casado (a)'), (2, 'Divorciado (a)'), (3, 'Viúvo (a)'), (4, 'Outro')] user = models.OneToOneField(User, verbose_name='Usuário', related_name='users', on_delete=models.CASCADE) cpf = BRCPFField('CPF', max_length=14, default=None) rg = models.CharField('RG', max_length=9, default=None) birthday = models.DateField('Data de Nascimento', default=None) civil_status = models.IntegerField('Estado Civil', choices=CIVIL_CHOICES, default=0) def __str__(self): return self.user.get_short_name() class Meta: verbose_name = 'Usuário' verbose_name_plural = 'Usuários'
class Usuario(AbstractUser): """ Classe modelo do Usuário """ username = None first_name = models.CharField(null=True, max_length=50, verbose_name="Nome") last_name = models.CharField(null=True, max_length=50, verbose_name="Sobrenome") cpf = BRCPFField(null=True, unique=True, max_length=14, verbose_name="CPF") telefone = models.CharField(null=True, max_length=14, verbose_name="Telefone") email = models.EmailField(null=False, unique=True, max_length=50, verbose_name="Email") password = models.CharField(null=False, max_length=128, verbose_name="Senha") is_active = models.BooleanField(null=False, default=True, verbose_name="Ativo") config_json = JSONField(verbose_name="Configurações JSON", default=pytradebot_json) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'first_name', 'last_name', 'cpf', 'telefone', 'password' ] objects = CustomUserManager() class Meta: db_table = 'usuarios' def __str__(self): return self.email
class Payment(TimeStampedModel): order = models.ForeignKey(Order, related_name="payments", on_delete=models.CASCADE) transaction_amount = models.DecimalField("Valor da Transação", max_digits=10, decimal_places=2) installments = models.IntegerField("Parcelas") payment_method_id = models.CharField("Método de Pagamento", max_length=250) email = models.EmailField() doc_number = BRCPFField("CPF") mercado_pago_id = models.CharField(max_length=250, blank=True, db_index=True) mercado_pago_status = models.CharField(max_length=250, blank=True) mercado_pago_status_detail = models.CharField(max_length=250, blank=True) class Meta: ordering = ("-modified", ) def __str__(self): return f"Pagamento {self.id}"
class User(AbstractUser): email = models.EmailField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=20, blank=False, null=False) last_name = models.CharField(max_length=20, blank=False, null=False) data_nascimento = models.DateField(blank=False, null=False) sexo = models.CharField(max_length=1, choices=SEXO_CHOICES, blank=False, null=False) faculdade = models.CharField(max_length=200, blank=True, null=True) periodo = models.CharField(max_length=20, blank=True, null=True, default=0) estado_civil = models.CharField(max_length=2, choices=ESTADO_CIVIL_CHOICES, null=True, blank=True) telefone = models.CharField(max_length=15, null=True, blank=True) endereco = models.CharField(max_length=250, blank=False, null=False) numero = models.CharField(max_length=250, blank=False, null=False) complemento = models.CharField(max_length=250, blank=False, null=False) bairro = models.CharField(max_length=250, blank=False, null=False) cidade = models.CharField(max_length=50, null=True, blank=True) cep = BRPostalCodeField("CEP", blank=False, null=False) cpf = BRCPFField("CPF", blank=False, unique=True, null=False) estado = BRStateField("Estado", blank=False, null=False)
class PreApprovedSales(models.Model): cpf = BRCPFField(unique=True) objects = PreApprovedSalesManager() def __str__(self): return f"{self.cpf}"
class Parentesco(models.Model): objects: None = None sexo_choice = ( ('Masculino', 'Masculino'), ('Feminino', 'Feminino'), ) parentesco_choice = ( ('Filho(a)', 'Filho(a)'), ('Conjuge', 'Conjuge'), ) estado_civil_choice = ( ('Solteiro(a)', 'Solteiro(a)'), ('Casado(a)', 'Casado(a)'), ('Convivente', 'Convivente'), ) declaracao_saude_choice = ( ('Sim', 'Sim'), ('Nao', 'Nao'), ) nome = models.CharField("Nome Dependente", max_length=255, blank=False) CPF = BRCPFField("Número CPF", max_length=14, null=False, unique=True) cod_empresa = models.CharField("Codigo Empresa", max_length=25, null=True, blank=True, validators=[cod_empresa_existe]) carteirinha = models.CharField("Numero da Carteirinha", max_length=35, null=True, blank=True) data_recebimento = models.DateField("Data Recebimento", auto_now=False, auto_now_add=False, null=False) tipo = models.CharField("Tipo Cadastro", max_length=25, default="Inclusão de Parentesco", editable=False) data_nascimento = models.DateField("Data Nascimento", auto_now_add=False, auto_now=False, blank=False, null=False) data_casamento = models.DateField("Data Casamento", auto_now_add=False, auto_now=False, blank=True, null=True) sexo = models.CharField(max_length=25, choices=sexo_choice, blank=True, default="Selecione", null=False) estado_civil = models.CharField(max_length=25, choices=estado_civil_choice, default="Selecione", null=False, blank=False) tipo_parentesco = models.CharField(max_length=25, choices=parentesco_choice, blank=False, default="Selecione", null=False) anexo_doc_parentesco = models.ImageField(upload_to='anexo_parentescos', blank=True, null=True) anexo_doc_casamento = models.ImageField(upload_to=doc_casamento_path, blank=True, null=True) anexo_doc_nascimento = models.ImageField(upload_to=doc_nascimento_path, blank=True, null=True) nome_mae = models.CharField("Nome da Mae", max_length=255) data_admissao = models.DateField("Data de Admissão", auto_now=False, auto_now_add=False, null=False) titular = models.ForeignKey(Titular, on_delete=models.CASCADE, blank=False) CEP = BRPostalCodeField("Código Postal", max_length=14, null=False) celular = models.CharField("Numero do Celular", max_length=100, null=True) cidade = models.CharField("Cidade", max_length=150, blank=False, null=False) estado = BRStateField("Estado UF", max_length=150, blank=False, null=False) declaracao_saude = models.CharField(max_length=25, choices=declaracao_saude_choice, blank=False, default="Selecione", null=False) desc_declarao_saude = models.CharField("Desc. Declaracao Saude", max_length=255, blank=True) observacoes = models.TextField("Obs.", blank=True, null=True) ativo = models.BooleanField(default=True) transferido = models.BooleanField(default=False) criado_em = models.DateTimeField("Criado em", auto_now_add=True) atualizado_em = models.DateTimeField("Atualizado em", auto_now=True) def prioridade(self): if self.ativo: if self.criado_em > timezone.now() - timedelta(days=30): return 'prioridade' return 'sem prioridade' def __str__(self): return f'{self.nome} - CPF: {self.CPF}' class Meta: ordering = ['ativo']
class BRPersonProfile(models.Model): cpf = BRCPFField() cnpj = BRCNPJField() postal_code = BRPostalCodeField()
class Users(AbstractBaseUser, PermissionsMixin): """ Usuarios do sistema """ username = models.CharField( 'Usuário / E-mail', max_length=37, unique=True, validators=[ validators.RegexValidator( re.compile('^[\w.@+-]+$'), 'Informe um nome de usuário válido. ' 'Este valor deve conter apenas letras, números ' 'e os caracteres: @/./+/-/_ .', 'invalid') ], help_text= 'Um nome curto que será usado para identificá-lo de forma única na plataforma', default='', ) name = models.CharField('Nome', max_length=150, default='', validators=[ validators.RegexValidator( re.compile('[^\W\d_]+$', re.UNICODE), 'Digite um nome válido (somente letras)', 'invalido') ]) email = models.EmailField('Email', unique=True) is_staff = models.BooleanField('Equipe', default=False) is_active = models.BooleanField('Ativo', default=True) cpf = BRCPFField('CPF', unique=True, help_text='Somente Números') date_joined = models.DateTimeField("Data de Entrada", auto_now_add=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'email', 'cpf'] objects = CustomUserManager() class Meta: verbose_name = 'Conta' verbose_name_plural = "Contas" ordering = ['name'] def __str__(self): return self.name or self.email def get_short_name(self): return "{}".format(self.name.split()[0] or self.username) def get_create_url(self): return reverse('users:create') def get_update_url(self): return reverse('users:update', kwargs={'slug': self.username}) def get_unicode_name(self): # Unicode normalize transforma um caracter em seu equivalente em latin. nfkd = unicodedata.normalize('NFKD', self.name) title_unicode = u"".join( [c for c in nfkd if not unicodedata.combining(c)]) # Usa expressão regular para retornar a palavra apenas com números, letras e espaço title_unicode = re.sub('[^a-zA-Z0-9 \\\]', '', title_unicode) # title_unicode = title_unicode.replace(' ', '_') return title_unicode def save(self, **kwargs): if not self.username: self.username = uuid.uuid4() super().save(**kwargs)