Skip to content

Commit 0e9db78

Browse files
committed
Update monthly spent sensor.
1 parent d5900e7 commit 0e9db78

6 files changed

Lines changed: 76 additions & 4 deletions

File tree

custom_components/rohlikcz/const.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
ICON_CALENDAR_REMOVE = "mdi:calendar-remove"
3535
ICON_INFO = "mdi:information-outline"
3636
ICON_DELIVERY_TIME = "mdi:timer-sand"
37+
ICON_MONTHLY_SPENT = "mdi:cash-register"
3738

3839
""" Service attributes """
3940
ATTR_CONFIG_ENTRY_ID = "config_entry_id"

custom_components/rohlikcz/rohlik_api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,8 @@ async def get_data(self):
191191
"last_order": "/api/v3/orders/delivered?offset=0&limit=1",
192192
"premium_profile": "/services/frontend-service/premium/profile",
193193
"next_delivery_slot": "/services/frontend-service/timeslots-api/",
194-
"delivery_announcements": "/services/frontend-service/announcements/delivery"
194+
"delivery_announcements": "/services/frontend-service/announcements/delivery",
195+
"delivered_orders": "/api/v3/orders/delivered?offset=0&limit=50"
195196
}
196197

197198
result["login"] = await self.login(session)

custom_components/rohlikcz/sensor.py

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
from homeassistant.helpers.entity_platform import AddEntitiesCallback
1717
from .const import DOMAIN, ICON_UPDATE, ICON_CREDIT, ICON_NO_LIMIT, ICON_FREE_EXPRESS, ICON_DELIVERY, ICON_BAGS, \
1818
ICON_CART, ICON_ACCOUNT, ICON_EMAIL, ICON_PHONE, ICON_PREMIUM_DAYS, ICON_LAST_ORDER, ICON_NEXT_ORDER_SINCE, \
19-
ICON_NEXT_ORDER_TILL, ICON_INFO, ICON_DELIVERY_TIME
19+
ICON_NEXT_ORDER_TILL, ICON_INFO, ICON_DELIVERY_TIME, ICON_MONTHLY_SPENT
2020
from .entity import BaseEntity
2121
from .hub import RohlikAccount
22-
from .utils import extract_delivery_datetime
22+
from .utils import extract_delivery_datetime, calculate_current_month_orders_total
2323

2424
SCAN_INTERVAL = timedelta(seconds=600)
2525

@@ -48,7 +48,8 @@ async def async_setup_entry(
4848
NextOrderTill(rohlik_hub),
4949
NextOrderSince(rohlik_hub),
5050
DeliveryInfo(rohlik_hub),
51-
DeliveryTime(rohlik_hub)
51+
DeliveryTime(rohlik_hub),
52+
MonthlySpent(rohlik_hub)
5253
]
5354

5455
if rohlik_hub.has_address:
@@ -423,6 +424,29 @@ async def async_will_remove_from_hass(self) -> None:
423424
self._rohlik_account.remove_callback(self.async_write_ha_state)
424425

425426

427+
class MonthlySpent(BaseEntity, SensorEntity):
428+
"""Sensor for amount spent in current month."""
429+
430+
_attr_translation_key = "monthly_spent"
431+
_attr_should_poll = False
432+
433+
@property
434+
def native_value(self) -> float | None:
435+
"""Returns amount spend within last month."""
436+
_LOGGER.error(self._rohlik_account.data.get('delivered_orders', "[]"))
437+
return calculate_current_month_orders_total(self._rohlik_account.data.get('delivered_orders', []))
438+
439+
@property
440+
def icon(self) -> str:
441+
return ICON_MONTHLY_SPENT
442+
443+
async def async_added_to_hass(self) -> None:
444+
self._rohlik_account.register_callback(self.async_write_ha_state)
445+
446+
async def async_will_remove_from_hass(self) -> None:
447+
self._rohlik_account.remove_callback(self.async_write_ha_state)
448+
449+
426450
class NoLimitOrders(BaseEntity, SensorEntity):
427451
"""Sensor for remaining no limit orders."""
428452

custom_components/rohlikcz/translations/cs.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@
128128
},
129129
"delivery_time": {
130130
"name": "Čas doručení"
131+
},
132+
"monthly_spent": {
133+
"name": "Měsíční útrata",
134+
"unit_of_measurement": ""
131135
}
132136
},
133137
"todo": {

custom_components/rohlikcz/translations/en.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@
128128
},
129129
"delivery_time": {
130130
"name": "Delivery Time"
131+
},
132+
"monthly_spent": {
133+
"name": "Spent This Month",
134+
"unit_of_measurement": "CZK"
131135
}
132136
},
133137
"todo": {

custom_components/rohlikcz/utils.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,45 @@
11
from datetime import timedelta, datetime, time
2+
import json
23
from zoneinfo import ZoneInfo
34
import re
45

6+
7+
def calculate_current_month_orders_total(orders: list) -> float|None:
8+
"""
9+
Calculate the total amount of orders for the current month from JSON data.
10+
11+
Args:
12+
orders (list): List of order dictionaries, each containing an 'orderTime' and 'priceComposition'
13+
14+
Returns:
15+
float: Total amount of orders for the current month. Returns 0.0 if no orders
16+
are found for the current month or None if the JSON is invalid.
17+
18+
"""
19+
try:
20+
21+
# Get current month pattern (e.g., "2025-06-")
22+
current_month_pattern = datetime.now().strftime("%Y-%m-")
23+
24+
# Filter orders from current month and calculate sum
25+
total_amount = 0.0
26+
27+
for order in orders:
28+
try:
29+
# Simple string check for current month
30+
if current_month_pattern in order['orderTime']:
31+
amount = float(order['priceComposition']['total']['amount'])
32+
total_amount += amount
33+
except (KeyError, ValueError, TypeError):
34+
# Skip invalid orders
35+
continue
36+
37+
return total_amount
38+
39+
except (json.JSONDecodeError, TypeError):
40+
return None
41+
42+
543
def extract_delivery_datetime(text: str) -> datetime | None:
644
"""
745
Extract delivery time information from various formatted strings and return a datetime object.

0 commit comments

Comments
 (0)