Пример #1
0
 def create(self, request, *args, **kwargs):
     data = deepcopy(request.data)
     serializer = self.serializer_class(data=data)
     try:
         if not serializer.initial_data.get('data_nascimento'):
             return Response({
                 'errors': "'data_nascimento' is required!"
             }, status=status.HTTP_400_BAD_REQUEST)
         serializer.initial_data['data_nascimento'] = datetime.strptime(
             serializer.initial_data['data_nascimento'], '%d/%m/%Y')
     except Exception:
         return Response({
             'errors': "Incorrect data format, should be DD/MM/YYYY"
         }, status=status.HTTP_400_BAD_REQUEST)
     if serializer.is_valid():
         if not cpfcnpj.validate(data['cpf']):
             return Response({
                 'message': 'CPF Inválido!',
                 'errors': ""
             }, status=status.HTTP_400_BAD_REQUEST)
         serializer.validated_data['inativo'] = None
         serializer.validated_data['data_nascimento'] = serializer.initial_data['data_nascimento']
         serializer.save()
         return Response(formatar_paciente_dict(serializer.validated_data), status=status.HTTP_201_CREATED)
     return Response({
         'errors': serializer.errors,
         'message': 'Preencha todos os campos corretamente!'
     }, status=status.HTTP_400_BAD_REQUEST)
Пример #2
0
def validate_registration(form, field):
    # TODO: Improve string sanatization
    value = field.data.replace('.', '')
    value = value.replace('-', '')

    if not cpfcnpj.validate(value):
        raise ValidationError(u"O CPF não é válido.")
    def update(self, instance, validated_data):
        self.update_address(instance.address, validated_data['address'])

        instance.fullName = validated_data['fullName']
        if validated_data['photo'] is not None:
            photo = validated_data['photo'].split(',')
            image64 = photo[1]
            instance.photo = store_image(directory='usuario',
                                         photo_name=instance.id,
                                         image64=image64)
        instance.birthDate = validated_data['birthDate']
        instance.nationality = validated_data['nationality']
        if validated_data['genre'] is not None:
            if validated_data['genre'] == 'M' or validated_data['genre'] == 'F':
                instance.genre = validated_data['genre']
            else:
                raise Exception('Genre tem que ser M ou F')

        if validated_data['cpf'] is not None:
            if not cpfcnpj.validate(validated_data['cpf']):
                raise Exception('CPF Inválido')

            instance.cpf = validated_data['cpf']

        instance.state = validated_data['blocked']
        instance.facebook = validated_data['facebook']
        instance.instagram = validated_data['instagram']
        instance.linkedin = validated_data['linkedin']
        instance.celular = validated_data['celular']

        instance.save()

        return instance
Пример #4
0
def validate_registration(form, field):
    # TODO: Improve string sanatization
    value = field.data.replace('.', '')
    value = value.replace('-', '')

    if not cpfcnpj.validate(value):
        raise ValidationError(u"O CPF não é válido.")
Пример #5
0
 def get(self, cpf):
     # checa se CPF tem numero valido
     if cpfcnpj.validate(cpf):
         # remove mascara do cpf se veio mascarado
         unmasked_cpf = cpfcnpj.clear_punctuation(cpf)
         if self.get_auth_token():
             url = self.CHECK_CPF_URL + unmasked_cpf
             headers = {
                 'Authorization': 'Bearer ' + self.bearer_token,
                 'Accept': 'application/json'
             }
             # tenta se conectar na API por X vezes antes de efetuar um raise de erro
             for i in range(self.CONNECTION_RETRY_LIMIT):
                 try:
                     response = requests.get(url,
                                             headers=headers,
                                             timeout=1)
                     response.raise_for_status()
                 except Exception:
                     continue
                 else:
                     # retorna dicionario com informacoes da SERPRO
                     return json.loads(response.text)
             else:
                 raise ConnectionError(
                     "Nao foi possivel se conectar na SERPRO")
         else:
             raise ConnectionError("Nao foi possivel gerar o Bearer Token")
     else:
         raise ValueError('Numero de CPF invalido')
Пример #6
0
    def validate(self, data):
        document_clear = cpfcnpj.clear_punctuation(data['document'])
        if not cpfcnpj.validate(document_clear) \
                or len(document_clear) != 14:
            raise serializers.ValidationError('This document is invalid')

        return data
