Expose every order component as its own entity and prepare for release
Validate / hassfest (push) Failing after 23s
Validate / pytest (push) Successful in 9s
Validate / HACS (push) Failing after 1m21s

Each cost line is now an entity rather than an attribute: subtotal, box price,
add-ons, tax and delivery fee, plus a total and free-delivery-remaining for the
open order, a delivery-day sensor, and a binary sensor that turns off at the
cutoff. Entities share a base class and declare a scope, so a description
states only the field it reads.

Also parses the driver tip, Bounty savings and the free-delivery threshold. The
threshold is carried across orders because the progress bar only renders on
carts that have not met it.

Adds LICENSE, hacs.json, a CI workflow, a pre-publish audit script, and a test
that cross-checks every entity's translation_key against both translation
files. Manifest URLs now point at GitHub rather than a private forge.
This commit is contained in:
flan
2026-08-03 19:32:50 +00:00
parent 527f662189
commit 3e880ff2c1
18 changed files with 760 additions and 144 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ from homeassistant.helpers.aiohttp_client import async_create_clientsession
from .api import FreshHarvestClient
from .coordinator import FreshHarvestCoordinator
PLATFORMS: list[Platform] = [Platform.SENSOR]
PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR]
type FreshHarvestConfigEntry = ConfigEntry[FreshHarvestCoordinator]
+29
View File
@@ -96,7 +96,12 @@ class DeliveryOrder:
subtotal: float | None = None
tax: float | None = None
delivery_fee: float | None = None
driver_tip: float | None = None
total: float | None = None
# What a Bounty membership would knock off this order. Marketing, not a charge.
bounty_savings: float | None = None
# How much more this order needs to qualify for free delivery, 0.0 once it does.
free_delivery_remaining: float | None = None
# Non-empty only while the order can still be changed, e.g. "Shop tomorrow"
# or "Shop thru Sunday 8/9". Empty once the order is locked for packing.
shop_window: str | None = None
@@ -126,6 +131,9 @@ class AccountSnapshot:
next_delivery: date | None = None
delivery_day: str | None = None
# Account-wide spend needed for free delivery. Only rendered on carts that
# have not reached it, so it is read once and applied to every order.
free_delivery_threshold: float | None = None
orders: list[DeliveryOrder] = field(default_factory=list)
@property
@@ -262,9 +270,30 @@ def parse_dashboard(html: str) -> AccountSnapshot:
order.tax = amount
elif key.startswith("delivery"):
order.delivery_fee = amount
elif key.startswith("driver tip"):
# Reads "Add Tip" until one is set, which is not an amount.
order.driver_tip = amount
elif "bounty savings" in key:
order.bounty_savings = amount
progress = soup.select_one(f"#DeliveryProgressBar-{delivery_id} progress")
if progress is not None and snapshot.free_delivery_threshold is None:
try:
snapshot.free_delivery_threshold = float(progress.get("max"))
except (TypeError, ValueError):
_LOGGER.debug("unparsable free-delivery threshold on %s", delivery_id)
snapshot.orders.append(order)
# Applied after the loop: the threshold is only rendered on carts that have
# not met it, so an order that already qualifies would otherwise miss it.
if snapshot.free_delivery_threshold is not None:
for order in snapshot.orders:
if order.subtotal is not None:
order.free_delivery_remaining = round(
max(0.0, snapshot.free_delivery_threshold - order.subtotal), 2
)
if not snapshot.orders and snapshot.next_delivery is None:
raise FreshHarvestError("dashboard markup not recognised")
return snapshot
@@ -0,0 +1,62 @@
"""Binary sensors for Fresh Harvest."""
from __future__ import annotations
from homeassistant.components.binary_sensor import (
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import FreshHarvestConfigEntry
from .coordinator import FreshHarvestCoordinator
from .entity import FreshHarvestEntity
DESCRIPTION = BinarySensorEntityDescription(
key="order_open",
translation_key="order_open",
icon="mdi:cart-arrow-right",
)
async def async_setup_entry(
hass: HomeAssistant,
entry: FreshHarvestConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the binary sensor platform."""
async_add_entities([FreshHarvestOrderOpen(entry.runtime_data, entry)])
class FreshHarvestOrderOpen(FreshHarvestEntity, BinarySensorEntity):
"""Whether any upcoming order can still be changed.
The single most useful thing to automate on: it goes off when the cutoff
passes, which is the last moment to add something to the box.
"""
entity_description = DESCRIPTION
def __init__(
self, coordinator: FreshHarvestCoordinator, entry: FreshHarvestConfigEntry
) -> None:
super().__init__(coordinator, entry, DESCRIPTION.key)
@property
def is_on(self) -> bool:
"""Return true while an order is still customizable."""
return self.target("open_order") is not None
@property
def extra_state_attributes(self) -> dict[str, str | None] | None:
"""Surface which order is open and until when."""
order = self.target("open_order")
if order is None:
return None
return {
"delivery_date": order.delivery_date.isoformat()
if order.delivery_date
else None,
"shop_window": order.shop_window,
}
+56
View File
@@ -0,0 +1,56 @@
"""Shared entity plumbing for Fresh Harvest.
Entities read one of three things: the account as a whole, the order arriving
next, or the order that can still be changed. Declaring that as a `scope` keeps
each entity's `value_fn` down to the field it actually cares about, instead of
every one of them repeating the same None checks.
"""
from __future__ import annotations
from typing import Literal
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .api import AccountSnapshot, DeliveryOrder
from .const import DOMAIN
from .coordinator import FreshHarvestCoordinator
Scope = Literal["account", "next_order", "open_order"]
def resolve_scope(
snapshot: AccountSnapshot, scope: Scope
) -> AccountSnapshot | DeliveryOrder | None:
"""Return the object a scope points at, or None when there is no such order."""
if scope == "account":
return snapshot
return getattr(snapshot, scope)
class FreshHarvestEntity(CoordinatorEntity[FreshHarvestCoordinator]):
"""Base for every Fresh Harvest entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: FreshHarvestCoordinator,
entry: ConfigEntry,
key: str,
) -> None:
super().__init__(coordinator)
self._attr_unique_id = f"{entry.entry_id}_{key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, entry.entry_id)},
name="Fresh Harvest",
manufacturer="Fresh Harvest",
entry_type=DeviceEntryType.SERVICE,
configuration_url="https://freshharvest.com/p/dashboard/details",
)
def target(self, scope: Scope) -> AccountSnapshot | DeliveryOrder | None:
"""Resolve this entity's scope against the latest snapshot."""
return resolve_scope(self.coordinator.data, scope)
+5 -9
View File
@@ -1,16 +1,12 @@
{
"domain": "freshharvest",
"name": "Fresh Harvest",
"codeowners": [
"@flan"
],
"codeowners": ["@sudolulo"],
"config_flow": true,
"documentation": "https://git.onetick.ninja/flan/ha-freshharvest",
"documentation": "https://github.com/sudolulo/ha-freshharvest",
"integration_type": "service",
"iot_class": "cloud_polling",
"issue_tracker": "https://git.onetick.ninja/flan/ha-freshharvest/issues",
"requirements": [
"beautifulsoup4>=4.12"
],
"version": "0.2.0"
"issue_tracker": "https://github.com/sudolulo/ha-freshharvest/issues",
"requirements": ["beautifulsoup4>=4.12"],
"version": "0.3.0"
}
+114 -67
View File
@@ -1,4 +1,9 @@
"""Sensors for Fresh Harvest."""
"""Sensors for Fresh Harvest.
Every part of an order is its own entity — box price, add-ons, tax, delivery
fee, subtotal and total — so an automation or dashboard can read any one of
them directly rather than digging through attributes.
"""
from __future__ import annotations
@@ -13,17 +18,17 @@ from homeassistant.components.sensor import (
SensorStateClass,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import FreshHarvestConfigEntry
from .api import AccountSnapshot, DeliveryOrder, OrderItem
from .const import DOMAIN
from .api import DeliveryOrder, OrderItem
from .coordinator import FreshHarvestCoordinator
from .entity import FreshHarvestEntity, Scope
CURRENCY = "USD"
def _format_item(item: OrderItem, with_price: bool = False) -> str:
def format_item(item: OrderItem, with_price: bool = False) -> str:
"""Render one line, e.g. '4 Complete Recovery Smoothie 15.2 fl oz — $17.96'."""
line = " ".join(
part for part in (str(item.quantity or ""), item.name, item.unit) if part
@@ -33,15 +38,21 @@ def _format_item(item: OrderItem, with_price: bool = False) -> str:
return line
def _items_attrs(order: DeliveryOrder | None) -> dict[str, Any] | None:
if order is None:
return None
def _contents_attrs(order: DeliveryOrder) -> dict[str, Any]:
return {
"box": order.box_name,
"box_price": order.box_price,
"produce": [_format_item(i) for i in order.items],
"add_ons": [_format_item(a, with_price=True) for a in order.addons],
"add_ons_total": order.addons_total,
"produce": [format_item(i) for i in order.items],
"add_ons": [format_item(a, with_price=True) for a in order.addons],
"produce_count": len(order.items),
"add_ons_count": len(order.addons),
}
def _total_attrs(order: DeliveryOrder) -> dict[str, Any]:
"""Charges that are not worth their own entity: optional or promotional."""
return {
"driver_tip": order.driver_tip,
"bounty_savings": order.bounty_savings,
}
@@ -49,77 +60,116 @@ def _items_attrs(order: DeliveryOrder | None) -> dict[str, Any] | None:
class FreshHarvestSensorDescription(SensorEntityDescription):
"""Describes a Fresh Harvest sensor."""
value_fn: Callable[[AccountSnapshot], Any]
attrs_fn: Callable[[AccountSnapshot], dict[str, Any] | None] | None = None
scope: Scope = "next_order"
value_fn: Callable[[Any], Any]
attrs_fn: Callable[[Any], dict[str, Any]] | None = None
def _money(**kwargs) -> FreshHarvestSensorDescription:
"""A dollar amount. A helper because there are eight of them.
Callers pass `translation_key` explicitly rather than deriving it from
`key`, so the name of every entity stays greppable in this file — which is
what `tests/test_translations.py` checks.
"""
return FreshHarvestSensorDescription(
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.TOTAL,
native_unit_of_measurement=CURRENCY,
**kwargs,
)
SENSORS: tuple[FreshHarvestSensorDescription, ...] = (
# --- the account itself -------------------------------------------------
FreshHarvestSensorDescription(
key="next_delivery",
translation_key="next_delivery",
scope="account",
device_class=SensorDeviceClass.DATE,
value_fn=lambda s: s.next_delivery,
attrs_fn=lambda s: {
"delivery_day": s.delivery_day,
"box": s.next_order.box_name if s.next_order else None,
"free_delivery_threshold": s.free_delivery_threshold,
},
),
FreshHarvestSensorDescription(
key="delivery_day",
translation_key="delivery_day",
scope="account",
icon="mdi:calendar-week",
value_fn=lambda s: s.delivery_day,
),
# --- the order arriving next --------------------------------------------
_money(
key="next_delivery_total",
translation_key="next_delivery_total",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.TOTAL,
native_unit_of_measurement="USD",
value_fn=lambda s: s.next_order.total if s.next_order else None,
attrs_fn=lambda s: None
if s.next_order is None
else {
"subtotal": s.next_order.subtotal,
"tax": s.next_order.tax,
"delivery_fee": s.next_order.delivery_fee,
},
value_fn=lambda o: o.total,
attrs_fn=_total_attrs,
),
FreshHarvestSensorDescription(
key="next_delivery_addons_total",
translation_key="next_delivery_addons_total",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.TOTAL,
native_unit_of_measurement="USD",
value_fn=lambda s: s.next_order.addons_total if s.next_order else None,
attrs_fn=lambda s: None
if s.next_order is None
else {
"box_price": s.next_order.box_price,
"add_ons": [
_format_item(a, with_price=True) for a in s.next_order.addons
],
},
_money(
key="next_delivery_subtotal",
translation_key="next_delivery_subtotal",
value_fn=lambda o: o.subtotal,
),
_money(
key="next_delivery_box_price",
translation_key="next_delivery_box_price",
value_fn=lambda o: o.box_price,
),
_money(
key="next_delivery_add_ons",
translation_key="next_delivery_add_ons",
value_fn=lambda o: o.addons_total,
),
_money(
key="next_delivery_tax",
translation_key="next_delivery_tax",
value_fn=lambda o: o.tax,
),
_money(
key="next_delivery_delivery_fee",
translation_key="next_delivery_delivery_fee",
value_fn=lambda o: o.delivery_fee,
),
FreshHarvestSensorDescription(
key="next_delivery_items",
translation_key="next_delivery_items",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement="items",
value_fn=lambda s: len(s.next_order.all_items) if s.next_order else None,
attrs_fn=lambda s: _items_attrs(s.next_order),
icon="mdi:basket-check",
value_fn=lambda o: len(o.all_items),
attrs_fn=_contents_attrs,
),
# --- the order that can still be changed --------------------------------
FreshHarvestSensorDescription(
key="open_order_delivery",
translation_key="open_order_delivery",
scope="open_order",
device_class=SensorDeviceClass.DATE,
value_fn=lambda s: s.open_order.delivery_date if s.open_order else None,
attrs_fn=lambda s: None
if s.open_order is None
else {
"total": s.open_order.total,
"box": s.open_order.box_name,
},
value_fn=lambda o: o.delivery_date,
attrs_fn=lambda o: {"box": o.box_name},
),
_money(
key="open_order_total",
translation_key="open_order_total",
scope="open_order",
value_fn=lambda o: o.total,
attrs_fn=_total_attrs,
),
_money(
key="open_order_free_delivery_remaining",
translation_key="open_order_free_delivery_remaining",
scope="open_order",
value_fn=lambda o: o.free_delivery_remaining,
),
FreshHarvestSensorDescription(
key="shop_window",
translation_key="shop_window",
value_fn=lambda s: (s.open_order.shop_window if s.open_order else None)
or "closed",
scope="open_order",
icon="mdi:clock-alert-outline",
# Distinct from unknown: there genuinely is no changeable order.
value_fn=lambda o: o.shop_window or "closed",
),
)
@@ -136,10 +186,9 @@ async def async_setup_entry(
)
class FreshHarvestSensor(CoordinatorEntity[FreshHarvestCoordinator], SensorEntity):
class FreshHarvestSensor(FreshHarvestEntity, SensorEntity):
"""A value read off the Fresh Harvest dashboard."""
_attr_has_entity_name = True
entity_description: FreshHarvestSensorDescription
def __init__(
@@ -148,25 +197,23 @@ class FreshHarvestSensor(CoordinatorEntity[FreshHarvestCoordinator], SensorEntit
entry: FreshHarvestConfigEntry,
description: FreshHarvestSensorDescription,
) -> None:
super().__init__(coordinator)
super().__init__(coordinator, entry, description.key)
self.entity_description = description
self._attr_unique_id = f"{entry.entry_id}_{description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, entry.entry_id)},
name="Fresh Harvest",
manufacturer="Fresh Harvest",
entry_type=DeviceEntryType.SERVICE,
configuration_url="https://freshharvest.com/p/dashboard/details",
)
@property
def native_value(self) -> Any:
"""Return the sensor value."""
return self.entity_description.value_fn(self.coordinator.data)
"""Return the sensor value, or None when its order does not exist."""
target = self.target(self.entity_description.scope)
if target is None:
return None
return self.entity_description.value_fn(target)
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the sensor's extra attributes."""
if self.entity_description.attrs_fn is None:
return None
return self.entity_description.attrs_fn(self.coordinator.data)
target = self.target(self.entity_description.scope)
if target is None:
return None
return self.entity_description.attrs_fn(target)
+27 -1
View File
@@ -22,21 +22,47 @@
"next_delivery": {
"name": "Next delivery"
},
"delivery_day": {
"name": "Delivery day"
},
"next_delivery_total": {
"name": "Next delivery total"
},
"next_delivery_addons_total": {
"next_delivery_subtotal": {
"name": "Next delivery subtotal"
},
"next_delivery_box_price": {
"name": "Next delivery box price"
},
"next_delivery_add_ons": {
"name": "Next delivery add-ons"
},
"next_delivery_tax": {
"name": "Next delivery tax"
},
"next_delivery_delivery_fee": {
"name": "Next delivery fee"
},
"next_delivery_items": {
"name": "Next delivery items"
},
"open_order_delivery": {
"name": "Open order delivery"
},
"open_order_total": {
"name": "Open order total"
},
"open_order_free_delivery_remaining": {
"name": "Open order free delivery remaining"
},
"shop_window": {
"name": "Shopping window"
}
},
"binary_sensor": {
"order_open": {
"name": "Order open"
}
}
}
}
@@ -22,21 +22,47 @@
"next_delivery": {
"name": "Next delivery"
},
"delivery_day": {
"name": "Delivery day"
},
"next_delivery_total": {
"name": "Next delivery total"
},
"next_delivery_addons_total": {
"next_delivery_subtotal": {
"name": "Next delivery subtotal"
},
"next_delivery_box_price": {
"name": "Next delivery box price"
},
"next_delivery_add_ons": {
"name": "Next delivery add-ons"
},
"next_delivery_tax": {
"name": "Next delivery tax"
},
"next_delivery_delivery_fee": {
"name": "Next delivery fee"
},
"next_delivery_items": {
"name": "Next delivery items"
},
"open_order_delivery": {
"name": "Open order delivery"
},
"open_order_total": {
"name": "Open order total"
},
"open_order_free_delivery_remaining": {
"name": "Open order free delivery remaining"
},
"shop_window": {
"name": "Shopping window"
}
},
"binary_sensor": {
"order_open": {
"name": "Order open"
}
}
}
}