Add duplicate detection, date range and dry run
Skip transactions that already exist in Firefly III, matched by date, description and amount. Add --start-date, --end-date and --dry-run, process transactions day by day, and rename --test-limit to --transactions-limit.
This commit is contained in:
1 parent
6920328ebc
commit
32040f33b9
2 files changed
+296
-102
No files matched your search
@@ -8,6 +8,8 @@ This tool helps you migrate your financial data from GnuCash to Firefly III auto
|
|||||||
- **Creates corresponding accounts in Firefly III** with proper hierarchical names and account types
|
- **Creates corresponding accounts in Firefly III** with proper hierarchical names and account types
|
||||||
- **Migrates transactions** between accounts with dates, amounts, and descriptions
|
- **Migrates transactions** between accounts with dates, amounts, and descriptions
|
||||||
- **Handles multiple currencies** by enabling them in Firefly III first
|
- **Handles multiple currencies** by enabling them in Firefly III first
|
||||||
|
- **Duplicate detection** - automatically skips transactions that already exist in Firefly III
|
||||||
|
- **Batch processing** - processes transactions day by day for better organization
|
||||||
- **Provides safety features** like test limits and accounts-only migration
|
- **Provides safety features** like test limits and accounts-only migration
|
||||||
|
|
||||||
## What gets migrated
|
## What gets migrated
|
||||||
@@ -23,6 +25,8 @@ This tool helps you migrate your financial data from GnuCash to Firefly III auto
|
|||||||
- Simple 2-split transactions with dates, amounts, descriptions
|
- Simple 2-split transactions with dates, amounts, descriptions
|
||||||
- Transaction memos/notes
|
- Transaction memos/notes
|
||||||
- Multi-currency support
|
- Multi-currency support
|
||||||
|
- **Duplicate detection** using date + description + amount matching
|
||||||
|
- **Batch processing** by date for efficient synchronization
|
||||||
- Complex split transactions are logged but skipped for manual review
|
- Complex split transactions are logged but skipped for manual review
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
@@ -90,13 +94,20 @@ python g2f.py \
|
|||||||
- `--gnucash-db` - Path to your GnuCash SQLite database file (required)
|
- `--gnucash-db` - Path to your GnuCash SQLite database file (required)
|
||||||
- `--firefly-url` - Your Firefly III base URL (required)
|
- `--firefly-url` - Your Firefly III base URL (required)
|
||||||
- `--firefly-token` - API token (optional if using FIREFLY_TOKEN environment variable)
|
- `--firefly-token` - API token (optional if using FIREFLY_TOKEN environment variable)
|
||||||
- `--test-limit` - Limit number of transactions for testing (optional)
|
- `--transactions-limit` - Limit number of transactions for testing (optional)
|
||||||
- `--accounts-only` - Only migrate accounts, skip transactions
|
- `--accounts-only` - Only migrate accounts, skip transactions
|
||||||
|
- `--start-date` - Start date for transaction migration (YYYY-MM-DD)
|
||||||
|
- `--end-date` - End date for transaction migration (YYYY-MM-DD)
|
||||||
|
- `--dry-run` - Perform a dry run without making any changes
|
||||||
|
|
||||||
## Safety Features
|
## Safety Features
|
||||||
|
|
||||||
- **Test limits**: Use `--test-limit` to migrate only a few transactions first
|
- **Test limits**: Use `--transactions-limit` to migrate only a few transactions first
|
||||||
- **Accounts-only mode**: Use `--accounts-only` to set up account structure first
|
- **Accounts-only mode**: Use `--accounts-only` to set up account structure first
|
||||||
|
- **Duplicate detection**: Automatically skips transactions that already exist
|
||||||
|
- **Date range filtering**: Use `--start-date` and `--end-date` to migrate specific time periods
|
||||||
|
- **Batch processing**: Transactions are processed day by day for better organization and logging
|
||||||
|
- **Dry run mode**: Use `--dry-run` to see what would be migrated without making changes
|
||||||
- **Detailed logging**: All actions are logged with timestamps
|
- **Detailed logging**: All actions are logged with timestamps
|
||||||
- **Error handling**: Failed operations are logged and don't stop the entire migration
|
- **Error handling**: Failed operations are logged and don't stop the entire migration
|
||||||
- **Hierarchical account names**: Full GnuCash account paths preserve your organization
|
- **Hierarchical account names**: Full GnuCash account paths preserve your organization
|
||||||
@@ -123,6 +134,28 @@ GnuCash's hierarchical account structure is preserved by using full account path
|
|||||||
|
|
||||||
This maintains your account organization while working within Firefly III's flat account structure.
|
This maintains your account organization while working within Firefly III's flat account structure.
|
||||||
|
|
||||||
|
## Duplicate Detection
|
||||||
|
|
||||||
|
The tool now includes intelligent duplicate detection to prevent importing the same transactions multiple times:
|
||||||
|
|
||||||
|
- **Detection method**: Transactions are identified as duplicates using a combination of date + description + amount
|
||||||
|
- **Automatic skipping**: Duplicate transactions are automatically skipped during migration
|
||||||
|
- **Batch processing**: Transactions are processed day by day, making it easy to resume migrations or add new data
|
||||||
|
- **Multiple identical transactions**: If you have multiple identical transactions on the same day, they are counted and handled appropriately
|
||||||
|
|
||||||
|
### Usage examples:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Basic migration with duplicate detection
|
||||||
|
python g2f.py --gnucash-db bank.gnucash --firefly-url http://localhost
|
||||||
|
|
||||||
|
# Import only transactions from a specific date range
|
||||||
|
python g2f.py --gnucash-db bank.gnucash --firefly-url http://localhost --start-date 2024-01-01 --end-date 2024-01-31
|
||||||
|
|
||||||
|
# Dry run to see what would be imported
|
||||||
|
python g2f.py --gnucash-db bank.gnucash --firefly-url http://localhost --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
## Important Notes
|
## Important Notes
|
||||||
|
|
||||||
- **Always backup your Firefly III data** before running a migration
|
- **Always backup your Firefly III data** before running a migration
|
||||||
|
|||||||
@@ -12,18 +12,19 @@ Author: Migration Script Generator
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from collections import defaultdict
|
||||||
|
from decimal import Decimal
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
import piecash
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
import piecash
|
|
||||||
|
|
||||||
# Configure logging
|
# Configure logging
|
||||||
logging.basicConfig(level=logging.INFO,
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s|%(levelname)s|%(message)s")
|
||||||
format="%(asctime)s|%(levelname)s|%(message)s")
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
ACCOUNT_TYPE_MAPPING = {
|
ACCOUNT_TYPE_MAPPING = {
|
||||||
@@ -78,18 +79,23 @@ class GnucashClient:
|
|||||||
logger.info(f"Found {len(accounts)} accounts in GnuCash")
|
logger.info(f"Found {len(accounts)} accounts in GnuCash")
|
||||||
return accounts
|
return accounts
|
||||||
|
|
||||||
def get_transactions(self, limit: int = 0) -> list:
|
def get_transactions(
|
||||||
|
self,
|
||||||
|
start_date: Optional[datetime.date] = None,
|
||||||
|
end_date: Optional[datetime.date] = None,
|
||||||
|
) -> list:
|
||||||
"""Get all transactions from the GnuCash book"""
|
"""Get all transactions from the GnuCash book"""
|
||||||
if not self.book:
|
if not self.book:
|
||||||
logger.error("Not connected to GnuCash database")
|
logger.error("Not connected to GnuCash database")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
# get all transactions, sorted by date
|
# get all transactions, sorted by date
|
||||||
all_transactions = sorted(self.book.transactions, key=lambda t: t.post_date)
|
all_transactions = [
|
||||||
|
txn
|
||||||
# apply limit if specified
|
for txn in self.book.transactions
|
||||||
if limit:
|
if (not start_date or txn.post_date.date() >= start_date)
|
||||||
all_transactions = all_transactions[:limit]
|
and (not end_date or txn.post_date.date() <= end_date)
|
||||||
|
]
|
||||||
|
|
||||||
logger.info(f"Found {len(all_transactions)} transactions in GnuCash")
|
logger.info(f"Found {len(all_transactions)} transactions in GnuCash")
|
||||||
return all_transactions
|
return all_transactions
|
||||||
@@ -108,14 +114,16 @@ class FireflyClient:
|
|||||||
def test_connection(self) -> bool:
|
def test_connection(self) -> bool:
|
||||||
"""Test connection to Firefly III API"""
|
"""Test connection to Firefly III API"""
|
||||||
try:
|
try:
|
||||||
response = requests.get(f"{self.base_url}/api/v1/about",
|
response = requests.get(
|
||||||
headers=self.headers)
|
f"{self.base_url}/api/v1/about", headers=self.headers
|
||||||
|
)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
logger.info("Successfully connected to Firefly III API")
|
logger.info("Successfully connected to Firefly III API")
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
logger.error(f"Failed to connect to Firefly III:"
|
logger.error(
|
||||||
f" {response.status_code}")
|
f"Failed to connect to Firefly III:" f" {response.status_code}"
|
||||||
|
)
|
||||||
return False
|
return False
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error connecting to Firefly III: {e}")
|
logger.error(f"Error connecting to Firefly III: {e}")
|
||||||
@@ -125,41 +133,45 @@ class FireflyClient:
|
|||||||
"""generic method to fetch all items from a paginated endpoint"""
|
"""generic method to fetch all items from a paginated endpoint"""
|
||||||
all_items = []
|
all_items = []
|
||||||
page = 1
|
page = 1
|
||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
response = requests.get(
|
response = requests.get(
|
||||||
f"{self.base_url}{endpoint}",
|
f"{self.base_url}{endpoint}",
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
params={"page": page, "limit": 50}
|
params={"page": page, "limit": 50},
|
||||||
)
|
)
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
logger.error(f"Failed to fetch {resource_name} page {page}:"
|
logger.error(
|
||||||
f" {response.status_code} - {response.text}")
|
f"Failed to fetch {resource_name} page {page}:"
|
||||||
|
f" {response.status_code} - {response.text}"
|
||||||
|
)
|
||||||
break
|
break
|
||||||
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
items_page = data["data"]
|
items_page = data["data"]
|
||||||
all_items.extend(items_page)
|
all_items.extend(items_page)
|
||||||
|
|
||||||
# check pagination info
|
# check pagination info
|
||||||
meta = data.get("meta", {})
|
meta = data.get("meta", {})
|
||||||
pagination = meta.get("pagination", {})
|
pagination = meta.get("pagination", {})
|
||||||
current_page = pagination.get("current_page", 1)
|
current_page = pagination.get("current_page", 1)
|
||||||
total_pages = pagination.get("total_pages", 1)
|
total_pages = pagination.get("total_pages", 1)
|
||||||
|
|
||||||
logger.debug(f"Fetched {resource_name} page {current_page} of {total_pages}"
|
logger.debug(
|
||||||
f" ({len(items_page)} items)")
|
f"Fetched {resource_name} page {current_page} of {total_pages}"
|
||||||
|
f" ({len(items_page)} items)"
|
||||||
|
)
|
||||||
|
|
||||||
if current_page >= total_pages:
|
if current_page >= total_pages:
|
||||||
break
|
break
|
||||||
|
|
||||||
page += 1
|
page += 1
|
||||||
|
|
||||||
logger.info(f"Found {len(all_items)} {resource_name} in Firefly III")
|
logger.info(f"Found {len(all_items)} {resource_name} in Firefly III")
|
||||||
return all_items
|
return all_items
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error fetching {resource_name}: {e}")
|
logger.error(f"Error fetching {resource_name}: {e}")
|
||||||
return all_items
|
return all_items
|
||||||
@@ -176,6 +188,20 @@ class FireflyClient:
|
|||||||
"""Get all piggy banks from Firefly III"""
|
"""Get all piggy banks from Firefly III"""
|
||||||
return self._paginated_get("/api/v1/piggy-banks", "piggy banks")
|
return self._paginated_get("/api/v1/piggy-banks", "piggy banks")
|
||||||
|
|
||||||
|
def get_transactions(self, start_date: str = None, end_date: str = None) -> list:
|
||||||
|
"""Get transactions from Firefly III with optional date filtering"""
|
||||||
|
# modify the _paginated_get to support query params for date filtering
|
||||||
|
endpoint = "/api/v1/transactions"
|
||||||
|
if start_date or end_date:
|
||||||
|
params = []
|
||||||
|
if start_date:
|
||||||
|
params.append(f"start={start_date}")
|
||||||
|
if end_date:
|
||||||
|
params.append(f"end={end_date}")
|
||||||
|
endpoint += "?" + "&".join(params)
|
||||||
|
|
||||||
|
return self._paginated_get(endpoint, "transactions")
|
||||||
|
|
||||||
def enable_currency(self, currency_code: str) -> bool:
|
def enable_currency(self, currency_code: str) -> bool:
|
||||||
"""enable an existing but disabled currency"""
|
"""enable an existing but disabled currency"""
|
||||||
if self.dry_run:
|
if self.dry_run:
|
||||||
@@ -274,8 +300,9 @@ class FireflyClient:
|
|||||||
def create_transaction(self, transaction_data: dict) -> bool:
|
def create_transaction(self, transaction_data: dict) -> bool:
|
||||||
"""Create a transaction in Firefly III"""
|
"""Create a transaction in Firefly III"""
|
||||||
if self.dry_run:
|
if self.dry_run:
|
||||||
logger.info(f"Dry run: would create transaction with data:"
|
logger.info(
|
||||||
f" {transaction_data}")
|
f"Dry run: would create transaction with data:" f" {transaction_data}"
|
||||||
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -286,9 +313,10 @@ class FireflyClient:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if response.status_code in [200, 201]:
|
if response.status_code in [200, 201]:
|
||||||
|
td_data = response.json()["data"]["attributes"]["transactions"][0]
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Created transaction:"
|
f"Created transaction:"
|
||||||
f" {transaction_data['transactions'][0]['description']}"
|
f" {td_data['date']} - {td_data['description']}"
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
@@ -309,7 +337,10 @@ class FireflyClient:
|
|||||||
f"Dry run: would create piggy bank {piggy_bank_data.get('name')}"
|
f"Dry run: would create piggy bank {piggy_bank_data.get('name')}"
|
||||||
f" with data: {piggy_bank_data}"
|
f" with data: {piggy_bank_data}"
|
||||||
)
|
)
|
||||||
return {"id": f"dry-run-piggy-{piggy_bank_data.get('name')}", "data": piggy_bank_data}
|
return {
|
||||||
|
"id": f"dry-run-piggy-{piggy_bank_data.get('name')}",
|
||||||
|
"data": piggy_bank_data,
|
||||||
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
@@ -343,6 +374,9 @@ class GnuCashToFireflyMigrator:
|
|||||||
self.firefly_client = firefly_client
|
self.firefly_client = firefly_client
|
||||||
self.accounts = {} # account full name -> Firefly III ID
|
self.accounts = {} # account full name -> Firefly III ID
|
||||||
self._currencies_cache = {} # currency_code -> firefly currency attributes
|
self._currencies_cache = {} # currency_code -> firefly currency attributes
|
||||||
|
self._existing_transactions = defaultdict(
|
||||||
|
list
|
||||||
|
) # (date, description, amount) -> [transaction IDs]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def currencies(self):
|
def currencies(self):
|
||||||
@@ -365,7 +399,9 @@ class GnuCashToFireflyMigrator:
|
|||||||
self._currencies_cache[code] = currency["attributes"]
|
self._currencies_cache[code] = currency["attributes"]
|
||||||
self._currencies_cache[code]["id"] = currency["id"]
|
self._currencies_cache[code]["id"] = currency["id"]
|
||||||
|
|
||||||
logger.info(f"Initialized {len(self._currencies_cache)} currencies in cache")
|
logger.info(
|
||||||
|
f"Initialized {len(self._currencies_cache)} currencies in cache"
|
||||||
|
)
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error initializing currencies: {e}")
|
logger.error(f"Error initializing currencies: {e}")
|
||||||
@@ -431,12 +467,14 @@ class GnuCashToFireflyMigrator:
|
|||||||
elif account.type in ["LOAN"] or "loan" in account.name.lower():
|
elif account.type in ["LOAN"] or "loan" in account.name.lower():
|
||||||
account_data["liability_type"] = "loan"
|
account_data["liability_type"] = "loan"
|
||||||
else:
|
else:
|
||||||
account_data["liability_type"] = "debt" # default for credit cards, etc.
|
account_data["liability_type"] = (
|
||||||
|
"debt" # default for credit cards, etc.
|
||||||
|
)
|
||||||
|
|
||||||
# liability_direction - required by API
|
# liability_direction - required by API
|
||||||
# "debit" means you owe the debt (most common case)
|
# "debit" means you owe the debt (most common case)
|
||||||
account_data["liability_direction"] = "debit"
|
account_data["liability_direction"] = "debit"
|
||||||
|
|
||||||
# interest - mandatory when type is liability, defaults to "0"
|
# interest - mandatory when type is liability, defaults to "0"
|
||||||
account_data["interest"] = "0"
|
account_data["interest"] = "0"
|
||||||
|
|
||||||
@@ -448,29 +486,62 @@ class GnuCashToFireflyMigrator:
|
|||||||
|
|
||||||
return self.firefly_client.create_account(account_data)
|
return self.firefly_client.create_account(account_data)
|
||||||
|
|
||||||
def create_firefly_piggy_bank(self, account: piecash.Account, parent_account_id: str) -> Optional[dict]:
|
def create_firefly_piggy_bank(
|
||||||
|
self, account: piecash.Account, parent_account_id: str
|
||||||
|
) -> Optional[dict]:
|
||||||
"""Create a piggy bank in Firefly III using piecash account object"""
|
"""Create a piggy bank in Firefly III using piecash account object"""
|
||||||
# Get currency code from parent account
|
# Get currency code from parent account
|
||||||
currency_code = account.commodity.mnemonic if account.commodity else "USD"
|
currency_code = account.commodity.mnemonic if account.commodity else "USD"
|
||||||
|
|
||||||
# Calculate current amount from account balance
|
# Calculate current amount from account balance
|
||||||
current_amount = abs(float(account.get_balance()))
|
current_amount = abs(account.get_balance())
|
||||||
|
|
||||||
piggy_bank_data = {
|
piggy_bank_data = {
|
||||||
"name": account.fullname, # Use short name, not fullname for piggy banks
|
"name": account.fullname, # Use short name, not fullname for piggy banks
|
||||||
"accounts": [{
|
"accounts": [
|
||||||
"account_id": parent_account_id,
|
{
|
||||||
}],
|
"account_id": parent_account_id,
|
||||||
|
}
|
||||||
|
],
|
||||||
"transaction_currency_code": currency_code,
|
"transaction_currency_code": currency_code,
|
||||||
"target_amount": current_amount * 2, # TODO fetch from the description
|
"target_amount": str(current_amount * 2), # TODO fetch from the description
|
||||||
"current_amount": current_amount,
|
"current_amount": str(current_amount),
|
||||||
}
|
}
|
||||||
|
|
||||||
if account.description:
|
if account.description:
|
||||||
piggy_bank_data["notes"] = account.description
|
piggy_bank_data["notes"] = account.description
|
||||||
|
|
||||||
return self.firefly_client.create_piggy_bank(piggy_bank_data)
|
return self.firefly_client.create_piggy_bank(piggy_bank_data)
|
||||||
|
|
||||||
|
def _build_transaction_key(self, date: str, description: str, amount: str) -> tuple:
|
||||||
|
"""build a key for duplicate detection: (date, description, amount)"""
|
||||||
|
# normalize description - strip whitespace and convert to lowercase
|
||||||
|
normalized_desc = (description or "").strip().lower()
|
||||||
|
normalized_amount = Decimal(amount).quantize(Decimal("0.01"))
|
||||||
|
return date, normalized_desc, normalized_amount
|
||||||
|
|
||||||
|
def load_existing_transactions(self, start_date: str = None, end_date: str = None):
|
||||||
|
"""load existing transactions from firefly to detect duplicates"""
|
||||||
|
logger.info("Loading existing transactions for duplicate detection...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
transactions = self.firefly_client.get_transactions(start_date, end_date)
|
||||||
|
|
||||||
|
for transaction in transactions:
|
||||||
|
# process each transaction split
|
||||||
|
for split in transaction["attributes"]["transactions"]:
|
||||||
|
key = self._build_transaction_key(
|
||||||
|
split["date"], split["description"], split["amount"]
|
||||||
|
)
|
||||||
|
self._existing_transactions[key].append(transaction["id"])
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Loaded {len(self._existing_transactions)} unique transaction patterns"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error loading existing transactions: {e}")
|
||||||
|
|
||||||
def match_existing_accounts(self):
|
def match_existing_accounts(self):
|
||||||
"""fetch existing firefly accounts and match with gnucash accounts"""
|
"""fetch existing firefly accounts and match with gnucash accounts"""
|
||||||
matched_count = 0
|
matched_count = 0
|
||||||
@@ -487,7 +558,7 @@ class GnuCashToFireflyMigrator:
|
|||||||
except KeyError:
|
except KeyError:
|
||||||
continue
|
continue
|
||||||
matched_count += 1
|
matched_count += 1
|
||||||
self.accounts[gc_acc.fullname] = ff_acc_data["id"]
|
self.accounts[gc_acc.fullname] = ff_acc_data
|
||||||
logger.debug(f"Pre-matched account: {gc_acc.fullname}")
|
logger.debug(f"Pre-matched account: {gc_acc.fullname}")
|
||||||
|
|
||||||
logger.debug(f"Pre-matched {matched_count} existing accounts")
|
logger.debug(f"Pre-matched {matched_count} existing accounts")
|
||||||
@@ -519,10 +590,10 @@ class GnuCashToFireflyMigrator:
|
|||||||
dest_split = None
|
dest_split = None
|
||||||
|
|
||||||
for split in splits:
|
for split in splits:
|
||||||
if float(split.value) < 0:
|
if split.is_credit:
|
||||||
source_split = split
|
source_split: piecash.Split = split
|
||||||
elif float(split.value) > 0:
|
elif split.is_debit:
|
||||||
dest_split = split
|
dest_split: piecash.Split = split
|
||||||
|
|
||||||
if not source_split or not dest_split:
|
if not source_split or not dest_split:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
@@ -531,29 +602,42 @@ class GnuCashToFireflyMigrator:
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
source_account_id = self.accounts.get(source_split.account.fullname)
|
src_account = self.accounts.get(source_split.account.fullname)
|
||||||
dest_account_id = self.accounts.get(dest_split.account.fullname)
|
dst_account = self.accounts.get(dest_split.account.fullname)
|
||||||
|
if not src_account or not dst_account:
|
||||||
if not source_account_id or not dest_account_id:
|
logger.warning(
|
||||||
logger.warning(f"Missing account mapping for transaction:"
|
f"Missing account mapping for transaction:"
|
||||||
f" {transaction.description}")
|
f" {transaction.description}"
|
||||||
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# get currency code
|
|
||||||
currency_code = transaction.currency.mnemonic if transaction.currency else "USD"
|
currency_code = transaction.currency.mnemonic if transaction.currency else "USD"
|
||||||
|
|
||||||
# format date
|
|
||||||
formatted_date = transaction.post_date.strftime("%Y-%m-%d")
|
formatted_date = transaction.post_date.strftime("%Y-%m-%d")
|
||||||
|
amount_str = str(abs(source_split.value))
|
||||||
|
|
||||||
|
# search for existing transactions
|
||||||
|
transaction_key = self._build_transaction_key(
|
||||||
|
formatted_date, transaction.description, amount_str
|
||||||
|
)
|
||||||
|
existing_txn_ids = self._existing_transactions.get(transaction_key, [])
|
||||||
|
if existing_txn_ids:
|
||||||
|
logger.info(
|
||||||
|
f"Skipping duplicate transaction on {formatted_date} for"
|
||||||
|
f" {transaction.description} ({amount_str}):"
|
||||||
|
f" already exists with IDs: {', '.join(existing_txn_ids)}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
transaction_data = {
|
transaction_data = {
|
||||||
"transactions": [
|
"transactions": [
|
||||||
{
|
{
|
||||||
"type": "transfer", # let Firefly determine the actual type
|
"type": "transfer", # let Firefly determine the actual type
|
||||||
"date": formatted_date,
|
"date": formatted_date,
|
||||||
"amount": str(abs(float(dest_split.value))),
|
"amount": amount_str,
|
||||||
"description": transaction.description or "Imported from GnuCash",
|
"description": transaction.description or "Imported from GnuCash",
|
||||||
"source_id": str(source_account_id),
|
"source_id": str(src_account["id"]),
|
||||||
"destination_id": str(dest_account_id),
|
"destination_id": str(dst_account["id"]),
|
||||||
"currency_code": currency_code,
|
"currency_code": currency_code,
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -568,7 +652,9 @@ class GnuCashToFireflyMigrator:
|
|||||||
if memos:
|
if memos:
|
||||||
transaction_data["transactions"][0]["notes"] = "; ".join(memos)
|
transaction_data["transactions"][0]["notes"] = "; ".join(memos)
|
||||||
|
|
||||||
return self.firefly_client.create_transaction(transaction_data)
|
result = self.firefly_client.create_transaction(transaction_data)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
def create_split_transaction(self, transaction: piecash.Transaction) -> bool:
|
def create_split_transaction(self, transaction: piecash.Transaction) -> bool:
|
||||||
"""Create a multi-split transaction (not fully implemented - needs complex handling)"""
|
"""Create a multi-split transaction (not fully implemented - needs complex handling)"""
|
||||||
@@ -590,8 +676,9 @@ class GnuCashToFireflyMigrator:
|
|||||||
if account.commodity:
|
if account.commodity:
|
||||||
# skip ignored currencies
|
# skip ignored currencies
|
||||||
if account.commodity.mnemonic in IGNORE_CURRENCIES:
|
if account.commodity.mnemonic in IGNORE_CURRENCIES:
|
||||||
logger.debug(f"Skipping ignored currency:"
|
logger.debug(
|
||||||
f" {account.commodity.mnemonic}")
|
f"Skipping ignored currency:" f" {account.commodity.mnemonic}"
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
# add to unique currencies set
|
# add to unique currencies set
|
||||||
unique_currencies.add(account.commodity.mnemonic)
|
unique_currencies.add(account.commodity.mnemonic)
|
||||||
@@ -615,24 +702,32 @@ class GnuCashToFireflyMigrator:
|
|||||||
continue
|
continue
|
||||||
# skip accounts with ignored currencies
|
# skip accounts with ignored currencies
|
||||||
if account.commodity and account.commodity.mnemonic in IGNORE_CURRENCIES:
|
if account.commodity and account.commodity.mnemonic in IGNORE_CURRENCIES:
|
||||||
logger.debug(f"Skipping account with ignored currency:"
|
logger.debug(
|
||||||
f" {account.fullname} ({account.commodity.mnemonic})")
|
f"Skipping account with ignored currency:"
|
||||||
|
f" {account.fullname} ({account.commodity.mnemonic})"
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# accounts with non-placeholder parents are piggy-banks
|
# accounts with non-placeholder parents are piggy-banks
|
||||||
if (account.parent
|
if (
|
||||||
and account.parent.type != "ROOT"
|
account.parent
|
||||||
and not account.parent.placeholder):
|
and account.parent.type != "ROOT"
|
||||||
|
and not account.parent.placeholder
|
||||||
|
):
|
||||||
logger.debug(f"Found piggy-bank account: {account.fullname}")
|
logger.debug(f"Found piggy-bank account: {account.fullname}")
|
||||||
|
|
||||||
# Get parent account ID from mapping
|
# Get parent account ID from mapping
|
||||||
parent_account_id = self.accounts.get(account.parent.fullname)
|
parent_account_id = self.accounts.get(account.parent.fullname)
|
||||||
if parent_account_id:
|
if parent_account_id:
|
||||||
firefly_piggy_bank = self.create_firefly_piggy_bank(account, parent_account_id)
|
firefly_piggy_bank = self.create_firefly_piggy_bank(
|
||||||
|
account, parent_account_id
|
||||||
|
)
|
||||||
if firefly_piggy_bank:
|
if firefly_piggy_bank:
|
||||||
piggy_bank_count += 1
|
piggy_bank_count += 1
|
||||||
else:
|
else:
|
||||||
logger.warning(f"Parent account not found for piggy bank: {account.fullname}")
|
logger.warning(
|
||||||
|
f"Parent account not found for piggy bank: {account.fullname}"
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# no existing match, create new account
|
# no existing match, create new account
|
||||||
@@ -641,27 +736,71 @@ class GnuCashToFireflyMigrator:
|
|||||||
self.accounts[account.fullname] = firefly_account["id"]
|
self.accounts[account.fullname] = firefly_account["id"]
|
||||||
created_count += 1
|
created_count += 1
|
||||||
|
|
||||||
logger.info(f"Account migration completed:"
|
logger.info(
|
||||||
f" {matched_count} matched,"
|
f"Account migration completed:"
|
||||||
f" {created_count} created,"
|
f" {matched_count} matched,"
|
||||||
f" {piggy_bank_count} piggy banks created")
|
f" {created_count} created,"
|
||||||
|
f" {piggy_bank_count} piggy banks created"
|
||||||
|
)
|
||||||
return matched_count + created_count + piggy_bank_count
|
return matched_count + created_count + piggy_bank_count
|
||||||
|
|
||||||
def migrate_transactions(self, limit: int = 0) -> int:
|
def migrate_transactions(
|
||||||
|
self,
|
||||||
|
start_date: Optional[datetime.date] = None,
|
||||||
|
end_date: Optional[datetime.date] = None,
|
||||||
|
) -> int:
|
||||||
"""Migrate transactions from GnuCash to Firefly III"""
|
"""Migrate transactions from GnuCash to Firefly III"""
|
||||||
logger.info("Starting transaction migration...")
|
logger.info("Starting transaction migration...")
|
||||||
|
|
||||||
transactions = self.gnucash_client.get_transactions(limit)
|
# load existing transactions for duplicate detection
|
||||||
|
self.load_existing_transactions(start_date, end_date)
|
||||||
|
|
||||||
|
gc_transactions = self.gnucash_client.get_transactions(start_date, end_date)
|
||||||
|
|
||||||
|
# group transactions by date for batch processing
|
||||||
|
gc_transactions_by_date = defaultdict(list)
|
||||||
|
for txn in gc_transactions:
|
||||||
|
txn_date = txn.post_date.strftime("%Y-%m-%d")
|
||||||
|
gc_transactions_by_date[txn_date].append(txn)
|
||||||
|
|
||||||
success_count = 0
|
success_count = 0
|
||||||
for transaction in transactions:
|
skipped_count = 0
|
||||||
if self.create_firefly_transaction(transaction):
|
total_days = len(gc_transactions_by_date)
|
||||||
success_count += 1
|
|
||||||
|
|
||||||
logger.info(f"Successfully created {success_count} out of {len(transactions)} transactions")
|
for day_num, date in enumerate(sorted(gc_transactions_by_date.keys()), 1):
|
||||||
|
gc_day_transactions = gc_transactions_by_date[date]
|
||||||
|
logger.info(
|
||||||
|
f"Processing day {day_num}/{total_days}: {date} "
|
||||||
|
f"({len(gc_day_transactions)} transactions)"
|
||||||
|
)
|
||||||
|
|
||||||
|
day_success = 0
|
||||||
|
for transaction in gc_day_transactions:
|
||||||
|
result = self.create_firefly_transaction(transaction)
|
||||||
|
if result:
|
||||||
|
day_success += 1
|
||||||
|
success_count += 1
|
||||||
|
else:
|
||||||
|
skipped_count += 1
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Day {date}: {day_success} created, "
|
||||||
|
f"{len(gc_day_transactions) - day_success} skipped/failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Transaction migration completed: {success_count} created, "
|
||||||
|
f"{skipped_count} skipped as duplicates, "
|
||||||
|
f"{len(gc_transactions) - success_count - skipped_count} failed"
|
||||||
|
)
|
||||||
return success_count
|
return success_count
|
||||||
|
|
||||||
def run_migration(self, transactions_limit: int = 0, accounts_only=False) -> bool:
|
def run_migration(
|
||||||
|
self,
|
||||||
|
start_date: Optional[datetime.date] = None,
|
||||||
|
end_date: Optional[datetime.date] = None,
|
||||||
|
accounts_only: bool = False,
|
||||||
|
) -> bool:
|
||||||
"""Run migration process"""
|
"""Run migration process"""
|
||||||
logger.info("Starting GnuCash to Firefly III migration...")
|
logger.info("Starting GnuCash to Firefly III migration...")
|
||||||
|
|
||||||
@@ -675,8 +814,9 @@ class GnuCashToFireflyMigrator:
|
|||||||
|
|
||||||
# initialize currencies cache
|
# initialize currencies cache
|
||||||
if not self.load_currencies():
|
if not self.load_currencies():
|
||||||
logger.warning("Failed to initialize currencies cache,"
|
logger.warning(
|
||||||
" will fetch individually")
|
"Failed to initialize currencies cache, will fetch individually"
|
||||||
|
)
|
||||||
|
|
||||||
# handle accounts
|
# handle accounts
|
||||||
if not self.migrate_accounts():
|
if not self.migrate_accounts():
|
||||||
@@ -688,7 +828,7 @@ class GnuCashToFireflyMigrator:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
# handle transactions (unless accounts-only)
|
# handle transactions (unless accounts-only)
|
||||||
transaction_count = self.migrate_transactions(transactions_limit)
|
transaction_count = self.migrate_transactions(start_date, end_date)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Migration completed! Migrated {len(self.accounts)}"
|
f"Migration completed! Migrated {len(self.accounts)}"
|
||||||
f" accounts and {transaction_count} transactions"
|
f" accounts and {transaction_count} transactions"
|
||||||
@@ -696,21 +836,28 @@ class GnuCashToFireflyMigrator:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def validate_date(date_string):
|
||||||
|
try:
|
||||||
|
return datetime.datetime.strptime(date_string, "%Y-%m-%d").date()
|
||||||
|
except ValueError:
|
||||||
|
raise argparse.ArgumentTypeError(
|
||||||
|
f"Invalid date format: {date_string}. Expected YYYY-MM-DD"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="Migrate data from GnuCash to Firefly III")
|
parser = argparse.ArgumentParser(
|
||||||
parser.add_argument("--gnucash-db", required=True, help="Path to GnuCash SQLite database file")
|
description="Migrate data from GnuCash to Firefly III"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--gnucash-db", required=True, help="Path to GnuCash SQLite database file"
|
||||||
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--firefly-url",
|
"--firefly-url",
|
||||||
required=True,
|
required=True,
|
||||||
help="Firefly III base URL (e.g., http://localhost)",
|
help="Firefly III base URL (e.g., http://localhost)",
|
||||||
)
|
)
|
||||||
parser.add_argument("--firefly-token", help="Firefly III API access token")
|
parser.add_argument("--firefly-token", help="Firefly III API access token")
|
||||||
parser.add_argument(
|
|
||||||
"--transactions-limit",
|
|
||||||
type=int,
|
|
||||||
help="Limit number of transactions to migrate (0 for all)",
|
|
||||||
default=0,
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--accounts-only",
|
"--accounts-only",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -721,6 +868,16 @@ def main():
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="Perform a dry run without making any changes",
|
help="Perform a dry run without making any changes",
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--start-date",
|
||||||
|
type=validate_date,
|
||||||
|
help="Start date for transaction migration (YYYY-MM-DD)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--end-date",
|
||||||
|
type=validate_date,
|
||||||
|
help="End date for transaction migration (YYYY-MM-DD)",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@@ -736,13 +893,17 @@ def main():
|
|||||||
|
|
||||||
# create client instances
|
# create client instances
|
||||||
gnucash_client = GnucashClient(args.gnucash_db)
|
gnucash_client = GnucashClient(args.gnucash_db)
|
||||||
firefly_client = FireflyClient(args.firefly_url,
|
firefly_client = FireflyClient(
|
||||||
firefly_token,
|
args.firefly_url, firefly_token, dry_run=args.dry_run
|
||||||
dry_run=args.dry_run)
|
)
|
||||||
|
|
||||||
migrator = GnuCashToFireflyMigrator(gnucash_client, firefly_client)
|
migrator = GnuCashToFireflyMigrator(gnucash_client, firefly_client)
|
||||||
|
|
||||||
success = migrator.run_migration(args.transactions_limit, args.accounts_only)
|
success = migrator.run_migration(
|
||||||
|
start_date=args.start_date,
|
||||||
|
end_date=args.end_date,
|
||||||
|
accounts_only=args.accounts_only,
|
||||||
|
)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
logger.info("Migration completed successfully!")
|
logger.info("Migration completed successfully!")
|
||||||
|
|||||||
Reference in new issue
Block a user