Esempio n. 1
0
    def index(self, **kwargs):
        """
        Look for clients in the web service of the DGII
            :param self:
            :param **kwargs dict :the parameters received
            :param term string : the character of the client or his rnc /
        """
        term = kwargs.get("term", False)
        query_dgii_wsmovil = request.env['ir.config_parameter'].sudo(
        ).get_param('dgii.wsmovil')
        if term and query_dgii_wsmovil == 'True':
            if term.isdigit() and len(term) in [9, 11]:
                result = rnc.check_dgii(term)
            else:
                result = rnc.search_dgii(term, end_at=20, start_at=1)
            if result is not None:
                if not isinstance(result, list):
                    result = [result]

                for d in result:
                    d["name"] = " ".join(
                        re.split(r"\s+", d["name"], flags=re.UNICODE)
                    )  # remove all duplicate white space from the name
                    d["label"] = u"{} - {}".format(d["rnc"], d["name"])
                return json.dumps(result)
Esempio n. 2
0
    def validate_rnc(self, **kwargs):
        """
        Check if the number provided is a valid RNC
            :param self:
            :param **kwargs dict :the parameters received
            :param rnc string : the character of the client or his rnc
        """
        num = kwargs.get("rnc", False)
        if num.isdigit():
            if (len(num) == 9
                    and rnc.is_valid(num)) or (len(num) == 11
                                               and cedula.is_valid(num)):
                try:
                    info = rnc.check_dgii(num)
                except Exception as err:
                    info = None
                    _logger.error(">>> " + str(err))

                if info is not None:
                    # remove all duplicate white space from the name
                    info["name"] = " ".join(
                        re.split(r"\s+", info["name"], flags=re.UNICODE))

                return json.dumps({"is_valid": True, "info": info})

        return json.dumps({"is_valid": False})
def check_dgii(number, timeout=30):  # pragma: no cover
    """Lookup the number using the DGII online web service.

    This uses the validation service run by the the Dirección General de
    Impuestos Internos, the Dominican Republic tax department to lookup
    registration information for the number. The timeout is in seconds.

    Returns a dict with the following structure::

        {
            'cedula': '12345678901',  # The requested number
            'name': 'The registered name',
            'commercial_name': 'An additional commercial name',
            'status': '2',            # 1: inactive, 2: active
            'category': '0',          # always 0?
            'payment_regime': '2',    # 1: N/D, 2: NORMAL, 3: PST
        }

    Will return None if the number is invalid or unknown."""
    # this function isn't automatically tested because it would require
    # network access for the tests and unnecessarily load the online service
    # we use the RNC implementation and change the rnc result to cedula
    result = rnc.check_dgii(number)
    if result and 'rnc' in result:
        result['cedula'] = result.pop('rnc')
    return result
Esempio n. 4
0
    def validate_rnc_cedula(self, number, model='partner'):
        if number:
            result, dgii_vals = {}, False
            model = 'res.partner' if model == 'partner' else 'res.company'

            if number.isdigit() and len(number) in (9, 11):
                message = u"El contacto: %s, está registrado con este RNC/Céd."
                contact = self.search([('vat', '=', number)])
                if contact:
                    name = contact.name if len(contact) == 1 else ", ".join(
                        [x.name for x in contact])
                    raise UserError(_(message % name))

                try:
                    is_rnc = len(number) == 9
                    rnc.validate(number) if is_rnc else cedula.validate(number)
                except Exception as e:
                    raise ValidationError(_(u"RNC/Ced Inválido"))

                dgii_vals = rnc.check_dgii(number)
                if dgii_vals is None:
                    if is_rnc:
                        raise ValidationError(_("RNC no disponible en DGII"))
                    result['vat'] = number
                    result['sale_fiscal_type'] = "final"
                else:
                    result['name'] = dgii_vals.get(
                        "name", False) or dgii_vals.get("commercial_name", "")
                    result['vat'] = dgii_vals.get('rnc')

                    if model == 'res.partner':
                        result['is_company'] = True if is_rnc else False,
                        result['sale_fiscal_type'] = "fiscal"
            return result
Esempio n. 5
0
def check_dgii(number, timeout=30):  # pragma: no cover
    """Lookup the number using the DGII online web service.

    This uses the validation service run by the the Dirección General de
    Impuestos Internos, the Dominican Republic tax department to lookup
    registration information for the number. The timeout is in seconds.

    Returns a dict with the following structure::

        {
            'cedula': '12345678901',  # The requested number
            'name': 'The registered name',
            'commercial_name': 'An additional commercial name',
            'status': '2',            # 1: inactive, 2: active
            'category': '0',          # always 0?
            'payment_regime': '2',    # 1: N/D, 2: NORMAL, 3: PST
        }

    Will return None if the number is invalid or unknown."""
    # this function isn't automatically tested because it would require
    # network access for the tests and unnecessarily load the online service
    # we use the RNC implementation and change the rnc result to cedula
    result = rnc.check_dgii(number)
    if result and 'rnc' in result:
        result['cedula'] = result.pop('rnc')
    return result
Esempio n. 6
0
    def _check_rnc(self):
        for partner_rnc in self:
            if partner_rnc.vat:
                if (
                    len(partner_rnc.vat) not in [9, 11]
                ):
                    raise UserError(
                        _(
                            "Check Vat Format or should not have any Caracter like '-'"
                        )
                    )
                    
                if (
                    not (
                        (len(partner_rnc.vat) == 9 and rnc.is_valid(partner_rnc.vat))
                        or (len(partner_rnc.vat) == 11 and cedula.is_valid(partner_rnc.vat))
                    )
                ):

                    raise UserError(
                        _(
                            "Check Vat, Seems like it's not correct"
                        )
                    )
                else:

                    result = rnc.check_dgii(partner_rnc.vat)
                    if result is not None:
                        # remove all duplicate white space from the name
                        result["name"] = " ".join(
                            re.split(r"\s+", result["name"], flags=re.UNICODE))
                        
                        partner_rnc.name = result["name"]
