Skip to content

Commit

Permalink
Management command to cleanup existing user phones
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn committed May 15, 2024
1 parent 2b6d03b commit 2703a78
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions lemarche/users/management/commands/cleanup_user_phone_field.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 2703a78

Please sign in to comment.