-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Management command to cleanup existing user phones
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
68 changes: 68 additions & 0 deletions
68
lemarche/users/management/commands/cleanup_user_phone_field.py
This file contains 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
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) |