1 """Services for the Picnic integration."""
3 from __future__
import annotations
5 from typing
import cast
7 from python_picnic_api
import PicnicAPI
8 import voluptuous
as vol
17 ATTR_PRODUCT_IDENTIFIERS,
21 SERVICE_ADD_PRODUCT_TO_CART,
26 """Exception for Picnic services."""
30 """Register services for the Picnic integration, if not registered yet."""
32 if hass.services.has_service(DOMAIN, SERVICE_ADD_PRODUCT_TO_CART):
35 async
def async_add_product_service(call: ServiceCall):
36 api_client = await
get_api_client(hass, call.data[ATTR_CONFIG_ENTRY_ID])
39 hass.services.async_register(
41 SERVICE_ADD_PRODUCT_TO_CART,
42 async_add_product_service,
45 vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
46 vol.Exclusive(ATTR_PRODUCT_ID, ATTR_PRODUCT_IDENTIFIERS): cv.string,
47 vol.Exclusive(ATTR_PRODUCT_NAME, ATTR_PRODUCT_IDENTIFIERS): cv.string,
48 vol.Optional(ATTR_AMOUNT): vol.All(vol.Coerce(int), vol.Range(min=1)),
54 async
def get_api_client(hass: HomeAssistant, config_entry_id: str) -> PicnicAPI:
55 """Get the right Picnic API client based on the device id, else get the default one."""
56 if config_entry_id
not in hass.data[DOMAIN]:
57 raise ValueError(f
"Config entry with id {config_entry_id} not found!")
58 return hass.data[DOMAIN][config_entry_id][CONF_API]
62 hass: HomeAssistant, api_client: PicnicAPI, call: ServiceCall
64 """Handle the call for the add_product service."""
65 product_id = call.data.get(ATTR_PRODUCT_ID)
67 product_id = await hass.async_add_executor_job(
68 product_search, api_client, cast(str, call.data[ATTR_PRODUCT_NAME])
74 await hass.async_add_executor_job(
75 api_client.add_product, product_id, call.data.get(ATTR_AMOUNT, 1)
79 def product_search(api_client: PicnicAPI, product_name: str |
None) -> str |
None:
80 """Query the api client for the product name."""
81 if product_name
is None:
84 search_result = api_client.search(product_name)
86 if not search_result
or "items" not in search_result[0]:
90 for item
in search_result[0][
"items"]:
92 return str(item[
"id"])
PicnicAPI get_api_client(HomeAssistant hass, str config_entry_id)
None async_register_services(HomeAssistant hass)
str|None product_search(PicnicAPI api_client, str|None product_name)
None handle_add_product(HomeAssistant hass, PicnicAPI api_client, ServiceCall call)