Skip to content

Commit

Permalink
Merge pull request #30 from wxt9861/feat/import
Browse files Browse the repository at this point in the history
Call transaction import on sensor update
  • Loading branch information
wxt9861 authored Aug 24, 2023
2 parents 5327501 + e3ec451 commit 0f7e404
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.10
FROM python:3.11

RUN apt-get update \
&& apt-get install -y --no-install-recommends \
Expand Down
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"python.pythonPath": "/usr/local/bin/python3"
"python.pythonPath": "/usr/local/bin/python3",
"files.associations": {
"*.yaml": "home-assistant"
}
}
52 changes: 45 additions & 7 deletions custom_components/ynab/__init__.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
"""YNAB Integration."""

import json
import logging
import os
from datetime import timedelta, date
from ynab_sdk import YNAB
from datetime import date, timedelta

import aiohttp
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import CONF_API_KEY
from homeassistant.helpers import discovery
from homeassistant.util import Throttle

import voluptuous as vol
from ynab_sdk import YNAB

from .const import (
CONF_NAME,
DEFAULT_NAME,
DEFAULT_API_ENDPOINT,
DEFAULT_BUDGET,
DEFAULT_CURRENCY,
DEFAULT_NAME,
DOMAIN,
DOMAIN_DATA,
ISSUE_URL,
Expand Down Expand Up @@ -115,6 +117,8 @@ async def update_data(self):
"""Update data."""

# setup YNAB API
await self.request_import()

self.ynab = YNAB(self.api_key)
self.all_budgets = await self.hass.async_add_executor_job(
self.ynab.budgets.get_budgets
Expand Down Expand Up @@ -251,6 +255,41 @@ async def update_data(self):
[category.name, category.balance / 1000, category.budgeted / 1000],
)

async def request_import(self):
"""Force transaction import."""

import_endpoint = (
f"{DEFAULT_API_ENDPOINT}/budgets/{self.budget}/transactions/import"
)
headers = {
"accept": "application/json",
"Authorization": f"Bearer {self.api_key}",
}

try:
async with aiohttp.ClientSession(headers=headers) as session:
async with session.post(url=import_endpoint) as response:
if response.status in [200, 201]:
response_data = json.loads(await response.text())

_LOGGER.debug(
"Imported transactions: %s",
len(response_data["data"]["transaction_ids"]),
)
_LOGGER.debug("API Stats: %s", response.headers["X-Rate-Limit"])

if len(response_data["data"]["transaction_ids"]) > 0:
_event_topic = DOMAIN + "_event"
_event_data = {
"transactions_imported": len(
response_data["data"]["transaction_ids"]
)
}
self.hass.bus.async_fire(_event_topic, _event_data)

except Exception as error: # pylint: disable=broad-except
_LOGGER.debug("Error encounted during forced import - %s", error)


async def check_files(hass):
"""Return bool that indicates if all files are present."""
Expand All @@ -272,9 +311,8 @@ async def check_files(hass):

async def check_url():
"""Return bool that indicates YNAB URL is accessible."""
import aiohttp # pylint: disable=import-outside-toplevel

url = "https://api.youneedabudget.com/v1"
url = DEFAULT_API_ENDPOINT

try:
async with aiohttp.ClientSession() as session:
Expand Down
3 changes: 2 additions & 1 deletion custom_components/ynab/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

PLATFORMS = ["sensor"]
REQUIRED_FILES = ["const.py", "manifest.json", "sensor.py"]
VERSION = "0.2.0"
VERSION = "0.3.0"
ISSUE_URL = "https://github.com/wxt9861/ynab/issues"

STARTUP = """
Expand All @@ -25,6 +25,7 @@
DEFAULT_NAME = "ynab"
DEFAULT_BUDGET = "last-used"
DEFAULT_CURRENCY = "$"
DEFAULT_API_ENDPOINT = "https://api.ynab.com/v1"

ICON = "mdi:finance"

Expand Down
4 changes: 2 additions & 2 deletions custom_components/ynab/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
"dependencies": [],
"codeowners": ["@wxt9861"],
"iot_class": "cloud_polling",
"requirements": ["ynab-sdk==0.4.0"],
"version": "0.2.0"
"requirements": ["ynab-sdk==0.5.0"],
"version": "0.3.0"
}
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ynab-sdk==0.5.0

0 comments on commit 0f7e404

Please sign in to comment.