diff --git a/lemarche/users/management/commands/cleanup_user_phone_field.py b/lemarche/users/management/commands/cleanup_user_phone_field.py new file mode 100644 index 000000000..ca1f830cb --- /dev/null +++ b/lemarche/users/management/commands/cleanup_user_phone_field.py @@ -0,0 +1,68 @@ +from django.core.management.base import BaseCommand +from phonenumber_field.phonenumber import PhoneNumber + +from lemarche.users.models import User + + +class Command(BaseCommand): + """ + This script is used to validate existing user phone numbers + And cleanup / replace them with valid numbers (with +33) + + Usage: + python manage.py cleanup_user_phone_field + python manage.py cleanup_user_phone_field --dry-run + """ + + def add_arguments(self, parser): + parser.add_argument("--dry-run", dest="dry_run", action="store_true", help="Dry run (no changes to the DB)") + + def handle(self, *args, **options): + self.stdout.write("-" * 80) + self.stdout.write(f"Users: {User.objects.count()}") + qs = User.objects.exclude(phone="") + self.stdout.write(f"Users with a phone: {qs.count()}") + + stats = { + "has_dot_count": 0, + "has_space_count": 0, + "without_plus_count": 0, + "valid_count": 0, + "invalid_count": 0, + } + invalid_list = list() + + for index, user in enumerate(qs): + valid = False + user_phone = str(user.phone) + + if "." in user_phone: + stats["has_dot_count"] += 1 + user_phone = user_phone.replace(".", "") + if " " in user_phone: + stats["has_space_count"] += 1 + user_phone = user_phone.replace(" ", "") + + if user_phone.isdigit() and len(user_phone) == 10: + user_phone = f"+33{user_phone[1:]}" + + if not user_phone.startswith("+"): + stats["without_plus_count"] += 1 + + try: + if user_phone.startswith("+") and PhoneNumber.from_string(user_phone).is_valid(): + valid = True + except: # noqa # NumberParseException.INVALID_COUNTRY_CODE + pass + + if valid: + stats["valid_count"] += 1 + if not options["dry_run"]: + pass # TODO + else: + stats["invalid_count"] += 1 + invalid_list.append(user_phone) + + print(stats) + # for num in invalid_list: + # print(num)