Esempio n. 7
0
    def validate_rnc_cedula(self, number):
        if number:
            if number.isdigit() and len(number) in (9, 11):
                message = "El contacto: %s, esta registrado con este RNC/Céd."
                contact = self.search([('vat', '=', number)])
                if contact:
                    name = contact.name if len(contact) == 1 else ", ".join(
                        [x.name for x in contact])
                    raise UserError(_(message % name))

                is_rnc = len(number) == 9
                try:
                    rnc.validate(number) if is_rnc else cedula.validate(number)
                except Exception as e:
                    raise ValidationError(_("RNC/Ced Inválido"))

                dgii_vals = rnc.check_dgii(number)

                if dgii_vals is None:
                    if is_rnc:
                        raise ValidationError(_("RNC no disponible en DGII"))
                    self.vat = number
                else:
                    self.name = dgii_vals.get("name", False) or dgii_vals.get(
                        "commercial_name", "")
                    self.vat = dgii_vals.get('rnc')
                    self.is_company = True if is_rnc else False,
                    self.sale_fiscal_type = "fiscal" if is_rnc else "final"
Esempio n. 8
0
 def test_check_dgii(self):
     """Test stdnum.do.rnc.check_dgii()"""
     # Test a normal valid number
     result = rnc.check_dgii('131098193')
     self.assertTrue(all(
         key in result.keys()
         for key in ['rnc', 'name', 'commercial_name', 'category', 'status']))
     self.assertEqual(result['rnc'], '131098193')
     # Test an invalid length number
     self.assertIsNone(rnc.check_dgii('123'))
     # Test a number with an invalid checksum
     self.assertIsNone(rnc.check_dgii('112031226'))
     # Valid number but unknown
     self.assertIsNone(rnc.check_dgii('814387152'))
     # Test a number on the whitelist
     result = rnc.check_dgii('501658167')
     self.assertEqual(result['rnc'], '501658167')
 def test_check_dgii(self):
     """Test stdnum.do.rnc.check_dgii()"""
     # Test a normal valid number
     result = rnc.check_dgii('131098193')
     self.assertTrue(all(
         key in result.keys()
         for key in ['rnc', 'name', 'commercial_name', 'category', 'status']))
     self.assertEqual(result['rnc'], '131098193')
     # Test an invalid length number
     self.assertIsNone(rnc.check_dgii('123'))
     # Test a number with an invalid checksum
     self.assertIsNone(rnc.check_dgii('112031226'))
     # Valid number but unknown
     self.assertIsNone(rnc.check_dgii('814387152'))
     # Test a number on the whitelist
     result = rnc.check_dgii('501658167')
     self.assertEqual(result['rnc'], '501658167')
Esempio n. 10
0
    def create(self, vals):
        if vals.get("sale_fiscal_type", None) == "fiscal":

            partner_id = self.env["res.partner"].browse(vals['partner_id'])

            if partner_id and partner_id.vat:
                if len(partner_id.vat) not in [
                        9, 11
                ] or not rnc.check_dgii(str(partner_id.vat)):
                    raise ValidationError(
                        _("El RNC del cliente NO pasó la validación en DGII\n\n"
                          "No es posible crear una factura con Crédito Fiscal "
                          "si el RNC del cliente es inválido."
                          "Verifique el RNC del cliente a fin de corregirlo y "
                          "vuelva a guardar la factura"))

        return super(AccountInvoice, self).create(vals)
Esempio n. 11
0
    def validate_rnc_cedula(self, number, model='partner'):
        if number:
            result, dgii_vals = {}, False
            model = 'res.partner' if model == 'partner' else 'res.company'

            if number.isdigit() and len(number) in (9, 11):
                message = "El contacto: %s, esta registrado con este RNC/Céd."
                self_id = self.id if self.id else 0
                # Considering multi-company scenarios
                domain = [('vat', '=', number), ('id', '!=', self_id),
                          ('parent_id', '=', False)]
                if self.env.ref('base.res_partner_rule').active:
                    domain.extend([('company_id', '=',
                                    self.env.user.company_id.id)])
                contact = self.search(domain)

                if contact:
                    name = contact.name if len(contact) == 1 else ", ".join(
                        [x.name for x in contact if x.name])
                    raise UserError(_(message) % name)

                try:
                    is_rnc = len(number) == 9
                    rnc.validate(number) if is_rnc else cedula.validate(number)
                except Exception:
                    _logger.warning(
                        "RNC/Ced Inválido en el contacto {}".format(self.name))

                dgii_vals = rnc.check_dgii(number)
                if dgii_vals is None:
                    if is_rnc:
                        _logger.error(
                            "RNC {} del contacto {} no está disponible en DGII"
                            .format(number, self.name))
                    result['vat'] = number
                    result['sale_fiscal_type'] = "final"
                else:
                    result['name'] = dgii_vals.get(
                        "name", False) or dgii_vals.get("commercial_name", "")
                    result['vat'] = dgii_vals.get('rnc')

                    if model == 'res.partner':
                        result['is_company'] = True if is_rnc else False
                        result['sale_fiscal_type'] = "fiscal"
            return result