|
| 1 | +from __future__ import annotations |
| 2 | +import logging |
| 3 | +from datetime import date |
| 4 | +from typing import Protocol, Optional |
| 5 | +import requests |
| 6 | +import requests.exceptions |
| 7 | + |
| 8 | +from domain import Shipment |
| 9 | + |
| 10 | + |
| 11 | +class CargoAPI(Protocol): |
| 12 | + |
| 13 | + def get_latest_eta(self, reference: str) -> date: |
| 14 | + ... |
| 15 | + |
| 16 | + def sync(self, shipment: Shipment) -> None: |
| 17 | + ... |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +class RealCargoAPI: |
| 22 | + API_URL = 'https://example.org' |
| 23 | + |
| 24 | + |
| 25 | + def get_latest_eta(self, reference: str) -> date: |
| 26 | + external_shipment_id = self._get_shipment_id(reference) |
| 27 | + if external_shipment_id is None: |
| 28 | + logging.warning( |
| 29 | + 'tried to get updated eta for shipment %s not yet sent to partners', |
| 30 | + reference |
| 31 | + ) |
| 32 | + return None |
| 33 | + |
| 34 | + [journey] = requests.get(f"{self.API_URL}/shipments/{external_shipment_id}/journeys").json()['items'] |
| 35 | + return date.fromisoformat(journey['eta']) |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + def sync(self, shipment: Shipment) -> None: |
| 40 | + external_shipment_id = self._get_shipment_id(shipment.reference) |
| 41 | + if external_shipment_id is None: |
| 42 | + requests.post(f'{self.API_URL}/shipments/', json={ |
| 43 | + 'client_reference': shipment.reference, |
| 44 | + 'arrival_date': shipment.eta.isoformat()[:10] if shipment.eta else None, |
| 45 | + 'products': [ |
| 46 | + {'sku': ol.sku, 'quantity': ol.qty} |
| 47 | + for ol in shipment.lines |
| 48 | + ] |
| 49 | + }) |
| 50 | + |
| 51 | + else: |
| 52 | + requests.put(f'{self.API_URL}/shipments/{external_shipment_id}/', json={ |
| 53 | + 'client_reference': shipment.reference, |
| 54 | + 'arrival_date': shipment.eta.isoformat()[:10] if shipment.eta else None, |
| 55 | + 'products': [ |
| 56 | + {'sku': ol.sku, 'quantity': ol.qty} |
| 57 | + for ol in shipment.lines |
| 58 | + ] |
| 59 | + }) |
| 60 | + |
| 61 | + |
| 62 | + def _get_shipment_id(self, our_reference) -> Optional[str]: |
| 63 | + try: |
| 64 | + their_shipments = requests.get(f"{self.API_URL}/shipments/").json()['items'] |
| 65 | + return next( |
| 66 | + (s['id'] for s in their_shipments if s['client_reference'] == our_reference), |
| 67 | + None |
| 68 | + ) |
| 69 | + |
| 70 | + except requests.exceptions.RequestException: |
| 71 | + logging.exception('Error retrieving shipment') |
| 72 | + raise |
0 commit comments