-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add support for use in importer hooks #16
Open
blaggacao
wants to merge
6
commits into
maread99:main
Choose a base branch
from
blaggacao:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f02edc1
fix: adopt main ledger base account names
blaggacao b92eb33
feat: add support for use in importer hooks
blaggacao ad7dea9
feat: add reconcile hook
blaggacao a31a91b
fix: remove oversight
blaggacao 118cf44
fix: make new cliargument optional
blaggacao 51ec6d4
Move all output to stderr
maread99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
from beancount.core.data import Transaction, Entries | ||
from beancount.ingest import extract | ||
|
||
from . import utils | ||
from . import reconcile | ||
from .errors import BeanaheadWriteError | ||
|
||
|
||
class ReconcileExpected: | ||
""" | ||
Hook class for smart_importer to reconcile expected entries on the fly. | ||
|
||
You also need to use the adapted duplicate hook to avoid false positives | ||
using the new style import invocation: | ||
|
||
... | ||
hools = [ReconcileExpected.adapted_find_duplicate_entries] | ||
beancount.ingest.scripts_utils.ingest(CONFIG, hooks=hooks) | ||
""" | ||
|
||
def __init__(self, x_txns_file): | ||
path = utils.get_verified_path(x_txns_file) | ||
utils.set_root_accounts_context(x_txns_file) | ||
_ = utils.get_verified_ledger_file_key(path) # just verify that a ledger | ||
self.expected_txns_path = path | ||
self.expected_txns: list[Transaction] = utils.get_unverified_txns(path) | ||
|
||
def __call__(self, importer, file, imported_entries, existing_entries) -> Entries: | ||
"""Apply the hook and modify the imported entries. | ||
|
||
Args: | ||
importer: The importer that this hooks is being applied to. | ||
file: The file that is being imported. | ||
imported_entries: The current list of imported entries. | ||
existing_entries: The existing entries, as passed to the extract | ||
function. | ||
|
||
Returns: | ||
The updated imported entries. | ||
""" | ||
new_txns, new_other = reconcile.separate_out_txns(imported_entries) | ||
reconciled_x_txns = reconcile.reconcile_x_txns(self.expected_txns, new_txns) | ||
|
||
updated_new_txns = reconcile.update_new_txns(new_txns, reconciled_x_txns) | ||
updated_entries = updated_new_txns + new_other | ||
|
||
# Update expected transation file | ||
x_txns_to_remove = [] | ||
for x_txn, _ in reconciled_x_txns: | ||
if x_txn in self.expected_txns: | ||
x_txns_to_remove.append(x_txn) | ||
|
||
prev_contents = utils.get_content(self.expected_txns_path) | ||
try: | ||
utils.remove_txns_from_ledger(self.expected_txns_path, x_txns_to_remove) | ||
except Exception as err: | ||
utils.write(self.expected_txns_path, prev_contents) | ||
raise BeanaheadWriteError( | ||
self.expected_txns_path, [self.expected_txns_path] | ||
) from err | ||
|
||
return updated_entries | ||
|
||
@staticmethod | ||
def adapted_find_duplicate_entries(new_entries_list, existing_entries): | ||
keep = [] | ||
# filter out expected transactions from duplicate detection | ||
for entry in existing_entries: | ||
if isinstance(entry, Transaction) and utils.TAGS_X & entry.tags: | ||
continue | ||
keep.append(entry) | ||
return extract.find_duplicate_entries(new_entries_list, keep) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
import datetime | ||
from pathlib import Path | ||
import re | ||
import sys | ||
|
||
from beancount import loader | ||
from beancount.core import data | ||
|
@@ -29,6 +30,14 @@ | |
TAG_RX = "rx_txn" | ||
TAGS_X = set([TAG_X, TAG_RX]) | ||
|
||
ADOPT_OPTIONS = [ | ||
"name_assets", | ||
"name_liabilities", | ||
"name_income", | ||
"name_expenses", | ||
"name_equity", | ||
] | ||
|
||
RX_META_DFLTS = { | ||
"final": None, | ||
"roll": True, | ||
|
@@ -67,6 +76,26 @@ | |
|
||
LEDGER_FILE_KEYS = ["x", "rx"] | ||
|
||
RootAccountsContext = {} # global context | ||
|
||
|
||
def set_root_accounts_context(path_ledger: str) -> dict[str]: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would you mind adding a simple test to verify that all's working as expected when users are using non-default category names? |
||
"""Set the root accounts context from the ledger file path. | ||
|
||
Returns | ||
------- | ||
dict[str] | ||
The name options set in the ledger. | ||
""" | ||
name_options: dict[str] = {} | ||
options = get_options(path_ledger) | ||
for opt in ADOPT_OPTIONS: | ||
if opt in options: | ||
name_options[opt] = options[opt] | ||
global RootAccountsContext | ||
RootAccountsContext = name_options | ||
return name_options | ||
|
||
|
||
def validate_file_key(file_key: str): | ||
"""Validate a file_key. | ||
|
@@ -114,8 +143,15 @@ def compose_header_footer(file_key: str) -> tuple[str, str]: | |
""" | ||
config = FILE_CONFIG[file_key] | ||
plugin, tag, comment = config["plugin"], config["tag"], config["comment"] | ||
extra_headers = "" | ||
for k, v in RootAccountsContext.items(): | ||
extra_headers += f'option "{k}" "{v}"\n' | ||
|
||
header = f"""option "title" "{config['title']}"\n""" | ||
if extra_headers: | ||
header += "\n" | ||
header += extra_headers | ||
header += "\n" | ||
if plugin is not None: | ||
header += f'plugin "{plugin}"\n' | ||
header += f"pushtag #{tag}\n" | ||
|
@@ -518,7 +554,7 @@ def reverse_automatic_balancing(txn: Transaction) -> Transaction: | |
""" | ||
new_postings = [] | ||
for posting in txn.postings: | ||
if AUTOMATIC_META in posting.meta: | ||
if AUTOMATIC_META in (posting.meta or {}): | ||
meta = {k: v for k, v in posting.meta.items() if k != AUTOMATIC_META} | ||
posting = posting._replace(units=None, meta=meta) | ||
new_postings.append(posting) | ||
|
@@ -537,10 +573,7 @@ def is_assets_account(string: str) -> bool: | |
>>> is_assets_account("Assets:US:BofA:Checking") | ||
True | ||
""" | ||
return is_account_type("Assets", string) | ||
|
||
|
||
BAL_SHEET_ACCS = ["Assets", "Liabilities"] | ||
return is_account_type(RootAccountsContext.get("name_assets", "Assets"), string) | ||
|
||
|
||
def is_balance_sheet_account(string: str) -> bool: | ||
|
@@ -566,7 +599,13 @@ def is_balance_sheet_account(string: str) -> bool: | |
>>> is_balance_sheet_account("Income:US:BayBook:Match401k") | ||
False | ||
""" | ||
return any(is_account_type(acc_type, string) for acc_type in BAL_SHEET_ACCS) | ||
return any( | ||
is_account_type(acc_type, string) | ||
for acc_type in [ | ||
RootAccountsContext.get("name_assets", "Assets"), | ||
RootAccountsContext.get("name_liabilities", "Liabilities"), | ||
] | ||
) | ||
|
||
|
||
def get_balance_sheet_accounts(txn: Transaction) -> list[str]: | ||
|
@@ -845,7 +884,8 @@ def get_input(text: str) -> str: | |
----- | ||
Function included to facilitate mocking user input when testing. | ||
""" | ||
return input(text) | ||
print(text, file=sys.stderr, end=": ") | ||
return input() | ||
|
||
|
||
def response_is_valid_number(response: str, max_value: int) -> bool: | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could a simple test be added to verify the hook is working as intended?