Пример #7
0
    def create(self, vals):
        # Valida CPF
        if not cpfcnpj.validate(vals['cpf_cnpj']):
            raise Warning(u'CPF invalido.')

        pelo_exportador = False
        # Verifica se o usuário foi criado pelo exportador Master
        if not self.env.context.get('no_reset_password'):
            # Adiciona ao contexto que o e-mail enviado será o de criação
            # de usuário
            context = dict(self.env.context)
            context['no_reset_password'] = True
            context['create_user'] = False
            self.env.context = context
            pelo_exportador = True

        # Cria o usuário
        res = super(ResUsers, self).create(vals)

        # Adiciona dados ao partner
        res.partner_id.cpf_cnpj = vals['cpf_cnpj']
        res.partner_id.user_id = res.id

        # Gera token
        token = CryptContext(['pbkdf2_sha512']).encrypt(vals['password'])
        res.token = token

        # Se o cadastro foi através do exportador
        if pelo_exportador:
            res.mapped('partner_id').signup_prepare(signup_type="reset")
            # Envia email de ativação
            template = self.env.ref('sce.usuario_criar_senha_email',
                                    raise_if_not_found=False)
            if res and template:
                template.sudo().with_context(
                    lang=res.lang,
                    auth_login=werkzeug.url_encode({'auth_login': res.token}),
                ).send_mail(res.id, force_send=True)

        # Se o cadastro foi através do site
        else:
            # Envia email de ativação
            template = self.env.ref(
                'sce.mail_template_user_signup_account_created_verify',
                raise_if_not_found=False)
            if res and template:
                template.sudo().with_context(
                    lang=res.lang,
                    auth_login=werkzeug.url_encode({'auth_login': res.token}),
                ).send_mail(res.id, force_send=True)
            # Desativa usuário
            res.active = False

        # GRUPOS
        groups = self.env['res.groups']
        group_exp_id = groups.search([('name', '=', 'Exportador')])
        res.groups_id = False
        res.groups_id = group_exp_id

        return res
Пример #8
0
    def clean_cpf(self):
        typed_cpf = clear_punctuation(self.cleaned_data['cpf'])
        if not cpf.validate(typed_cpf):
            raise forms.ValidationError(self.error_messages['invalid_cpf'],
                                        code='invalid_cpf')

        return typed_cpf
Пример #9
0
async def base_c(request, cpf):
    result = await app.mongo['test'].basea.find_one({'cpf': cpf})
    if not cpf or not cpfcnpj.validate(cpf) or not result:
        return json({'Error': f'CPF {cpf} does not exist or invalid'},
                    400,
                    headers={'Content-type': 'application/json'})
    return json(result, 200)
