|
| 1 | +from datetime import timedelta |
| 2 | + |
| 3 | +from django.core.management.base import BaseCommand |
| 4 | +from django.db.models import Q |
| 5 | +from django.utils import timezone |
| 6 | + |
| 7 | +from erp.models import Activite, Erp |
| 8 | +from erp.provider.entreprise import check_closed |
| 9 | + |
| 10 | +IGNORED_ACTIVITIES = ["Administration publique", "Mairie", "Gendarmerie", "Bureau de poste"] |
| 11 | + |
| 12 | + |
| 13 | +class Command(BaseCommand): |
| 14 | + help = "Check for closed ERPs from outscraper API" |
| 15 | + |
| 16 | + def add_arguments(self, parser): |
| 17 | + parser.add_argument( |
| 18 | + "--start_pk", |
| 19 | + type=int, |
| 20 | + required=False, |
| 21 | + default=0, |
| 22 | + help="Resume the check since this given ERP PK in our DB.", |
| 23 | + ) |
| 24 | + parser.add_argument( |
| 25 | + "--write", |
| 26 | + default=False, |
| 27 | + action="store_true", |
| 28 | + help="Actually edit the database", |
| 29 | + ) |
| 30 | + |
| 31 | + parser.add_argument( |
| 32 | + "--nb_days", |
| 33 | + type=int, |
| 34 | + required=False, |
| 35 | + default=60, |
| 36 | + help="Check the ERPs which have not been checked in the last nb_days.", |
| 37 | + ) |
| 38 | + |
| 39 | + def _flag_erp_as_closed(self, existing_erp): |
| 40 | + print(f"Flag permanently closed ERP: {existing_erp} - {existing_erp.get_absolute_uri()}") |
| 41 | + if not self.write: |
| 42 | + print("Dry run mode, no DB action, use --write to apply this deletion") |
| 43 | + return |
| 44 | + |
| 45 | + existing_erp.permanently_closed = True |
| 46 | + existing_erp.save() |
| 47 | + |
| 48 | + def handle(self, *args, **options): |
| 49 | + self.write = options["write"] |
| 50 | + self.start_pk = options.get("start_pk") |
| 51 | + |
| 52 | + ignored_activities = Activite.objects.filter(nom__in=IGNORED_ACTIVITIES) |
| 53 | + if ignored_activities.count() != len(IGNORED_ACTIVITIES): |
| 54 | + print("Please check the IGNORED_ACTIVITIES list, at least one activity has not been found. Exit...") |
| 55 | + return |
| 56 | + |
| 57 | + limit_date = timezone.now() - timedelta(days=options["nb_days"]) |
| 58 | + qs = Erp.objects.published().filter(Q(check_closed_at=None) | Q(check_closed_at__lte=limit_date)) |
| 59 | + qs = qs.exclude(activite__in=ignored_activities) |
| 60 | + if self.start_pk: |
| 61 | + qs = qs.filter(pk__gte=self.start_pk) |
| 62 | + qs = qs.order_by("pk") |
| 63 | + |
| 64 | + for erp in qs.iterator(): |
| 65 | + print(f"Checking ERP with PK {erp.pk}") |
| 66 | + query = f"{erp.numero} {erp.voie}" if erp.numero else erp.lieu_dit |
| 67 | + query = f"{erp.nom}, {query} {erp.code_postal} {erp.commune}" |
| 68 | + |
| 69 | + if check_closed(query, erp.commune_ext.code_insee): |
| 70 | + self._flag_erp_as_closed(erp) |
| 71 | + continue |
| 72 | + |
| 73 | + if self.write: |
| 74 | + erp.check_closed_at = timezone.now() |
| 75 | + erp.save(update_fields=("check_closed_at",)) |
0 commit comments