Skip to content

Commit

Permalink
Update linters configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
gperiard committed Nov 24, 2024
1 parent d0e8739 commit 5669c01
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 28 deletions.
9 changes: 5 additions & 4 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[flake8]
ignore = E231, E241
max-line-length = 120
extend-ignore = E203
exclude = .git,__pycache__,build,dist
per-file-ignores =
__init__.py:F401
max-line-length = 88
count = true
# imported but unused
__init__.py: F401
7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,9 @@ pyyaml = "^6.0.1"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 120
target-version = ['py311']
include = '\.pyi?$'
60 changes: 37 additions & 23 deletions ynab2splitwise/backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import logging
import os
import argparse
from datetime import datetime
from sync import YNABClient


def backfill_splits(account_config: dict, dry_run: bool = False) -> None:
"""
Backfills category splits for all previously synced transactions that haven't been split yet.
Expand All @@ -23,16 +23,17 @@ def backfill_splits(account_config: dict, dry_run: bool = False) -> None:
response = ynab.request.get(
f"{ynab.base_url}/budgets/{ynab.budget_id}/transactions"
).json()

transactions = response["data"]["transactions"]

# Filter for synced transactions (green flag) that don't have subtransactions
synced_transactions = [
t for t in transactions
if t.get("flag_color") == "green"
t
for t in transactions
if t.get("flag_color") == "green"
and (not t.get("subtransactions") or len(t.get("subtransactions")) == 0)
]

if not synced_transactions:
logging.info("No transactions found that need backfilling")
return
Expand All @@ -41,10 +42,14 @@ def backfill_splits(account_config: dict, dry_run: bool = False) -> None:
synced_transactions.sort(key=lambda x: x["date"])
first_transaction = synced_transactions[0]
last_transaction = synced_transactions[-1]
total_amount = sum(abs(t["amount"]) for t in synced_transactions) / 1000 # Convert to dollars
total_amount = (
sum(abs(t["amount"]) for t in synced_transactions) / 1000
) # Convert to dollars

logging.info(f"Found {len(synced_transactions)} transactions to backfill")
logging.info(f"Date range: {first_transaction['date']} to {last_transaction['date']}")
logging.info(
f"Date range: {first_transaction['date']} to {last_transaction['date']}"
)
logging.info(f"Total amount to be split: ${total_amount:.2f}")

if dry_run:
Expand All @@ -56,24 +61,24 @@ def backfill_splits(account_config: dict, dry_run: bool = False) -> None:
f"Transaction: {t['date']} {t['payee_name']} "
f"(${abs(t['amount']) / 1000:.2f}) would be split into:"
)
logging.info(
f" - Original category: ${abs(remaining_amount) / 1000:.2f}"
)
logging.info(
f" - Splitwise category: ${abs(split_amount) / 1000:.2f}"
)
logging.info(f" - Original category: ${abs(remaining_amount) / 1000:.2f}")
logging.info(f" - Splitwise category: ${abs(split_amount) / 1000:.2f}")
logging.info("\nSummary:")
logging.info(f"Total transactions to be updated: {len(synced_transactions)}")
logging.info(f"First transaction date: {first_transaction['date']} ({first_transaction['payee_name']})")
logging.info(f"Last transaction date: {last_transaction['date']} ({last_transaction['payee_name']})")
logging.info(
f"First transaction date: {first_transaction['date']} ({first_transaction['payee_name']})"
)
logging.info(
f"Last transaction date: {last_transaction['date']} ({last_transaction['payee_name']})"
)
logging.info(f"Total amount to be split: ${total_amount:.2f}")
return

# Process transactions in batches of 100 to avoid API limits
batch_size = 100
processed_count = 0
for i in range(0, len(synced_transactions), batch_size):
batch = synced_transactions[i:i + batch_size]
batch = synced_transactions[i : i + batch_size]
try:
ynab.set_transactions_synced(batch)
processed_count += len(batch)
Expand All @@ -83,15 +88,23 @@ def backfill_splits(account_config: dict, dry_run: bool = False) -> None:

logging.info("\nBackfill Summary:")
logging.info(f"Total transactions processed: {processed_count}")
logging.info(f"First transaction date: {first_transaction['date']} ({first_transaction['payee_name']})")
logging.info(f"Last transaction date: {last_transaction['date']} ({last_transaction['payee_name']})")
logging.info(
f"First transaction date: {first_transaction['date']} ({first_transaction['payee_name']})"
)
logging.info(
f"Last transaction date: {last_transaction['date']} ({last_transaction['payee_name']})"
)
logging.info(f"Total amount split: ${total_amount:.2f}")


def main():
# Set up argument parser
parser = argparse.ArgumentParser(description='Backfill YNAB transaction splits')
parser.add_argument('--dry-run', action='store_true',
help='Show what would be done without making actual changes')
parser = argparse.ArgumentParser(description="Backfill YNAB transaction splits")
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be done without making actual changes",
)
args = parser.parse_args()

logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO").upper())
Expand All @@ -111,5 +124,6 @@ def main():

logging.info("Finished YNAB to Splitwise backfill")


if __name__ == "__main__":
main()

0 comments on commit 5669c01

Please sign in to comment.