Пример #10
0
        def saveCli():
            try:
                name = self.cliedit.leName.text().title()
                assert name, 'Digite o nome do cliente!'
                birth = self.cliedit.deBirthFun.date().toString('dd/MM/yyyy')
                idade = int(QtCore.QDate.currentDate().toString('dd/MM/yyyy')[6:10]) - int(birth[6:10])
                if self.cliedit.buttonGroup.checkedButton().text() == 'PF':
                    assert idade >= 18, 'Este cliente tem menos de 18 anos!'
                cpfcnpj = self.cliedit.leCpfCnpj.text().strip()
                assert cpfcnpjv.validate(cpfcnpj), 'CPF/CNPJ inválido!'
                rgie = self.cliedit.leRgIe.text().strip()
                email = self.cliedit.leMail.text().strip()
                if self.cliedit.leCodCli.text():
                    sql = f"""UPDATE clients SET altdate = '{QtCore.QDateTime.currentDateTime().toString("dd/MM/yyyy hh:mm:ss")}', lastAlter={self.userId}, blocked = '{int(self.cliedit.checkBox.isChecked())}',
                    name = '{name}', birthFun = '{birth}', sex = {self.cliedit.buttonGroup_2.checkedId()}, cpfcnpj='{cpfcnpj}', rgie = NULLIF('{rgie}', ''),
                    phone1op = '{self.cliedit.cbPhone1.currentText()}', phone1 = '{self.cliedit.lePhone1.text()}', phone2op = '{self.cliedit.cbPhone2.currentText()}',
                    phone2 = '{self.cliedit.lePhone2.text()}', phone3 = '{self.cliedit.lePhone3.text()}', email = NULLIF('{email}', ''), cep = '{self.cliedit.leCep.text()}',
                    adress = '{self.cliedit.leStreet.text()}', number = '{self.cliedit.leNumber.text()}', adress2 = '{self.cliedit.leComp.text()}',
                    district = '{self.cliedit.leDistrict.text()}', city = '{self.cliedit.leCity.text()}', state = '{self.cliedit.leState.text()}', contry = '{self.cliedit.leContry.text()}' WHERE id={int(self.cliedit.leCodCli.text())}"""
                    self.dbConn.queryDB(sql)
                    loadCli(int(self.cliedit.leCodCli.text()))
                else:
                    sql = f"""INSERT INTO clients (regdate, altdate, lastAlter, regtype, blocked,
                    name, birthFun, sex, cpfcnpj, rgie, phone1op, phone1, phone2op, phone2, phone3, email, cep,
                    adress, number, adress2, district, city, state, contry)
                    VALUES ('{QtCore.QDateTime.currentDateTime().toString('dd/MM/yyyy hh:mm:ss')}',
                    '{QtCore.QDateTime.currentDateTime().toString('dd/MM/yyyy hh:mm:ss')}',
                    {self.userId}, {self.cliedit.buttonGroup.checkedId()},
                    '{int(self.cliedit.checkBox.isChecked())}', '{name}', '{birth}',
                    {self.cliedit.buttonGroup_2.checkedId()},
                    '{cpfcnpj}', NULLIF('{rgie}', ''), '{self.cliedit.cbPhone1.currentText()}',
                    '{self.cliedit.lePhone1.text()}', '{self.cliedit.cbPhone2.currentText() }', '{self.cliedit.lePhone2.text()}',
                    '{self.cliedit.lePhone3.text()}', NULLIF('{email}', ''),
                    '{self.cliedit.leCep.text()}', '{self.cliedit.leStreet.text()}',
                    '{self.cliedit.leNumber.text()}', '{self.cliedit.leComp.text()}',
                    '{self.cliedit.leDistrict.text()}', '{self.cliedit.leCity.text()}',
                    '{self.cliedit.leState.text()}', '{self.cliedit.leContry.text()}')"""
                    #print('SQL SaveCli: ', sql)
                    lrid = self.dbConn.queryDB(sql)
                    #print('Last row id: ', lrid)
                    loadCli(lrid)

            except sqlite3.IntegrityError as e:
                msg = QMessageBox()
                msg.setWindowTitle('Falha ao salvar.')
                #print(e.args)
                if 'clients.email' in e.args[0]:
                    msg.setText(f'Este E-mail já está sendo utilizado.')
                if 'clients.cpfcnpj' in e.args[0]:
                    msg.setText(f'Este CPF/CNPJ já está sendo utilizado.')
                if 'clients.rgie' in e.args[0]:
                    msg.setText(f'Este RG/IE já está sendo utilizado.')
                msg.exec_()
            except AssertionError as e:
                msg = QMessageBox()
                msg.setWindowTitle('Falha ao salvar.')
                #print(e.args)
                msg.setText(e.args[0])
                msg.exec_()
    def document_is_valid(self, document):
        document = self.format_document(document)
        for number in document:
            if number.isalpha():
                return False

        validate = cpfcnpj.validate(document)
        return validate
Пример #12
0
 def get(self):
     cpf = request.args.get("cpf")
     if not cpfcnpj.validate(cpf):
         return {'message': f"invalid cpf"}
     r = requests.get(f'http://{HOST_NAME}{PORT}/base_2?cpf={compatible.clear_punctuation(cpf)}').json()
     if not r:
         return {'message': f"cpf {cpf} doesn\'t exist"}
     return jsonify(r)
Пример #13
0
    def __new__(cls, *args, **kwargs):
        cls.errors.update({'cpf_invalid': 'O CPF fornecido é inválido'})
        value = super().__new__(cls, *args, **kwargs)

        if not cpfcnpj.validate(value):
            raise TypeSystemError(cls=cls, code='cpf_invalid')

        return value
Пример #14
0
def adesao(request):
    if request.method=="POST":
        cnpj=request.POST['CNPJ']
        if cpfcnpj.validate(cnpj)==False:
            messages.info(request, 'O CNPJ é inválido')
            return render(request,'index.html')

        else:
            return render(request,'page.html')
Пример #15
0
def validate_cpfcnpj(value, required=False, verbose=None):
    value = ''.join([c for c in str(value) if c.isdigit()])
    if not value:
        if required:
            raise ValidationError(_(f'{verbose} required'))
        return value

    if not cpfcnpj.validate(value):
        raise ValidationError(_(f'{verbose} invalid'))

    return value
