Skip to content

Commit

Permalink
Add shipmentType and DeliveryAddressType (#34)
Browse files Browse the repository at this point in the history
- Add ShipmentType and DeliveryAddressType.
- Add more debug information.
  • Loading branch information
geert36 authored Jan 26, 2025
1 parent 8e52de6 commit a4470dd
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 15 deletions.
26 changes: 17 additions & 9 deletions custom_components/postnl/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

_LOGGER = logging.getLogger(__name__)


class PostNLCoordinator(DataUpdateCoordinator):
data: dict[str, list[Package]]
graphq_api: PostNLGraphql
Expand All @@ -28,11 +27,13 @@ def __init__(self, hass: HomeAssistant) -> None:
name="PostNL",
update_interval=timedelta(seconds=90),
)

_LOGGER.debug("PostNLCoordinator initialized with update interval: %s", self.update_interval)

async def _async_update_data(self) -> dict[str, list[Package]]:
_LOGGER.debug('Get API data')
_LOGGER.debug("Starting data update for PostNL.")
try:
auth: AsyncConfigEntryAuth = self.hass.data[DOMAIN][self.config_entry.entry_id]['auth']
_LOGGER.debug("Authenticating with PostNL API.")
await auth.check_and_refresh_token()

self.graphq_api = PostNLGraphql(auth.access_token)
Expand All @@ -45,6 +46,7 @@ async def _async_update_data(self) -> dict[str, list[Package]]:

shipments = await self.hass.async_add_executor_job(self.graphq_api.shipments)

_LOGGER.debug("Shipments fetched: %s", shipments)
receiver_shipments = [self.transform_shipment(shipment) for shipment in
shipments.get('trackedShipments', {}).get('receiverShipments', [])]
data['receiver'] = await asyncio.gather(*receiver_shipments)
Expand All @@ -53,10 +55,11 @@ async def _async_update_data(self) -> dict[str, list[Package]]:
shipments.get('trackedShipments', {}).get('senderShipments', [])]
data['sender'] = await asyncio.gather(*sender_shipments)

_LOGGER.debug('Found %d packages', len(data['sender']) + len(data['receiver']))
_LOGGER.info("Updated PostNL data: %d receiver packages, %d sender packages.", len(data['receiver']), len(data['sender']))

return data
except requests.exceptions.RequestException as exception:
_LOGGER.error("Network error during PostNL data update: %s", exception, exc_info=True)
raise UpdateFailed("Unable to update PostNL data") from exception

async def transform_shipment(self, shipment) -> Package:
Expand All @@ -70,23 +73,26 @@ async def transform_shipment(self, shipment) -> Package:
key=shipment.get('key'),
name=shipment.get('title'),
url=shipment.get('detailsUrl'),
shipment_type=shipment.get('shipmentType'),
status_message="Pakket is bezorgd",
delivered=shipment.get('delivered'),
delivery_date=shipment.get('deliveredTimeStamp')
delivery_date=shipment.get('deliveredTimeStamp'),
delivery_address_type=shipment.get('deliveryAddressType')
)

_LOGGER.debug("Fetching Track and Trace details for shipment %s.", shipment['key'])
track_and_trace_details = await self.hass.async_add_executor_job(self.jouw_api.track_and_trace,
shipment['key'])

if not track_and_trace_details.get('colli'):
_LOGGER.debug('No colli found.')
_LOGGER.debug(track_and_trace_details)
_LOGGER.warning("No colli found for shipment %s. Details: %s", shipment['key'], track_and_trace_details)

colli = track_and_trace_details.get('colli', {}).get(shipment['barcode'], {})

status_message = "Unknown"

if colli:
_LOGGER.debug("Colli details found for shipment %s: %s", shipment['key'], colli)
if colli.get("routeInformation"):
route_information = colli.get("routeInformation")
planned_date = route_information.get("plannedDeliveryTime")
Expand All @@ -106,8 +112,7 @@ async def transform_shipment(self, shipment) -> Package:

status_message = colli.get('statusPhase', {}).get('message', "Unknown")
else:
_LOGGER.debug('Barcode not found in track and trace details.')
_LOGGER.debug(track_and_trace_details)
_LOGGER.warning("Barcode not found in colli details for shipment %s.", shipment['key'])
planned_date = shipment.get('deliveryWindowFrom', None)
planned_from = shipment.get('deliveryWindowFrom', None)
planned_to = shipment.get('deliveryWindowTo', None)
Expand All @@ -117,13 +122,16 @@ async def transform_shipment(self, shipment) -> Package:
key=shipment.get('key'),
name=shipment.get('title'),
url=shipment.get('detailsUrl'),
shipment_type=shipment.get('shipmentType'),
status_message=status_message,
delivered=shipment.get('delivered'),
delivery_date=shipment.get('deliveredTimeStamp'),
delivery_address_type=shipment.get('deliveryAddressType'),
planned_date=planned_date,
planned_from=planned_from,
planned_to=planned_to,
expected_datetime=expected_datetime
)
except requests.exceptions.RequestException as exception:
_LOGGER.error("Error fetching Track and Trace details for shipment %s: %s", shipment.get('key'), exception, exc_info=True)
raise UpdateFailed("Unable to update PostNL data") from exception
12 changes: 9 additions & 3 deletions custom_components/postnl/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,17 @@

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities):
"""Set up the PostNL sensor platform."""
_LOGGER.debug("Setting up PostNL sensors")

coordinator = PostNLCoordinator(hass)

await coordinator.async_config_entry_first_refresh()
userinfo = hass.data[DOMAIN][entry.entry_id]['userinfo']

userinfo = hass.data[DOMAIN][entry.entry_id].get("userinfo", {})
if not userinfo:
_LOGGER.error("No userinfo found for PostNL entry")
return

_LOGGER.debug("Userinfo loaded: %s", userinfo)

async_add_entities([
PostNLDelivery(
Expand All @@ -38,7 +44,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
receiver=False
)
])

_LOGGER.debug("PostNL sensors added")

class PostNLDelivery(CoordinatorEntity, Entity):
def __init__(self, coordinator, postnl_userinfo, unique_id, name, receiver: bool = True):
Expand Down
9 changes: 6 additions & 3 deletions custom_components/postnl/structs/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ class Package:
key: str
name: str
url: str
shipment_type: str
status_message: str
delivered: bool
delivery_date: str | None
delivery_address_type: str | None
planned_date: str | None
planned_from: str | None
planned_to: str | None
Expand All @@ -15,9 +17,11 @@ def __init__(
key: str,
name: str,
url: str,
shipment_type: str,
status_message: str,
delivered: bool,
delivery_date: str | None = None,
delivery_address_type: str | None = None,
planned_date: str | None = None,
planned_from: str | None = None,
planned_to: str | None = None,
Expand All @@ -26,13 +30,12 @@ def __init__(
self.key = key
self.name = name
self.url = url
self.shipment_type = shipment_type
self.status_message = status_message
self.delivered = delivered
self.delivery_date = delivery_date
self.delivery_address_type = delivery_address_type
self.planned_date = planned_date
self.planned_from = planned_from
self.planned_to = planned_to
self.expected_datetime = expected_datetime



0 comments on commit a4470dd

Please sign in to comment.