Last active
August 10, 2020 19:57
-
-
Save arkanister/2abc50fc8d4323456f5e6c12b8b9da21 to your computer and use it in GitHub Desktop.
CNPJ Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import itertools | |
| import random | |
| def _cnpj_dv(digits): | |
| """ | |
| Returns the calculated verification digit. | |
| """ | |
| mul = list(itertools.chain(*[range(len(digits) - 7, 1, -1), range(9, 1, -1)])) | |
| return ((sum([a * b for a, b in zip(digits, mul)]) * 10) % 11) % 10 | |
| def mask_cnpj(value): | |
| digits = ''.join(filter(lambda x: x.isdigit(), map(str, value or ''))) | |
| if not digits or len(digits) > 15: | |
| return value | |
| digits = '%015s' % digits | |
| return '%s.%s.%s/%s-%s' % (digits[:3], digits[3:6], digits[6:9], digits[9:13], digits[13:]) | |
| def generate_cnpj(mask=False): | |
| digits = [0] + [random.randint(0, 9) for _ in range(8)] + [0, 0, 0, 1] | |
| digits.append(_cnpj_dv(digits)) | |
| digits.append(_cnpj_dv(digits)) | |
| value = ''.join(map(str, digits)) | |
| return mask_cnpj(value) if mask else value | |
| def validate_cnpj(value): | |
| digits = list(map(int, filter(lambda x: x.isdigit(), value or ''))) | |
| length = len(digits) | |
| if not digits or length > 15: | |
| return False | |
| digits = ([0] * (15 - length)) + digits | |
| return digits[13] == _cnpj_dv(digits[:13]) and digits[14] == _cnpj_dv(digits[:14]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment