manager-for-ynab 1.0.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- manager_for_ynab/__init__.py +3 -0
- manager_for_ynab/__main__.py +4 -0
- manager_for_ynab/_auth.py +17 -0
- manager_for_ynab/_main.py +71 -0
- manager_for_ynab/_version.py +13 -0
- manager_for_ynab/pending_income/__init__.py +141 -0
- manager_for_ynab/pending_income/pending_income.sql +24 -0
- manager_for_ynab/py.typed +0 -0
- manager_for_ynab/reconciler/__init__.py +433 -0
- manager_for_ynab/zero_out/__init__.py +213 -0
- manager_for_ynab-1.0.0.dist-info/METADATA +58 -0
- manager_for_ynab-1.0.0.dist-info/RECORD +20 -0
- manager_for_ynab-1.0.0.dist-info/WHEEL +6 -0
- manager_for_ynab-1.0.0.dist-info/entry_points.txt +2 -0
- manager_for_ynab-1.0.0.dist-info/licenses/LICENSE +21 -0
- manager_for_ynab-1.0.0.dist-info/top_level.txt +3 -0
- testing/__init__.py +0 -0
- testing/fixtures.py +31 -0
- testing/seed.sql +289 -0
- tests/__init__.py +0 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
_ENV_TOKEN = "YNAB_PERSONAL_ACCESS_TOKEN"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def resolve_token(token_override: str | None = None) -> str:
|
|
8
|
+
token = token_override or os.environ.get(_ENV_TOKEN)
|
|
9
|
+
if token:
|
|
10
|
+
return token
|
|
11
|
+
|
|
12
|
+
raise ValueError(
|
|
13
|
+
f"Must set YNAB access token as {_ENV_TOKEN!r} environment variable or pass token_override directly. See https://api.ynab.com/#personal-access-tokens"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
__all__ = [resolve_token.__name__, _ENV_TOKEN]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
import manager_for_ynab.pending_income as pending_income
|
|
6
|
+
import manager_for_ynab.reconciler as reconciler
|
|
7
|
+
import manager_for_ynab.zero_out as zero_out
|
|
8
|
+
from manager_for_ynab._version import get_version
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_RECONCILER_HELP = "Find and automatically reconciles unreconciled transactions."
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
18
|
+
parser = argparse.ArgumentParser(prog="manager-for-ynab")
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"--version", action="version", version=f"%(prog)s {get_version()}"
|
|
21
|
+
)
|
|
22
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
23
|
+
|
|
24
|
+
reconciler_parser = subparsers.add_parser(
|
|
25
|
+
"reconciler",
|
|
26
|
+
help=_RECONCILER_HELP,
|
|
27
|
+
description=_RECONCILER_HELP,
|
|
28
|
+
)
|
|
29
|
+
reconciler_parser.set_defaults(func=_run_reconciler)
|
|
30
|
+
|
|
31
|
+
pending_income_parser = subparsers.add_parser(
|
|
32
|
+
"pending-income", help="Move pending income transactions to today."
|
|
33
|
+
)
|
|
34
|
+
pending_income_parser.set_defaults(func=_run_pending_income)
|
|
35
|
+
|
|
36
|
+
zero_out_parser = subparsers.add_parser(
|
|
37
|
+
"zero-out",
|
|
38
|
+
help="Set a category's budgeted amount to zero across a month range.",
|
|
39
|
+
)
|
|
40
|
+
zero_out_parser.set_defaults(func=_run_zero_out)
|
|
41
|
+
return parser
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _run_reconciler(argv: Sequence[str]) -> int:
|
|
45
|
+
return reconciler.run(argv)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _run_pending_income(argv: Sequence[str]) -> int:
|
|
49
|
+
return pending_income.run(argv)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _run_zero_out(argv: Sequence[str]) -> int:
|
|
53
|
+
return zero_out.run(argv)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv: Sequence[str] = ()) -> int:
|
|
57
|
+
argv = argv or sys.argv[1:]
|
|
58
|
+
if not argv:
|
|
59
|
+
build_parser().print_help()
|
|
60
|
+
return 0
|
|
61
|
+
match argv[0]:
|
|
62
|
+
case "reconciler":
|
|
63
|
+
return _run_reconciler(argv[1:])
|
|
64
|
+
case "pending-income":
|
|
65
|
+
return _run_pending_income(argv[1:])
|
|
66
|
+
case "zero-out":
|
|
67
|
+
return _run_zero_out(argv[1:])
|
|
68
|
+
|
|
69
|
+
parser = build_parser()
|
|
70
|
+
parser.parse_args(argv)
|
|
71
|
+
raise AssertionError("subcommand parser should have exited")
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from configparser import ConfigParser
|
|
2
|
+
from importlib.metadata import PackageNotFoundError
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_version(distribution: str = "manager_for_ynab") -> str:
|
|
8
|
+
try:
|
|
9
|
+
return version(distribution)
|
|
10
|
+
except PackageNotFoundError:
|
|
11
|
+
config = ConfigParser()
|
|
12
|
+
config.read(Path(__file__).resolve().parent.parent / "setup.cfg")
|
|
13
|
+
return config["metadata"]["version"]
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import sqlite3
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import date
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Never
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
import rich
|
|
13
|
+
import ynab
|
|
14
|
+
from rich.table import Table
|
|
15
|
+
from sqlite_export_for_ynab import default_db_path
|
|
16
|
+
from sqlite_export_for_ynab import sync
|
|
17
|
+
from tldm import tldm
|
|
18
|
+
|
|
19
|
+
from manager_for_ynab._auth import resolve_token
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from collections.abc import Sequence
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_PACKAGE = "manager-for-ynab pending-income"
|
|
26
|
+
_PENDING_INCOME_SQL = (
|
|
27
|
+
files("manager_for_ynab.pending_income").joinpath("pending_income.sql").read_text()
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Transaction:
|
|
33
|
+
id: str
|
|
34
|
+
plan_id: str
|
|
35
|
+
account_name: str
|
|
36
|
+
payee_name: str
|
|
37
|
+
amount_formatted: str
|
|
38
|
+
date: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
42
|
+
parser = argparse.ArgumentParser(prog=_PACKAGE)
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"--sqlite-export-for-ynab-db", type=Path, default=default_db_path()
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument("--sqlite-export-for-ynab-full-refresh", action="store_true")
|
|
47
|
+
parser.add_argument("--for-real", action="store_true")
|
|
48
|
+
return parser
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run(argv: Sequence[str] | None = None, *, token_override: str | None = None) -> int:
|
|
52
|
+
args = build_parser().parse_args(argv)
|
|
53
|
+
db: Path = args.sqlite_export_for_ynab_db
|
|
54
|
+
full_refresh: bool = args.sqlite_export_for_ynab_full_refresh
|
|
55
|
+
for_real: bool = args.for_real
|
|
56
|
+
|
|
57
|
+
token = resolve_token(token_override)
|
|
58
|
+
|
|
59
|
+
print("** Refreshing SQLite DB **")
|
|
60
|
+
asyncio.run(sync(token, db, full_refresh))
|
|
61
|
+
print("** Done **")
|
|
62
|
+
|
|
63
|
+
with sqlite3.connect(db) as con:
|
|
64
|
+
con.row_factory = sqlite3.Row
|
|
65
|
+
txns_by_plan = fetch_pending_income(con.cursor())
|
|
66
|
+
|
|
67
|
+
total_txns = sum(len(txns) for txns in txns_by_plan.values())
|
|
68
|
+
print(f"Found {total_txns} income transaction(s) to update.")
|
|
69
|
+
if total_txns == 0:
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
print_found_txns([txn for txns in txns_by_plan.values() for txn in txns])
|
|
73
|
+
|
|
74
|
+
grouped = build_updates(txns_by_plan, date.today())
|
|
75
|
+
|
|
76
|
+
if not for_real:
|
|
77
|
+
print("Use --for-real to actually update transactions.")
|
|
78
|
+
return 0
|
|
79
|
+
|
|
80
|
+
api_client = ynab.TransactionsApi(
|
|
81
|
+
ynab.ApiClient(ynab.Configuration(access_token=token))
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
with tldm[Never](
|
|
85
|
+
total=total_txns, desc=f"Updating {total_txns} transaction(s)"
|
|
86
|
+
) as progress:
|
|
87
|
+
for plan_id, txns in grouped.items():
|
|
88
|
+
api_client.update_transactions(
|
|
89
|
+
plan_id, ynab.PatchTransactionsWrapper(transactions=txns)
|
|
90
|
+
)
|
|
91
|
+
progress.update(len(txns))
|
|
92
|
+
|
|
93
|
+
return 0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def build_updates(
|
|
97
|
+
txns_by_plan: dict[str, list[Transaction]], today: date
|
|
98
|
+
) -> dict[str, list[ynab.SaveTransactionWithIdOrImportId]]:
|
|
99
|
+
grouped: dict[str, list[ynab.SaveTransactionWithIdOrImportId]] = defaultdict(list)
|
|
100
|
+
for plan_id, txns in txns_by_plan.items():
|
|
101
|
+
grouped[plan_id].extend(
|
|
102
|
+
ynab.SaveTransactionWithIdOrImportId(id=txn.id, date=today) for txn in txns
|
|
103
|
+
)
|
|
104
|
+
return grouped
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def fetch_pending_income(cur: sqlite3.Cursor) -> dict[str, list[Transaction]]:
|
|
108
|
+
txns = cur.execute(_PENDING_INCOME_SQL).fetchall()
|
|
109
|
+
|
|
110
|
+
txns_by_plan: dict[str, list[Transaction]] = defaultdict(list)
|
|
111
|
+
for txn in txns:
|
|
112
|
+
txns_by_plan[txn["plan_id"]].append(
|
|
113
|
+
Transaction(
|
|
114
|
+
id=txn["id"],
|
|
115
|
+
plan_id=txn["plan_id"],
|
|
116
|
+
account_name=txn["account_name"],
|
|
117
|
+
payee_name=txn["payee_name"],
|
|
118
|
+
amount_formatted=txn["amount_formatted"],
|
|
119
|
+
date=txn["date"],
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
return txns_by_plan
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def print_found_txns(found_txns: list[Transaction]) -> None:
|
|
127
|
+
table = Table(title="Pending Income Transactions")
|
|
128
|
+
table.add_column("Date")
|
|
129
|
+
table.add_column("Account")
|
|
130
|
+
table.add_column("Payee")
|
|
131
|
+
table.add_column("Amount", justify="right")
|
|
132
|
+
|
|
133
|
+
for txn in found_txns:
|
|
134
|
+
table.add_row(
|
|
135
|
+
txn.date, txn.account_name, txn.payee_name or "", txn.amount_formatted
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
rich.print(table)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
__all__ = [run.__name__]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
SELECT
|
|
2
|
+
transactions.id
|
|
3
|
+
, transactions.plan_id
|
|
4
|
+
, transactions.account_name
|
|
5
|
+
, transactions.payee_name
|
|
6
|
+
, transactions.amount_formatted
|
|
7
|
+
, transactions."date"
|
|
8
|
+
FROM transactions
|
|
9
|
+
WHERE
|
|
10
|
+
TRUE
|
|
11
|
+
AND transactions.cleared = 'uncleared'
|
|
12
|
+
AND transactions."date" < DATE('now', 'localtime')
|
|
13
|
+
AND transactions.amount > 0
|
|
14
|
+
AND NOT transactions.deleted
|
|
15
|
+
AND SUBSTR(transactions."date", 6, 2) = SUBSTR(DATE(), 6, 2)
|
|
16
|
+
AND transactions.id NOT IN (
|
|
17
|
+
SELECT subtransactions.transfer_transaction_id
|
|
18
|
+
FROM subtransactions
|
|
19
|
+
WHERE
|
|
20
|
+
subtransactions.transfer_transaction_id IS NOT NULL
|
|
21
|
+
AND NOT subtransactions.deleted
|
|
22
|
+
)
|
|
23
|
+
ORDER BY transactions."date", transactions.account_name, transactions.payee_name
|
|
24
|
+
;
|
|
File without changes
|
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import itertools
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sqlite3
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from dataclasses import field
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Never
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
import aiohttp
|
|
15
|
+
from babel.numbers import format_currency
|
|
16
|
+
from sqlite_export_for_ynab import default_db_path
|
|
17
|
+
from sqlite_export_for_ynab import sync
|
|
18
|
+
from tldm import tldm
|
|
19
|
+
|
|
20
|
+
from manager_for_ynab._auth import resolve_token
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
from collections.abc import Iterable
|
|
25
|
+
from collections.abc import Sequence
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_PACKAGE = "manager-for-ynab reconciler"
|
|
29
|
+
|
|
30
|
+
_NEG_BAL_ACCT_TYPES = frozenset(("checking", "savings", "cash"))
|
|
31
|
+
|
|
32
|
+
_LOCALE_EN_US = "en_US"
|
|
33
|
+
_DESCRIPTION = "Find and automatically reconciles unreconciled transactions."
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Transaction:
|
|
38
|
+
plan_id: str
|
|
39
|
+
id: str
|
|
40
|
+
amount: Decimal
|
|
41
|
+
amount_formatted: str
|
|
42
|
+
payee: str
|
|
43
|
+
cleared: str
|
|
44
|
+
|
|
45
|
+
def pretty(self) -> str:
|
|
46
|
+
return f"{self.amount_formatted:>10} - {self.payee}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class PlanAccount:
|
|
51
|
+
plan_id: str
|
|
52
|
+
account_name: str
|
|
53
|
+
account_id: str
|
|
54
|
+
account_type: str
|
|
55
|
+
cleared_balance: Decimal
|
|
56
|
+
currency: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
60
|
+
parser = argparse.ArgumentParser(prog=_PACKAGE, description=_DESCRIPTION)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--mode",
|
|
63
|
+
choices=("single", "batch"),
|
|
64
|
+
default="single",
|
|
65
|
+
help="Reconciliation mode. `single` uses --account-like/--target. `batch` uses --account-target-pairs.",
|
|
66
|
+
)
|
|
67
|
+
parser.add_argument(
|
|
68
|
+
"--account-like",
|
|
69
|
+
help="SQL LIKE pattern to match account name (must match exactly one account)",
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--target",
|
|
73
|
+
type=lambda s: Decimal(re.sub("[,$]", "", s)),
|
|
74
|
+
help="Target balance to match towards for reconciliation",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--account-target-pairs",
|
|
78
|
+
nargs="+",
|
|
79
|
+
help="Batch mode only. Account pattern/target pairs in `ACCOUNT_LIKE=TARGET` format (example: `Checking%%=500.30`).",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument(
|
|
82
|
+
"--for-real",
|
|
83
|
+
action="store_true",
|
|
84
|
+
help="Whether to actually perform the reconciliation. If unset, this tool only prints the transactions that would be reconciled.",
|
|
85
|
+
)
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
"--sqlite-export-for-ynab-db",
|
|
88
|
+
type=Path,
|
|
89
|
+
default=default_db_path(),
|
|
90
|
+
help="Path to sqlite-export-for-ynab SQLite DB file (respects sqlite-export-for-ynab configuration; if unset, will be %(default)s)",
|
|
91
|
+
)
|
|
92
|
+
parser.add_argument(
|
|
93
|
+
"--sqlite-export-for-ynab-full-refresh",
|
|
94
|
+
action="store_true",
|
|
95
|
+
help="Whether to **DROP ALL TABLES** and fetch all plan data again. If unset, this tool only does an incremental refresh",
|
|
96
|
+
)
|
|
97
|
+
return parser
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
async def async_run(
|
|
101
|
+
argv: Sequence[str] | None = None, *, token_override: str | None = None
|
|
102
|
+
) -> int:
|
|
103
|
+
args = build_parser().parse_args(argv)
|
|
104
|
+
mode: str = args.mode
|
|
105
|
+
account_like: str | None = args.account_like
|
|
106
|
+
raw_target: Decimal | None = args.target
|
|
107
|
+
account_target_pairs: list[str] | None = args.account_target_pairs
|
|
108
|
+
for_real: bool = args.for_real
|
|
109
|
+
db: Path = args.sqlite_export_for_ynab_db
|
|
110
|
+
full_refresh: bool = args.sqlite_export_for_ynab_full_refresh
|
|
111
|
+
|
|
112
|
+
if mode == "single":
|
|
113
|
+
if account_target_pairs:
|
|
114
|
+
raise ValueError(
|
|
115
|
+
"`--account-target-pairs` is only valid when `--mode batch` is selected."
|
|
116
|
+
)
|
|
117
|
+
if account_like is None or raw_target is None:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
"`--mode single` requires both `--account-like` and `--target`."
|
|
120
|
+
)
|
|
121
|
+
account_likes = [_normalize_account_like(account_like)]
|
|
122
|
+
raw_targets = [raw_target]
|
|
123
|
+
else:
|
|
124
|
+
assert mode == "batch"
|
|
125
|
+
if account_like is not None or raw_target is not None:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
"`--mode batch` cannot be used with `--account-like` or `--target`; use `--account-target-pairs` instead."
|
|
128
|
+
)
|
|
129
|
+
if not account_target_pairs:
|
|
130
|
+
raise ValueError("`--mode batch` requires `--account-target-pairs`.")
|
|
131
|
+
account_likes, raw_targets = _parse_account_targets(account_target_pairs)
|
|
132
|
+
|
|
133
|
+
token = resolve_token(token_override)
|
|
134
|
+
|
|
135
|
+
print("** Refreshing SQLite DB **")
|
|
136
|
+
await sync(token, db, full_refresh)
|
|
137
|
+
print("** Done **")
|
|
138
|
+
|
|
139
|
+
with sqlite3.connect(db) as con:
|
|
140
|
+
con.row_factory = sqlite3.Row
|
|
141
|
+
|
|
142
|
+
cur = con.cursor()
|
|
143
|
+
|
|
144
|
+
plan_accts = fetch_plan_accts(cur, account_likes)
|
|
145
|
+
transactions = fetch_transactions(cur, plan_accts)
|
|
146
|
+
|
|
147
|
+
rets = list(
|
|
148
|
+
await asyncio.gather(
|
|
149
|
+
*(
|
|
150
|
+
asyncio.create_task(
|
|
151
|
+
_reconcile_account(
|
|
152
|
+
token,
|
|
153
|
+
acct,
|
|
154
|
+
txns,
|
|
155
|
+
rt * (-1 if acct.account_type in _NEG_BAL_ACCT_TYPES else 1),
|
|
156
|
+
for_real,
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
for rt, acct, txns in zip(
|
|
160
|
+
raw_targets, plan_accts, transactions, strict=True
|
|
161
|
+
)
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
print("Done.")
|
|
167
|
+
|
|
168
|
+
return max(rets)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _parse_account_targets(
|
|
172
|
+
account_target_pairs: list[str],
|
|
173
|
+
) -> tuple[list[str], list[Decimal]]:
|
|
174
|
+
account_likes: list[str] = []
|
|
175
|
+
raw_targets: list[Decimal] = []
|
|
176
|
+
for pair in account_target_pairs:
|
|
177
|
+
account_like, _, target = pair.partition("=")
|
|
178
|
+
account_likes.append(_normalize_account_like(account_like))
|
|
179
|
+
raw_targets.append(Decimal(re.sub("[,$]", "", target)))
|
|
180
|
+
return account_likes, raw_targets
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _normalize_account_like(account_like: str) -> str:
|
|
184
|
+
if "%" in account_like or "_" in account_like:
|
|
185
|
+
return account_like
|
|
186
|
+
|
|
187
|
+
return f"%{account_like}%"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
async def _reconcile_account(
|
|
191
|
+
token: str,
|
|
192
|
+
plan_acct: PlanAccount,
|
|
193
|
+
transactions: list[Transaction],
|
|
194
|
+
target: Decimal,
|
|
195
|
+
for_real: bool,
|
|
196
|
+
) -> int:
|
|
197
|
+
prefix = f"[{plan_acct.account_name}]"
|
|
198
|
+
|
|
199
|
+
to_reconcile, balance_met = find_to_reconcile(
|
|
200
|
+
transactions,
|
|
201
|
+
plan_acct.cleared_balance,
|
|
202
|
+
target,
|
|
203
|
+
progress_desc=f"{prefix} Testing combinations",
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
if not to_reconcile:
|
|
207
|
+
if balance_met:
|
|
208
|
+
print(f"{prefix} Balance already reconciled to target")
|
|
209
|
+
return 0
|
|
210
|
+
pretty_target = format_currency(
|
|
211
|
+
target, currency=plan_acct.currency, locale=_LOCALE_EN_US
|
|
212
|
+
)
|
|
213
|
+
print(f"{prefix} No match found for target {pretty_target}")
|
|
214
|
+
return 1
|
|
215
|
+
|
|
216
|
+
print(
|
|
217
|
+
f"{prefix} Match found:",
|
|
218
|
+
*(
|
|
219
|
+
f"{prefix} * {t.pretty()}"
|
|
220
|
+
for t in sorted(to_reconcile, key=lambda t: t.amount)
|
|
221
|
+
),
|
|
222
|
+
sep=os.linesep,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
if for_real:
|
|
226
|
+
await do_reconcile(
|
|
227
|
+
token,
|
|
228
|
+
plan_acct.plan_id,
|
|
229
|
+
to_reconcile,
|
|
230
|
+
progress_desc=f"{prefix} Reconciling",
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
return 0
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def fetch_plan_accts(
|
|
237
|
+
cur: sqlite3.Cursor, account_likes: list[str]
|
|
238
|
+
) -> list[PlanAccount]:
|
|
239
|
+
plan_accts = cur.execute(
|
|
240
|
+
f"""
|
|
241
|
+
SELECT
|
|
242
|
+
plans.id as plan_id
|
|
243
|
+
, plans.name as plan_name
|
|
244
|
+
, accounts.name as account_name
|
|
245
|
+
, accounts.type as account_type
|
|
246
|
+
, accounts.id as account_id
|
|
247
|
+
, accounts.type as account_type
|
|
248
|
+
, accounts.cleared_balance
|
|
249
|
+
, plans.currency_format_iso_code
|
|
250
|
+
FROM accounts
|
|
251
|
+
JOIN plans
|
|
252
|
+
ON accounts.plan_id = plans.id
|
|
253
|
+
WHERE
|
|
254
|
+
TRUE
|
|
255
|
+
AND NOT deleted
|
|
256
|
+
AND NOT closed
|
|
257
|
+
AND ({" OR ".join("accounts.name LIKE ?" for _ in account_likes)})
|
|
258
|
+
ORDER BY
|
|
259
|
+
CASE
|
|
260
|
+
{" ".join(f"WHEN accounts.name LIKE ? THEN {i}" for i, _ in enumerate(account_likes))}
|
|
261
|
+
END
|
|
262
|
+
""",
|
|
263
|
+
(*account_likes, *account_likes),
|
|
264
|
+
).fetchall()
|
|
265
|
+
|
|
266
|
+
if len(plan_accts) != len(account_likes):
|
|
267
|
+
raise ValueError(
|
|
268
|
+
f"\n❌ Must have {len(account_likes)} total account matches for the supplied pairs, but instead found: {_pretty(plan_accts)}\nChange account LIKE patterns to be more precise and try again."
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
return [
|
|
272
|
+
PlanAccount(
|
|
273
|
+
plan_id=pl["plan_id"],
|
|
274
|
+
account_name=pl["account_name"],
|
|
275
|
+
account_id=pl["account_id"],
|
|
276
|
+
cleared_balance=Decimal(-pl["cleared_balance"]) / 1000,
|
|
277
|
+
account_type=pl["account_type"],
|
|
278
|
+
currency=pl["currency_format_iso_code"],
|
|
279
|
+
)
|
|
280
|
+
for pl in plan_accts
|
|
281
|
+
]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _pretty(plan_accts: list[sqlite3.Row]) -> str:
|
|
285
|
+
if not plan_accts:
|
|
286
|
+
return "nothing!"
|
|
287
|
+
|
|
288
|
+
return "\n" + "\n".join(
|
|
289
|
+
sorted(f" * {pl['plan_name']} - {pl['account_name']}" for pl in plan_accts)
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def fetch_transactions(
|
|
294
|
+
cur: sqlite3.Cursor, plan_accts: list[PlanAccount]
|
|
295
|
+
) -> list[list[Transaction]]:
|
|
296
|
+
assert plan_accts
|
|
297
|
+
|
|
298
|
+
unreconciled = cur.execute(
|
|
299
|
+
f"""
|
|
300
|
+
SELECT
|
|
301
|
+
id
|
|
302
|
+
, plan_id
|
|
303
|
+
, account_id
|
|
304
|
+
, amount
|
|
305
|
+
, amount_formatted
|
|
306
|
+
, payee_name
|
|
307
|
+
, cleared
|
|
308
|
+
FROM transactions
|
|
309
|
+
WHERE
|
|
310
|
+
TRUE
|
|
311
|
+
AND cleared != 'reconciled'
|
|
312
|
+
AND NOT deleted
|
|
313
|
+
AND ({" OR ".join("account_id = ?" for _ in plan_accts)})
|
|
314
|
+
ORDER BY date
|
|
315
|
+
""",
|
|
316
|
+
tuple(pl.account_id for pl in plan_accts),
|
|
317
|
+
).fetchall()
|
|
318
|
+
|
|
319
|
+
grouped: dict[str, list[Transaction]] = {pl.account_id: [] for pl in plan_accts}
|
|
320
|
+
for u in unreconciled:
|
|
321
|
+
grouped[u["account_id"]].append(
|
|
322
|
+
Transaction(
|
|
323
|
+
u["plan_id"],
|
|
324
|
+
u["id"],
|
|
325
|
+
Decimal(-u["amount"]) / 1000,
|
|
326
|
+
u["amount_formatted"],
|
|
327
|
+
u["payee_name"],
|
|
328
|
+
u["cleared"],
|
|
329
|
+
)
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
return list(grouped.values())
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def find_to_reconcile(
|
|
336
|
+
transactions: list[Transaction],
|
|
337
|
+
account_balance: Decimal,
|
|
338
|
+
target: Decimal,
|
|
339
|
+
progress_desc: str,
|
|
340
|
+
) -> tuple[tuple[Transaction, ...], bool]:
|
|
341
|
+
cleared, uncleared = partition(transactions, lambda t: t.cleared == "cleared")
|
|
342
|
+
|
|
343
|
+
reconciled_balance = account_balance - sum(t.amount for t in cleared)
|
|
344
|
+
if reconciled_balance == target and not cleared:
|
|
345
|
+
return (), True
|
|
346
|
+
|
|
347
|
+
with tldm[Never](
|
|
348
|
+
total=2 ** len(uncleared), desc=progress_desc, complete_bar_on_early_finish=True
|
|
349
|
+
) as pbar:
|
|
350
|
+
for n in range(len(uncleared) + 1):
|
|
351
|
+
for combo in itertools.combinations(uncleared, n):
|
|
352
|
+
if (
|
|
353
|
+
reconciled_balance
|
|
354
|
+
+ sum(t.amount for t in itertools.chain(cleared, combo))
|
|
355
|
+
== target
|
|
356
|
+
):
|
|
357
|
+
return tuple(itertools.chain(cleared, combo)), True
|
|
358
|
+
pbar.update()
|
|
359
|
+
|
|
360
|
+
return (), False
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
async def do_reconcile(
|
|
364
|
+
token: str, plan_id: str, to_reconcile: Sequence[Transaction], progress_desc: str
|
|
365
|
+
) -> None:
|
|
366
|
+
yc = YnabClient(token)
|
|
367
|
+
with tldm[Never](total=len(to_reconcile), desc=progress_desc) as pbar:
|
|
368
|
+
async with aiohttp.ClientSession() as session:
|
|
369
|
+
try:
|
|
370
|
+
await yc.reconcile(session, pbar, plan_id, [t.id for t in to_reconcile])
|
|
371
|
+
except Error4034:
|
|
372
|
+
await asyncio.gather(
|
|
373
|
+
*(
|
|
374
|
+
yc.reconcile(session, pbar, to_reconcile[0].plan_id, [t.id])
|
|
375
|
+
for t in to_reconcile
|
|
376
|
+
)
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def partition[T](
|
|
381
|
+
items: Iterable[T], func: Callable[[T], bool]
|
|
382
|
+
) -> tuple[list[T], list[T]]:
|
|
383
|
+
trues, falses = [], []
|
|
384
|
+
for i in items:
|
|
385
|
+
if func(i):
|
|
386
|
+
trues.append(i)
|
|
387
|
+
else:
|
|
388
|
+
falses.append(i)
|
|
389
|
+
return trues, falses
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
class Error4034(Exception):
|
|
393
|
+
"""Raised when an internal YNAB rate-limit is reached. A workaround is to reconcile one-at-a-time."""
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
@dataclass
|
|
397
|
+
class YnabClient:
|
|
398
|
+
token: str
|
|
399
|
+
headers: dict[str, str] = field(init=False)
|
|
400
|
+
|
|
401
|
+
def __post_init__(self) -> None:
|
|
402
|
+
self.headers = {
|
|
403
|
+
"Authorization": f"Bearer {self.token}",
|
|
404
|
+
"Content-Type": "application/json",
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async def reconcile(
|
|
408
|
+
self,
|
|
409
|
+
session: aiohttp.ClientSession,
|
|
410
|
+
pbar: tldm[Never],
|
|
411
|
+
plan_id: str,
|
|
412
|
+
transaction_ids: list[str],
|
|
413
|
+
) -> None:
|
|
414
|
+
reconciled = [{"id": t, "cleared": "reconciled"} for t in transaction_ids]
|
|
415
|
+
|
|
416
|
+
url = f"https://api.ynab.com/v1/plans/{plan_id}/transactions"
|
|
417
|
+
|
|
418
|
+
async with session.request(
|
|
419
|
+
"PATCH", url, headers=self.headers, json={"transactions": reconciled}
|
|
420
|
+
) as resp:
|
|
421
|
+
body = await resp.json()
|
|
422
|
+
|
|
423
|
+
if body.get("error", {}).get("id") == "403.4":
|
|
424
|
+
raise Error4034()
|
|
425
|
+
|
|
426
|
+
pbar.update(len(transaction_ids))
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def run(argv: Sequence[str] | None = None, *, token_override: str | None = None) -> int:
|
|
430
|
+
return asyncio.run(async_run(argv, token_override=token_override))
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
__all__ = [default_db_path.__name__, run.__name__, sync.__name__]
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import datetime
|
|
4
|
+
import re
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
import ynab
|
|
9
|
+
|
|
10
|
+
from manager_for_ynab._auth import resolve_token
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import Generator
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
_PACKAGE = "manager-for-ynab zero-out"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog=_PACKAGE,
|
|
23
|
+
description="Zero out planned amount for a category from a start year-month through the end month.",
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--plan-id",
|
|
27
|
+
help="YNAB plan ID. If omitted, uses the most recently updated one.",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"--category-name",
|
|
31
|
+
required=True,
|
|
32
|
+
help="Category name to update (matched with a regex but must match uniquely).",
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--start",
|
|
36
|
+
type=parse_year_month,
|
|
37
|
+
required=True,
|
|
38
|
+
help="Start year-month (e.g. 2025-01).",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"--end",
|
|
42
|
+
type=parse_year_month,
|
|
43
|
+
help="End year-month inclusive (e.g. 2025-06). Defaults to current month.",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--for-real",
|
|
47
|
+
action="store_true",
|
|
48
|
+
help="Apply the updates instead of only previewing them.",
|
|
49
|
+
)
|
|
50
|
+
return parser
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_year_month(raw: str) -> tuple[int, int]:
|
|
54
|
+
year, month = tuple(map(int, raw.split("-")))
|
|
55
|
+
if month < 1 or month > 12:
|
|
56
|
+
raise argparse.ArgumentTypeError(f"Invalid month in {raw!r}. Expected YYYY-MM.")
|
|
57
|
+
return year, month
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def month_range(
|
|
61
|
+
start_year: int, start_month: int, end_year: int, end_month: int
|
|
62
|
+
) -> Generator[tuple[int, int]]:
|
|
63
|
+
return (
|
|
64
|
+
(year, month0 + 1)
|
|
65
|
+
for year, month0 in (
|
|
66
|
+
divmod(i, 12)
|
|
67
|
+
for i in range(start_year * 12 + start_month - 1, end_year * 12 + end_month)
|
|
68
|
+
)
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def format_months(months: tuple[tuple[int, int], ...]) -> list[str]:
|
|
73
|
+
return [f"{year}-{month:02d}" for year, month in months]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _update_month_category(
|
|
77
|
+
categories_api: ynab.CategoriesApi,
|
|
78
|
+
plan_id: str,
|
|
79
|
+
category_id: str,
|
|
80
|
+
year: int,
|
|
81
|
+
month: int,
|
|
82
|
+
) -> tuple[str, str | None]:
|
|
83
|
+
month_str = f"{year}-{month:02d}"
|
|
84
|
+
try:
|
|
85
|
+
categories_api.update_month_category(
|
|
86
|
+
plan_id=plan_id,
|
|
87
|
+
month=datetime.date(year, month, 1),
|
|
88
|
+
category_id=category_id,
|
|
89
|
+
data=ynab.PatchMonthCategoryWrapper(
|
|
90
|
+
category=ynab.SaveMonthCategory(budgeted=0)
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
return month_str, None
|
|
94
|
+
except ynab.ApiException as e:
|
|
95
|
+
return month_str, f"{e}"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _get_plan_id(plans_api: ynab.PlansApi, plan_id: str | None) -> str:
|
|
99
|
+
if plan_id:
|
|
100
|
+
return plan_id
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
plans_response = plans_api.get_plans()
|
|
104
|
+
except ynab.ApiException as e:
|
|
105
|
+
raise RuntimeError(f"Failed to fetch plans: {e}") from e
|
|
106
|
+
|
|
107
|
+
plans = plans_response.data.plans
|
|
108
|
+
if not plans:
|
|
109
|
+
raise RuntimeError("No plans found in this YNAB account.")
|
|
110
|
+
|
|
111
|
+
plan = max(plans, key=lambda b: b.last_modified_on or datetime.datetime.min)
|
|
112
|
+
print(f"Using plan: {plan.name} ({plan.id})")
|
|
113
|
+
return str(plan.id)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _get_category_id(
|
|
117
|
+
categories_api: ynab.CategoriesApi, plan_id: str, category_name: str
|
|
118
|
+
) -> tuple[str, str]:
|
|
119
|
+
try:
|
|
120
|
+
cats_resp = categories_api.get_categories(plan_id)
|
|
121
|
+
except ynab.ApiException as e:
|
|
122
|
+
raise RuntimeError(f"Failed to fetch categories: {e}") from e
|
|
123
|
+
|
|
124
|
+
matching = [
|
|
125
|
+
category
|
|
126
|
+
for group in cats_resp.data.category_groups
|
|
127
|
+
for category in group.categories
|
|
128
|
+
if re.search(category_name, category.name, re.IGNORECASE)
|
|
129
|
+
]
|
|
130
|
+
if len(matching) != 1:
|
|
131
|
+
names = ", ".join(category.name for category in matching)
|
|
132
|
+
raise RuntimeError(
|
|
133
|
+
f"Found {len(matching)} categories matching '{category_name}' - {names}."
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
category = matching[0]
|
|
137
|
+
return str(category.id), category.name
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
async def _run_updates(
|
|
141
|
+
categories_api: ynab.CategoriesApi,
|
|
142
|
+
plan_id: str,
|
|
143
|
+
category_id: str,
|
|
144
|
+
months: tuple[tuple[int, int], ...],
|
|
145
|
+
) -> None:
|
|
146
|
+
with ThreadPoolExecutor(max_workers=5) as executor:
|
|
147
|
+
tasks = tuple(
|
|
148
|
+
asyncio.get_running_loop().run_in_executor(
|
|
149
|
+
executor,
|
|
150
|
+
_update_month_category,
|
|
151
|
+
categories_api,
|
|
152
|
+
plan_id,
|
|
153
|
+
category_id,
|
|
154
|
+
year,
|
|
155
|
+
month,
|
|
156
|
+
)
|
|
157
|
+
for year, month in months
|
|
158
|
+
)
|
|
159
|
+
for task in tasks:
|
|
160
|
+
month_str, err = await task
|
|
161
|
+
if err is None:
|
|
162
|
+
print(f"{month_str}: set planned to 0.")
|
|
163
|
+
else:
|
|
164
|
+
print(f"Failed to update month {month_str}: {err}")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def run(argv: Sequence[str] | None = None, *, token_override: str | None = None) -> int:
|
|
168
|
+
args = build_parser().parse_args(argv)
|
|
169
|
+
|
|
170
|
+
token = resolve_token(token_override)
|
|
171
|
+
|
|
172
|
+
configuration = ynab.Configuration(access_token=token)
|
|
173
|
+
|
|
174
|
+
with ynab.ApiClient(configuration) as api_client:
|
|
175
|
+
plans_api = ynab.PlansApi(api_client)
|
|
176
|
+
categories_api = ynab.CategoriesApi(api_client)
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
plan_id = _get_plan_id(plans_api, args.plan_id)
|
|
180
|
+
category_id, category_name = _get_category_id(
|
|
181
|
+
categories_api, plan_id, args.category_name
|
|
182
|
+
)
|
|
183
|
+
except RuntimeError as e:
|
|
184
|
+
print(e)
|
|
185
|
+
return 1
|
|
186
|
+
|
|
187
|
+
print(f"Using category: {category_name} ({category_id})")
|
|
188
|
+
|
|
189
|
+
start_year, start_month = args.start
|
|
190
|
+
if args.end:
|
|
191
|
+
end_year, end_month = args.end
|
|
192
|
+
else:
|
|
193
|
+
today = datetime.date.today()
|
|
194
|
+
end_year, end_month = today.year, today.month
|
|
195
|
+
|
|
196
|
+
months = tuple(month_range(start_year, start_month, end_year, end_month))
|
|
197
|
+
month_labels = format_months(months)
|
|
198
|
+
if not month_labels:
|
|
199
|
+
print("No months selected.")
|
|
200
|
+
return 0
|
|
201
|
+
|
|
202
|
+
print("Months to update:", ", ".join(month_labels))
|
|
203
|
+
if not args.for_real:
|
|
204
|
+
print("Use --for-real to actually update categories.")
|
|
205
|
+
return 0
|
|
206
|
+
|
|
207
|
+
asyncio.run(_run_updates(categories_api, plan_id, category_id, months))
|
|
208
|
+
|
|
209
|
+
print("Done.")
|
|
210
|
+
return 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
__all__ = [run.__name__]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: manager_for_ynab
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Manager for YNAB
|
|
5
|
+
Home-page: https://github.com/mxr/manager-for-ynab
|
|
6
|
+
Author: Max R
|
|
7
|
+
Author-email: mxr@users.noreply.github.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: ynab,budget,plan,cli,reconcile,automation,manager
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
13
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
14
|
+
Requires-Python: >=3.14
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: Babel
|
|
18
|
+
Requires-Dist: aiohttp
|
|
19
|
+
Requires-Dist: rich
|
|
20
|
+
Requires-Dist: sqlite-export-for-ynab>=2
|
|
21
|
+
Requires-Dist: tldm
|
|
22
|
+
Requires-Dist: ynab>=4
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# manager-for-ynab
|
|
26
|
+
|
|
27
|
+
[](https://results.pre-commit.ci/latest/github/mxr/manager-for-ynab/main)
|
|
28
|
+
|
|
29
|
+
Manager for YNAB.
|
|
30
|
+
|
|
31
|
+
## What This Does
|
|
32
|
+
|
|
33
|
+
This repo is a single CLI for YNAB-focused tools.
|
|
34
|
+
|
|
35
|
+
- `reconciler`: find and automatically reconciles unreconciled transactions
|
|
36
|
+
- `pending-income`: move pending income transactions to today
|
|
37
|
+
- `zero-out`: set a category's planned amount to zero across a month range
|
|
38
|
+
|
|
39
|
+
Tool-specific docs:
|
|
40
|
+
|
|
41
|
+
- [Reconciler](tools/reconciler/README.md)
|
|
42
|
+
- [Pending Income](tools/pending-income/README.md)
|
|
43
|
+
- [Zero Out](tools/zero-out/README.md)
|
|
44
|
+
|
|
45
|
+
## Installation
|
|
46
|
+
|
|
47
|
+
```console
|
|
48
|
+
$ pip install manager-for-ynab
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
```console
|
|
54
|
+
$ manager-for-ynab --help
|
|
55
|
+
$ manager-for-ynab reconciler --help
|
|
56
|
+
$ manager-for-ynab pending-income --help
|
|
57
|
+
$ manager-for-ynab zero-out --help
|
|
58
|
+
```
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
manager_for_ynab/__init__.py,sha256=u_Xt3XTEMY0grnPdERhQE9HxEacvcFZeqSphl7XvTms,67
|
|
2
|
+
manager_for_ynab/__main__.py,sha256=W3d-XhwSgHNGVcSGPjovgjxPa-n8yJ70k0ks0i0PY7Q,97
|
|
3
|
+
manager_for_ynab/_auth.py,sha256=ztlEiW3xTFb6AqqgTcv0TXtagr8HFcsuAZ3avajZcJU,446
|
|
4
|
+
manager_for_ynab/_main.py,sha256=FnnZz85D_4_UcOkdZDNt0nyUL5Mnx8OeefH-r4FtABI,2077
|
|
5
|
+
manager_for_ynab/_version.py,sha256=lui3ULP0QBEzdZmmM38ta2joZi0jU3E65_A87rv1VGw,450
|
|
6
|
+
manager_for_ynab/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
manager_for_ynab/pending_income/__init__.py,sha256=A7Ow60WchGdVqxBxMYMxL72DCfxScB8w2U3l2NXc1FI,4143
|
|
8
|
+
manager_for_ynab/pending_income/pending_income.sql,sha256=Hy-LR2L1z1mam8QvJoiNlrUmfWUPB4g77wzpnzx10aI,767
|
|
9
|
+
manager_for_ynab/reconciler/__init__.py,sha256=gDQvdr8iiRi2o8mq77F8zdjRW4aAQsDPdg8AkWKsTkA,13236
|
|
10
|
+
manager_for_ynab/zero_out/__init__.py,sha256=bR84GLXiv0EyDNB4SuE-yZL9BQNKqR43YfqKUpbjLuE,6292
|
|
11
|
+
manager_for_ynab-1.0.0.dist-info/licenses/LICENSE,sha256=gQqRlt6eZUGXElH2Nxcy3fBX2_d1tmvo7cWfxFbVjI4,1062
|
|
12
|
+
testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
testing/fixtures.py,sha256=HNKbOuwvv60C-6EFHzTCefFUrQjdZKx53mOY0aCc-1M,566
|
|
14
|
+
testing/seed.sql,sha256=CNOTw7T6y8XgonlCUu-0SbvR3CtzGf8QOZvAvzA2Sv8,4737
|
|
15
|
+
tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
manager_for_ynab-1.0.0.dist-info/METADATA,sha256=A8a6OOcEstxQKgjK5KOnL8IKy_NeUcqHaF-Ru4SFoQQ,1647
|
|
17
|
+
manager_for_ynab-1.0.0.dist-info/WHEEL,sha256=TdQ5LtNwLuxTCjgxN51AgdU5w-KkB9ttmLbzjTH02pg,109
|
|
18
|
+
manager_for_ynab-1.0.0.dist-info/entry_points.txt,sha256=JMIqSKGvhZgjIdLhGqO5X6ktWQcEk0hlXx9n8wGfIm8,65
|
|
19
|
+
manager_for_ynab-1.0.0.dist-info/top_level.txt,sha256=JzksQ-wlpJODt0PfAOlIQ_bgSl26CLEtBrmFcck6eQc,31
|
|
20
|
+
manager_for_ynab-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Max R
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
testing/__init__.py
ADDED
|
File without changes
|
testing/fixtures.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import os.path
|
|
2
|
+
import sqlite3
|
|
3
|
+
from uuid import uuid4
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from aioresponses import aioresponses
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
PLAN_ID_1 = str(uuid4())
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.fixture()
|
|
13
|
+
def db(tmpdir):
|
|
14
|
+
with open(os.path.join(os.path.dirname(__file__), "seed.sql")) as f:
|
|
15
|
+
contents = f.read()
|
|
16
|
+
|
|
17
|
+
path = tmpdir / "db.sqlite"
|
|
18
|
+
with sqlite3.connect(path) as con:
|
|
19
|
+
con.executescript(contents)
|
|
20
|
+
yield str(path)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.fixture
|
|
24
|
+
def mock_aioresponses():
|
|
25
|
+
with aioresponses() as m:
|
|
26
|
+
yield m
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
TOKEN = f"token-{uuid4()}"
|
|
30
|
+
|
|
31
|
+
PLAN_ID = "a20542ae-bb3e-4282-8b3e-df3bdea4be10"
|
testing/seed.sql
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
CREATE TABLE plans (
|
|
2
|
+
id TEXT PRIMARY KEY
|
|
3
|
+
, name TEXT
|
|
4
|
+
, currency_format_currency_symbol TEXT
|
|
5
|
+
, currency_format_iso_code TEXT
|
|
6
|
+
)
|
|
7
|
+
;
|
|
8
|
+
|
|
9
|
+
INSERT INTO plans VALUES (
|
|
10
|
+
'a20542ae-bb3e-4282-8b3e-df3bdea4be10'
|
|
11
|
+
, 'My Plan'
|
|
12
|
+
, '$'
|
|
13
|
+
, 'USD'
|
|
14
|
+
)
|
|
15
|
+
;
|
|
16
|
+
|
|
17
|
+
CREATE TABLE accounts (
|
|
18
|
+
id TEXT PRIMARY KEY
|
|
19
|
+
, plan_id TEXT
|
|
20
|
+
, cleared_balance INT
|
|
21
|
+
, closed BOOLEAN
|
|
22
|
+
, deleted BOOLEAN
|
|
23
|
+
, name TEXT
|
|
24
|
+
, type TEXT
|
|
25
|
+
)
|
|
26
|
+
;
|
|
27
|
+
|
|
28
|
+
INSERT INTO accounts VALUES (
|
|
29
|
+
'8fe2a49b-17b9-47a1-8aaa-c60d661e7f25'
|
|
30
|
+
, (
|
|
31
|
+
SELECT id
|
|
32
|
+
FROM plans
|
|
33
|
+
ORDER BY id LIMIT 1
|
|
34
|
+
)
|
|
35
|
+
, 430000
|
|
36
|
+
, 0
|
|
37
|
+
, 0
|
|
38
|
+
, 'Checking'
|
|
39
|
+
, 'checking'
|
|
40
|
+
)
|
|
41
|
+
;
|
|
42
|
+
|
|
43
|
+
INSERT INTO accounts VALUES (
|
|
44
|
+
'ab56a1c8-439e-4eaf-931b-37f2d68d1cf5'
|
|
45
|
+
, (
|
|
46
|
+
SELECT id
|
|
47
|
+
FROM plans
|
|
48
|
+
ORDER BY id LIMIT 1
|
|
49
|
+
)
|
|
50
|
+
, -200000
|
|
51
|
+
, 0
|
|
52
|
+
, 0
|
|
53
|
+
, 'Credit Card'
|
|
54
|
+
, 'creditCard'
|
|
55
|
+
)
|
|
56
|
+
;
|
|
57
|
+
|
|
58
|
+
CREATE TABLE transactions (
|
|
59
|
+
id TEXT PRIMARY KEY
|
|
60
|
+
, plan_id TEXT
|
|
61
|
+
, account_id TEXT
|
|
62
|
+
, "date" TEXT
|
|
63
|
+
, amount INT
|
|
64
|
+
, amount_formatted TEXT
|
|
65
|
+
, payee_name TEXT
|
|
66
|
+
, cleared TEXT
|
|
67
|
+
, deleted BOOLEAN
|
|
68
|
+
)
|
|
69
|
+
;
|
|
70
|
+
|
|
71
|
+
INSERT INTO transactions VALUES (
|
|
72
|
+
'ae3d9f6b-07f1-4c49-9137-5133c8bf0500'
|
|
73
|
+
, (
|
|
74
|
+
SELECT id
|
|
75
|
+
FROM plans
|
|
76
|
+
ORDER BY id LIMIT 1
|
|
77
|
+
)
|
|
78
|
+
, (
|
|
79
|
+
SELECT id
|
|
80
|
+
FROM accounts
|
|
81
|
+
WHERE name = 'Checking'
|
|
82
|
+
ORDER BY id LIMIT 1
|
|
83
|
+
)
|
|
84
|
+
, '2025-08-01'
|
|
85
|
+
, 400000
|
|
86
|
+
, '-$400.00'
|
|
87
|
+
, 'Payee'
|
|
88
|
+
, 'reconciled'
|
|
89
|
+
, 0
|
|
90
|
+
)
|
|
91
|
+
;
|
|
92
|
+
|
|
93
|
+
INSERT INTO transactions VALUES (
|
|
94
|
+
'9a97f337-28db-4c2d-990f-d9ec0e9bc765'
|
|
95
|
+
, (
|
|
96
|
+
SELECT id
|
|
97
|
+
FROM plans
|
|
98
|
+
ORDER BY id LIMIT 1
|
|
99
|
+
)
|
|
100
|
+
, (
|
|
101
|
+
SELECT id
|
|
102
|
+
FROM accounts
|
|
103
|
+
WHERE name = 'Checking'
|
|
104
|
+
ORDER BY id LIMIT 1
|
|
105
|
+
)
|
|
106
|
+
, '2025-08-01'
|
|
107
|
+
, 30000
|
|
108
|
+
, '-$30.00'
|
|
109
|
+
, 'Payee'
|
|
110
|
+
, 'cleared'
|
|
111
|
+
, 0
|
|
112
|
+
)
|
|
113
|
+
;
|
|
114
|
+
|
|
115
|
+
INSERT INTO transactions VALUES (
|
|
116
|
+
'c479c335-b54f-48b9-8b74-49a907f1b3f2'
|
|
117
|
+
, (
|
|
118
|
+
SELECT id
|
|
119
|
+
FROM plans
|
|
120
|
+
ORDER BY id LIMIT 1
|
|
121
|
+
)
|
|
122
|
+
, (
|
|
123
|
+
SELECT id
|
|
124
|
+
FROM accounts
|
|
125
|
+
WHERE name = 'Checking'
|
|
126
|
+
ORDER BY id LIMIT 1
|
|
127
|
+
)
|
|
128
|
+
, '2025-08-01'
|
|
129
|
+
, 60000
|
|
130
|
+
, '-$60.00'
|
|
131
|
+
, 'Payee'
|
|
132
|
+
, 'uncleared'
|
|
133
|
+
, 0
|
|
134
|
+
)
|
|
135
|
+
;
|
|
136
|
+
|
|
137
|
+
INSERT INTO transactions VALUES (
|
|
138
|
+
'96817e5f-d272-4012-9790-38f8a8e2be90'
|
|
139
|
+
, (
|
|
140
|
+
SELECT id
|
|
141
|
+
FROM plans
|
|
142
|
+
ORDER BY id LIMIT 1
|
|
143
|
+
)
|
|
144
|
+
, (
|
|
145
|
+
SELECT id
|
|
146
|
+
FROM accounts
|
|
147
|
+
WHERE name = 'Checking'
|
|
148
|
+
ORDER BY id LIMIT 1
|
|
149
|
+
)
|
|
150
|
+
, '2025-08-01'
|
|
151
|
+
, 20000
|
|
152
|
+
, '-$20.00'
|
|
153
|
+
, 'Payee'
|
|
154
|
+
, 'uncleared'
|
|
155
|
+
, 0
|
|
156
|
+
)
|
|
157
|
+
;
|
|
158
|
+
|
|
159
|
+
INSERT INTO transactions VALUES (
|
|
160
|
+
'eeef0922-b226-4f8a-bf00-66d4d98e348c'
|
|
161
|
+
, (
|
|
162
|
+
SELECT id
|
|
163
|
+
FROM plans
|
|
164
|
+
ORDER BY id LIMIT 1
|
|
165
|
+
)
|
|
166
|
+
, (
|
|
167
|
+
SELECT id
|
|
168
|
+
FROM accounts
|
|
169
|
+
WHERE name = 'Checking'
|
|
170
|
+
ORDER BY id LIMIT 1
|
|
171
|
+
)
|
|
172
|
+
, '2025-08-01'
|
|
173
|
+
, 10000
|
|
174
|
+
, '-$10.00'
|
|
175
|
+
, 'Payee'
|
|
176
|
+
, 'uncleared'
|
|
177
|
+
, 0
|
|
178
|
+
)
|
|
179
|
+
;
|
|
180
|
+
|
|
181
|
+
INSERT INTO transactions VALUES (
|
|
182
|
+
'21c45599-4113-4888-9969-66d42553d870'
|
|
183
|
+
, (
|
|
184
|
+
SELECT id
|
|
185
|
+
FROM plans
|
|
186
|
+
ORDER BY id LIMIT 1
|
|
187
|
+
)
|
|
188
|
+
, (
|
|
189
|
+
SELECT id
|
|
190
|
+
FROM accounts
|
|
191
|
+
WHERE name = 'Credit Card'
|
|
192
|
+
ORDER BY id LIMIT 1
|
|
193
|
+
)
|
|
194
|
+
, '2025-08-01'
|
|
195
|
+
, -400000
|
|
196
|
+
, '$400.00'
|
|
197
|
+
, 'Payee'
|
|
198
|
+
, 'reconciled'
|
|
199
|
+
, 0
|
|
200
|
+
)
|
|
201
|
+
;
|
|
202
|
+
|
|
203
|
+
INSERT INTO transactions VALUES (
|
|
204
|
+
'956ff61f-b0e4-4f36-bf7d-f31d008ff7e4'
|
|
205
|
+
, (
|
|
206
|
+
SELECT id
|
|
207
|
+
FROM plans
|
|
208
|
+
ORDER BY id LIMIT 1
|
|
209
|
+
)
|
|
210
|
+
, (
|
|
211
|
+
SELECT id
|
|
212
|
+
FROM accounts
|
|
213
|
+
WHERE name = 'Credit Card'
|
|
214
|
+
ORDER BY id LIMIT 1
|
|
215
|
+
)
|
|
216
|
+
, '2025-08-01'
|
|
217
|
+
, -30000
|
|
218
|
+
, '$30.00'
|
|
219
|
+
, 'Payee'
|
|
220
|
+
, 'cleared'
|
|
221
|
+
, 0
|
|
222
|
+
)
|
|
223
|
+
;
|
|
224
|
+
|
|
225
|
+
INSERT INTO transactions VALUES (
|
|
226
|
+
'c9ca467d-e89d-4d0d-8356-f37d4f798c5f'
|
|
227
|
+
, (
|
|
228
|
+
SELECT id
|
|
229
|
+
FROM plans
|
|
230
|
+
ORDER BY id LIMIT 1
|
|
231
|
+
)
|
|
232
|
+
, (
|
|
233
|
+
SELECT id
|
|
234
|
+
FROM accounts
|
|
235
|
+
WHERE name = 'Credit Card'
|
|
236
|
+
ORDER BY id LIMIT 1
|
|
237
|
+
)
|
|
238
|
+
, '2025-08-01'
|
|
239
|
+
, -60000
|
|
240
|
+
, '$60.00'
|
|
241
|
+
, 'Payee'
|
|
242
|
+
, 'uncleared'
|
|
243
|
+
, 0
|
|
244
|
+
)
|
|
245
|
+
;
|
|
246
|
+
|
|
247
|
+
INSERT INTO transactions VALUES (
|
|
248
|
+
'258b33fb-a2b2-4833-9274-05697c68ff1d'
|
|
249
|
+
, (
|
|
250
|
+
SELECT id
|
|
251
|
+
FROM plans
|
|
252
|
+
ORDER BY id LIMIT 1
|
|
253
|
+
)
|
|
254
|
+
, (
|
|
255
|
+
SELECT id
|
|
256
|
+
FROM accounts
|
|
257
|
+
WHERE name = 'Credit Card'
|
|
258
|
+
ORDER BY id LIMIT 1
|
|
259
|
+
)
|
|
260
|
+
, '2025-08-01'
|
|
261
|
+
, -20000
|
|
262
|
+
, '$20.00'
|
|
263
|
+
, 'Payee'
|
|
264
|
+
, 'uncleared'
|
|
265
|
+
, 0
|
|
266
|
+
)
|
|
267
|
+
;
|
|
268
|
+
|
|
269
|
+
INSERT INTO transactions VALUES (
|
|
270
|
+
'd9faa297-f59e-4516-bcbf-664b298ff09e'
|
|
271
|
+
, (
|
|
272
|
+
SELECT id
|
|
273
|
+
FROM plans
|
|
274
|
+
ORDER BY id LIMIT 1
|
|
275
|
+
)
|
|
276
|
+
, (
|
|
277
|
+
SELECT id
|
|
278
|
+
FROM accounts
|
|
279
|
+
WHERE name = 'Credit Card'
|
|
280
|
+
ORDER BY id LIMIT 1
|
|
281
|
+
)
|
|
282
|
+
, '2025-08-01'
|
|
283
|
+
, -10000
|
|
284
|
+
, '$10.00'
|
|
285
|
+
, 'Payee'
|
|
286
|
+
, 'uncleared'
|
|
287
|
+
, 0
|
|
288
|
+
)
|
|
289
|
+
;
|
tests/__init__.py
ADDED
|
File without changes
|