Пример #16
0
 def post(self, request):
     try:
         serializer = CompanySerializer(data=request.data)
         cnpj = request.data['cnpj']
         if cpfcnpj.validate(cnpj) and serializer.is_valid():
             serializer.save()
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED)
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     except Exception:
         return JsonResponse({"mensagem": "Ocorreu um erro no servidor"},
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Пример #17
0
    def validate_custom_fields(self, **kwargs):
        """
        O :attr:`taxpayer_id` precisa ser um CPF ou CNPJ válido. Então verificamos isso.

        Args:
            **kwargs:
        """
        errors = []

        if self._allow_empty:
            return errors

        if not cpfcnpj.validate(self.taxpayer_id):
            errors.append(FieldError("taxpayer_id", "taxpayer_id inválido!"))
        return errors
Пример #18
0
 def validateCPF(self, cpf):
     if not cpfcnpj.validate(cpf):
         raise Exception('CPF inválido')
     else:
         allow = ["supervisor", "gerente", "diretor"]
         user = self.interface.getDataByField('users', 'cpf', cpf)
         if not user:
             raise Exception('Não foi encontrado usuário com esse cpf')
         print (user)
         c = 0
         for a in allow:
             if a in str(user):
                 c += 1
         if c == 0:
             raise Exception('Esse usuário não tem permissão')
Пример #19
0
    def validate(self, attrs):
        cpf = attrs['cpf']
        if not cpfcnpj.validate(cpf):
            raise serializers.ValidationError({'cpf': 'Invalid CPF number.'})

        telephone = attrs['telephone']
        pattern_telephone = re.compile(r'^\d{10,11}$')
        # Checks if a given phone is valid acording to format:
        # 11 1234 5678 or 11 9 1234 5678
        # without spaces or signs.
        if not bool((re.fullmatch(pattern_telephone, telephone))):
            raise serializers.ValidationError(
                {'telephone': 'Invalid telephone number.'})

        return attrs
Пример #20
0
def check_cpf(cpf):
    try:
        global dropatempt
        global dropped
        print('check_cpf')
        test = cpfcnpj.validate(cpf)
        print(test)

        eel.python_errors(test)

        if test == True:
            dropatempt = 0
            dropped = False
            check_motor()

    except:
        eel.python_errors('Exception')
    def salvarDados(self):
        print("Salvando...")

        self.nome = str(e1.get())
        self.cpf = str(e2.get())
        self.file = './training/' + str(self.cpf) + '.yml'
        print(self.nome, self.cpf)

        if cpfcnpj.validate(self.cpf):
            if not os.path.isfile(self.file):
                self.facialRecognation()
            else:
                messagebox.showerror("Erro", "O CPF já foi cadastrado!")
        else:
            messagebox.showerror("Erro", "CPF inválido!")

        self.Tela.destroy()
    def Entrar(self):

        print("Entrou")
        self.cpf = e3.get()
        if cpfcnpj.validate(self.cpf):
            self.file = './training/' + str(self.cpf) + '.yml'
            try:
                if os.path.isfile(self.file):
                    self.imagem_entrar()
                else:
                    messagebox.showerror("Erro", "CPF não está cadastrado")
            except:
                print('Error')

        else:
            messagebox.showerror("Erro", "CPF inválido")

        self.Tela.destroy()
Пример #23
0
    def create(self, vals):
        vals['parent_id'] = self.env.user.partner_id.id
        vals['active'] = False
        if not cpfcnpj.validate(vals['cpf_cnpj']):
            raise Warning(u'CNPJ invalido.')
        else:
            if self.env['exportador'].search([('cpf_cnpj', '=',
                                               vals['cpf_cnpj'])]).id:
                raise Warning(u'CNPJ já cadastrado.')

        res = super(Exportador, self).create(vals)
        # Vincula o usuário que criou ao grupo de funcionários
        vals = {
            'funcionario_id': self.env.user.partner_id.id,
            'exportador_id': res.id,
        }
        res.funcionario_exportador_ids.create(vals)

        return res
Пример #24
0
def criar_cliente():
    clear_screen()

    print('\nAdicionar novo cliente')

    nome = str(input('Nome:')).upper()

    while True:
        cpf_number = str(input('CPF:'))
        validado = cpfcnpj.validate(cpf_number)

        if validado:
            break
        else:
            print('Erro. Favor inserir um CPF válido')

    ano_nasc = int(input('Ano de Nascimento:'))

    cliente = Cliente(nome, cpf_number, ano_nasc)

    print(f'Idade: {cliente.idade}')

    return cliente
Пример #25
0
    def write(self, vals):
        '''

        :param vals:
        :return:
        '''
        # Verifica se o CNPJ é válido
        if 'cpf_cnpj' in vals and self.is_company:
            if not cpfcnpj.validate(vals['cpf_cnpj']):
                raise Warning(u'CNPJ invalido.')

        if self.env.user.has_group('sce.group_exportador'):
            if self.state != 'rascunho':
                campos_permitidos = ['exportador_linha_negocio_ids']
                result = all(elem in campos_permitidos
                             for elem in list(vals.keys()))
                if result:
                    vals['state'] = 'rascunho'
                    res = super(Exportador, self).sudo().write(vals)
                    self.enviar_cadastro()

                    return res

        return super(Exportador, self).write(vals)
Пример #26
0
 def post(self, request, pk):
     try:
         if pk <= "0":
             return JsonResponse(
                 {"mensagem": "O ID tem que ser maior que 0"},
                 status=status.HTTP_400_BAD_REQUEST)
         company = Company.objects.get(pk=pk)
         serializer = CompanySerializer(company, data=request.data)
         cnpj = request.data['cnpj']
         if cpfcnpj.validate(cnpj) and serializer.is_valid():
             serializer.save()
             return Response(serializer.data)
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     except Company.DoesNotExist:
         return JsonResponse({"mensagem": "A empresa não existe"},
                             status=status.HTTP_400_BAD_REQUEST)
     except Exception:
         return JsonResponse(
             {
                 "mensagem":
                 "Ocorreu um erro em skeel/views.py/EditCompanyByID"
             },
             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Пример #27
0
 def test_validate_unicode_cnpj_true(self):
     self.assertTrue(cpfcnpj.validate(u'11444777000161'))
Пример #28
0
def cpf_check(form, field):
    if not (cpfcnpj.validate(field.data)) or not(str.isdigit(field.data)):
        raise ValidationError('CPf not valid')
Пример #29
0
 def test_validate_cnpj_false(self):
     self.assertFalse(cpfcnpj.validate(self.invalid_cnpj))
Пример #30
0
 def mascared_test_validate_cnpj_true(self):
     self.assertTrue(cpfcnpj.validate(self.mascared_valid_cnpj))
Пример #31
0
 def validate_cpf(self, key, cnpj) -> str:
     if not len(cnpj) == 11:
         raise ValueError('invalid cpf')
     if not cpfcnpj.validate(cnpj):
         raise ValueError('invalid cpf')
     return cnpj
Пример #32
0
 def clean_cpf_cnpj(self):
     if not cpfcnpj.validate(self.cleaned_data.get('cpf_cnpj').replace('.', '').replace('/', '').replace('-', '')):
         raise forms.ValidationError(_('Invalid value for this Field'))
     return self.cleaned_data.get('cpf_cnpj')
Пример #33
0
 def test_validate_unicode_cpf_tru(self):
     self.assertTrue(cpfcnpj.validate(u"11144477735"))
Пример #34
0
 def test_validate_cnpj_true(self):
     self.assertTrue(cpfcnpj.validate(self.valid_cnpj))
 def __is_invalid(self, row):
     return (row['document_type'] in ['bill_of_sale', 'simple_receipt']) \
         & (not cpfcnpj.validate(str(row['recipient_id'])))
Пример #36
0
def validate_cpf(value):
    if not cpfcnpj.validate(value):
        raise ValidationError('CPF inválido')
Пример #37
0
 def mascared_test_validate_cnpj_false(self):
     self.assertFalse(cpfcnpj.validate(self.mascared_invalid_cnpj))
Пример #38
0
 def test_wrong_cnpj_size(self):
     self.assertFalse(cpfcnpj.validate(self.invalid_cnpj_size))
Пример #39
0
 def validateCPF(self, cpf):
     if not cpfcnpj.validate(cpf):
         raise Exception('CPF inválido')
Пример #40
0
 def mascared_test_wrong_cnpj_size(self):
     self.assertFalse(cpfcnpj.validate(self.mascared_invalid_cnpj_size))