|
| 1 | +import logging |
| 2 | +import requests |
| 3 | +from typing import Union |
| 4 | +from datetime import datetime |
| 5 | +from django.utils.timezone import make_aware |
| 6 | +from django.core.management.base import BaseCommand |
| 7 | +from django.conf import settings |
| 8 | +from django.db import models |
| 9 | + |
| 10 | +from api.models import CronJob, CronJobStatus |
| 11 | +from country_plan.models import CountryPlan |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +NAME = 'ingest_country_plan_file' |
| 16 | +# Ref: https://github.com/IFRCGo/go-api/issues/1614 |
| 17 | +SOURCE = 'https://go-api.ifrc.org/api/publicsiteappeals?AppealsTypeID=1851&Hidden=false' |
| 18 | + |
| 19 | + |
| 20 | +class Command(BaseCommand): |
| 21 | + @staticmethod |
| 22 | + def parse_date(text: str) -> Union[datetime, None]: |
| 23 | + """ |
| 24 | + Convert Appeal API datetime into django datetime |
| 25 | + Parameters |
| 26 | + ---------- |
| 27 | + text : str |
| 28 | + Datetime eg: 2022-11-29T11:24:00 |
| 29 | + """ |
| 30 | + if text: |
| 31 | + return make_aware( |
| 32 | + # NOTE: Format is assumed by looking at the data from Appeal API |
| 33 | + datetime.strptime(text, '%Y-%m-%dT%H:%M:%S') |
| 34 | + ) |
| 35 | + |
| 36 | + def load_for_country(self, country_data): |
| 37 | + country_iso2 = country_data.get('LocationCountryCode') |
| 38 | + country_name = country_data.get('LocationCountryName') |
| 39 | + public_plan_url = country_data.get('BaseDirectory') or '' + country_data.get('BaseFileName') or '' |
| 40 | + inserted_date = self.parse_date(country_data.get('Inserted')) |
| 41 | + if ( |
| 42 | + (country_iso2 is None and country_name is None) or |
| 43 | + public_plan_url is None or |
| 44 | + inserted_date is None |
| 45 | + ): |
| 46 | + return |
| 47 | + country_plan = CountryPlan.objects.filter( |
| 48 | + models.Q(country__iso__iexact=country_iso2) | |
| 49 | + models.Q(country__name__iexact=country_name) |
| 50 | + ).first() |
| 51 | + if country_plan is None: |
| 52 | + logger.warning(f'{NAME} No country_plan found for: {(country_iso2, country_name)}') |
| 53 | + return |
| 54 | + if country_plan.appeal_api_inserted_date and country_plan.appeal_api_inserted_date >= inserted_date: |
| 55 | + # No need to do anything here |
| 56 | + return |
| 57 | + public_plan_url = country_data['BaseDirectory'] + country_data['BaseFileName'] |
| 58 | + country_plan.appeal_api_inserted_date = inserted_date |
| 59 | + country_plan.load_file_to_country_plan( |
| 60 | + public_plan_url, |
| 61 | + # NOTE: File provided are PDF, |
| 62 | + f"public-plan-{country_data['BaseFileName']}.pdf", |
| 63 | + ) |
| 64 | + country_plan.is_publish = True |
| 65 | + country_plan.save( |
| 66 | + update_fields=( |
| 67 | + 'appeal_api_inserted_date', |
| 68 | + 'public_plan_file', # By load_file_to_country_plan |
| 69 | + 'is_publish', |
| 70 | + ) |
| 71 | + ) |
| 72 | + return True |
| 73 | + |
| 74 | + def load(self): |
| 75 | + updated = 0 |
| 76 | + auth = (settings.APPEALS_USER, settings.APPEALS_PASS) |
| 77 | + results = requests.get(SOURCE, auth=auth, headers={'Accept': 'application/json'}).json() |
| 78 | + for result in results: |
| 79 | + try: |
| 80 | + if self.load_for_country(result): |
| 81 | + updated += 1 |
| 82 | + except Exception as ex: |
| 83 | + logger.error('Could not Updated countries plan', exc_info=True) |
| 84 | + country_info = ( |
| 85 | + result.get('LocationCountryCode'), |
| 86 | + result.get('LocationCountryName'), |
| 87 | + ) |
| 88 | + CronJob.sync_cron({ |
| 89 | + 'name': NAME, |
| 90 | + 'message': f"Could not updated country plan for {country_info}\n\nException:\n{str(ex)}", |
| 91 | + 'status': CronJobStatus.ERRONEOUS, |
| 92 | + }) |
| 93 | + return updated |
| 94 | + |
| 95 | + def handle(self, *args, **kwargs): |
| 96 | + try: |
| 97 | + logger.info('\nFetching data for country plans:: ') |
| 98 | + countries_plan_updated = self.load() |
| 99 | + CronJob.sync_cron({ |
| 100 | + 'name': NAME, |
| 101 | + 'message': 'Updated countries plan', |
| 102 | + 'num_result': countries_plan_updated, |
| 103 | + 'status': CronJobStatus.SUCCESSFUL, |
| 104 | + }) |
| 105 | + logger.info('Updated countries plan') |
| 106 | + except Exception as ex: |
| 107 | + logger.error('Could not Updated countries plan', exc_info=True) |
| 108 | + CronJob.sync_cron({ |
| 109 | + 'name': NAME, |
| 110 | + 'message': f'Could not Updated countries plan\n\nException:\n{str(ex)}', |
| 111 | + 'status': CronJobStatus.ERRONEOUS, |
| 112 | + }) |
0 commit comments