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:
snegov committed 2026-11-18 20:03:17 -07:00
1 parent 6920328ebc
commit 32040f33b9
2 files changed
+296 -102

No files matched your search

+35 -2
View File
@@ -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
- **Migrates transactions** between accounts with dates, amounts, and descriptions
- **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
## 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
- Transaction memos/notes
- 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
## Requirements
@@ -90,13 +94,20 @@ python g2f.py \
- `--gnucash-db` - Path to your GnuCash SQLite database file (required)
- `--firefly-url` - Your Firefly III base URL (required)
- `--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
- `--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
- **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
- **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
- **Error handling**: Failed operations are logged and don't stop the entire migration
- **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.
## 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
- **Always backup your Firefly III data** before running a migration
+261 -100
View File
@@ -12,18 +12,19 @@ Author: Migration Script Generator
"""
import argparse
import datetime
import logging
import os
import sys
from collections import defaultdict
from decimal import Decimal
from typing import Optional
import piecash
import requests
import piecash
# Configure logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s|%(levelname)s|%(message)s")
logging.basicConfig(level=logging.INFO, format="%(asctime)s|%(levelname)s|%(message)s")
logger = logging.getLogger(__name__)
ACCOUNT_TYPE_MAPPING = {
@@ -78,18 +79,23 @@ class GnucashClient:
logger.info(f"Found {len(accounts)} accounts in GnuCash")
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"""
if not self.book:
logger.error("Not connected to GnuCash database")
return []
# get all transactions, sorted by date
all_transactions = sorted(self.book.transactions, key=lambda t: t.post_date)
# apply limit if specified
if limit:
all_transactions = all_transactions[:limit]
all_transactions = [
txn
for txn in self.book.transactions
if (not start_date or txn.post_date.date() >= start_date)
and (not end_date or txn.post_date.date() <= end_date)
]
logger.info(f"Found {len(all_transactions)} transactions in GnuCash")
return all_transactions
@@ -108,14 +114,16 @@ class FireflyClient:
def test_connection(self) -> bool:
"""Test connection to Firefly III API"""
try:
response = requests.get(f"{self.base_url}/api/v1/about",
headers=self.headers)
response = requests.get(
f"{self.base_url}/api/v1/about", headers=self.headers
)
if response.status_code == 200:
logger.info("Successfully connected to Firefly III API")
return True
else:
logger.error(f"Failed to connect to Firefly III:"
f" {response.status_code}")
logger.error(
f"Failed to connect to Firefly III:" f" {response.status_code}"
)
return False
except Exception as 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"""
all_items = []
page = 1
try:
while True:
response = requests.get(
f"{self.base_url}{endpoint}",
headers=self.headers,
params={"page": page, "limit": 50}
params={"page": page, "limit": 50},
)
if response.status_code != 200:
logger.error(f"Failed to fetch {resource_name} page {page}:"
f" {response.status_code} - {response.text}")
logger.error(
f"Failed to fetch {resource_name} page {page}:"
f" {response.status_code} - {response.text}"
)
break
data = response.json()
items_page = data["data"]
all_items.extend(items_page)
# check pagination info
meta = data.get("meta", {})
pagination = meta.get("pagination", {})
current_page = pagination.get("current_page", 1)
total_pages = pagination.get("total_pages", 1)
logger.debug(f"Fetched {resource_name} page {current_page} of {total_pages}"
f" ({len(items_page)} items)")
logger.debug(
f"Fetched {resource_name} page {current_page} of {total_pages}"
f" ({len(items_page)} items)"
)
if current_page >= total_pages:
break
page += 1
logger.info(f"Found {len(all_items)} {resource_name} in Firefly III")
return all_items
except Exception as e:
logger.error(f"Error fetching {resource_name}: {e}")
return all_items
@@ -176,6 +188,20 @@ class FireflyClient:
"""Get all piggy banks from Firefly III"""
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:
"""enable an existing but disabled currency"""
if self.dry_run:
@@ -274,8 +300,9 @@ class FireflyClient:
def create_transaction(self, transaction_data: dict) -> bool:
"""Create a transaction in Firefly III"""
if self.dry_run:
logger.info(f"Dry run: would create transaction with data:"
f" {transaction_data}")
logger.info(
f"Dry run: would create transaction with data:" f" {transaction_data}"
)
return True
try:
@@ -286,9 +313,10 @@ class FireflyClient:
)
if response.status_code in [200, 201]:
td_data = response.json()["data"]["attributes"]["transactions"][0]
logger.info(
f"Created transaction:"
f" {transaction_data['transactions'][0]['description']}"
f" {td_data['date']} - {td_data['description']}"
)
return True
else:
@@ -309,7 +337,10 @@ class FireflyClient:
f"Dry run: would create piggy bank {piggy_bank_data.get('name')}"
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:
response = requests.post(
@@ -343,6 +374,9 @@ class GnuCashToFireflyMigrator:
self.firefly_client = firefly_client
self.accounts = {} # account full name -> Firefly III ID
self._currencies_cache = {} # currency_code -> firefly currency attributes
self._existing_transactions = defaultdict(
list
) # (date, description, amount) -> [transaction IDs]
@property
def currencies(self):
@@ -365,7 +399,9 @@ class GnuCashToFireflyMigrator:
self._currencies_cache[code] = currency["attributes"]
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
except Exception as 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():
account_data["liability_type"] = "loan"
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
# "debit" means you owe the debt (most common case)
account_data["liability_direction"] = "debit"
# interest - mandatory when type is liability, defaults to "0"
account_data["interest"] = "0"
@@ -448,29 +486,62 @@ class GnuCashToFireflyMigrator:
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"""
# Get currency code from parent account
currency_code = account.commodity.mnemonic if account.commodity else "USD"
# Calculate current amount from account balance
current_amount = abs(float(account.get_balance()))
current_amount = abs(account.get_balance())
piggy_bank_data = {
"name": account.fullname, # Use short name, not fullname for piggy banks
"accounts": [{
"account_id": parent_account_id,
}],
"accounts": [
{
"account_id": parent_account_id,
}
],
"transaction_currency_code": currency_code,
"target_amount": current_amount * 2, # TODO fetch from the description
"current_amount": current_amount,
"target_amount": str(current_amount * 2), # TODO fetch from the description
"current_amount": str(current_amount),
}
if account.description:
piggy_bank_data["notes"] = account.description
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):
"""fetch existing firefly accounts and match with gnucash accounts"""
matched_count = 0
@@ -487,7 +558,7 @@ class GnuCashToFireflyMigrator:
except KeyError:
continue
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 {matched_count} existing accounts")
@@ -519,10 +590,10 @@ class GnuCashToFireflyMigrator:
dest_split = None
for split in splits:
if float(split.value) < 0:
source_split = split
elif float(split.value) > 0:
dest_split = split
if split.is_credit:
source_split: piecash.Split = split
elif split.is_debit:
dest_split: piecash.Split = split
if not source_split or not dest_split:
logger.warning(
@@ -531,29 +602,42 @@ class GnuCashToFireflyMigrator:
)
return False
source_account_id = self.accounts.get(source_split.account.fullname)
dest_account_id = self.accounts.get(dest_split.account.fullname)
if not source_account_id or not dest_account_id:
logger.warning(f"Missing account mapping for transaction:"
f" {transaction.description}")
src_account = self.accounts.get(source_split.account.fullname)
dst_account = self.accounts.get(dest_split.account.fullname)
if not src_account or not dst_account:
logger.warning(
f"Missing account mapping for transaction:"
f" {transaction.description}"
)
return False
# get currency code
currency_code = transaction.currency.mnemonic if transaction.currency else "USD"
# format date
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 = {
"transactions": [
{
"type": "transfer", # let Firefly determine the actual type
"date": formatted_date,
"amount": str(abs(float(dest_split.value))),
"amount": amount_str,
"description": transaction.description or "Imported from GnuCash",
"source_id": str(source_account_id),
"destination_id": str(dest_account_id),
"source_id": str(src_account["id"]),
"destination_id": str(dst_account["id"]),
"currency_code": currency_code,
}
]
@@ -568,7 +652,9 @@ class GnuCashToFireflyMigrator:
if 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:
"""Create a multi-split transaction (not fully implemented - needs complex handling)"""
@@ -590,8 +676,9 @@ class GnuCashToFireflyMigrator:
if account.commodity:
# skip ignored currencies
if account.commodity.mnemonic in IGNORE_CURRENCIES:
logger.debug(f"Skipping ignored currency:"
f" {account.commodity.mnemonic}")
logger.debug(
f"Skipping ignored currency:" f" {account.commodity.mnemonic}"
)
continue
# add to unique currencies set
unique_currencies.add(account.commodity.mnemonic)
@@ -615,24 +702,32 @@ class GnuCashToFireflyMigrator:
continue
# skip accounts with ignored currencies
if account.commodity and account.commodity.mnemonic in IGNORE_CURRENCIES:
logger.debug(f"Skipping account with ignored currency:"
f" {account.fullname} ({account.commodity.mnemonic})")
logger.debug(
f"Skipping account with ignored currency:"
f" {account.fullname} ({account.commodity.mnemonic})"
)
continue
# accounts with non-placeholder parents are piggy-banks
if (account.parent
and account.parent.type != "ROOT"
and not account.parent.placeholder):
if (
account.parent
and account.parent.type != "ROOT"
and not account.parent.placeholder
):
logger.debug(f"Found piggy-bank account: {account.fullname}")
# Get parent account ID from mapping
parent_account_id = self.accounts.get(account.parent.fullname)
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:
piggy_bank_count += 1
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
# no existing match, create new account
@@ -641,27 +736,71 @@ class GnuCashToFireflyMigrator:
self.accounts[account.fullname] = firefly_account["id"]
created_count += 1
logger.info(f"Account migration completed:"
f" {matched_count} matched,"
f" {created_count} created,"
f" {piggy_bank_count} piggy banks created")
logger.info(
f"Account migration completed:"
f" {matched_count} matched,"
f" {created_count} created,"
f" {piggy_bank_count} piggy banks created"
)
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"""
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
for transaction in transactions:
if self.create_firefly_transaction(transaction):
success_count += 1
skipped_count = 0
total_days = len(gc_transactions_by_date)
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
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"""
logger.info("Starting GnuCash to Firefly III migration...")
@@ -675,8 +814,9 @@ class GnuCashToFireflyMigrator:
# initialize currencies cache
if not self.load_currencies():
logger.warning("Failed to initialize currencies cache,"
" will fetch individually")
logger.warning(
"Failed to initialize currencies cache, will fetch individually"
)
# handle accounts
if not self.migrate_accounts():
@@ -688,7 +828,7 @@ class GnuCashToFireflyMigrator:
return True
# handle transactions (unless accounts-only)
transaction_count = self.migrate_transactions(transactions_limit)
transaction_count = self.migrate_transactions(start_date, end_date)
logger.info(
f"Migration completed! Migrated {len(self.accounts)}"
f" accounts and {transaction_count} transactions"
@@ -696,21 +836,28 @@ class GnuCashToFireflyMigrator:
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():
parser = argparse.ArgumentParser(description="Migrate data from GnuCash to Firefly III")
parser.add_argument("--gnucash-db", required=True, help="Path to GnuCash SQLite database file")
parser = argparse.ArgumentParser(
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(
"--firefly-url",
required=True,
help="Firefly III base URL (e.g., http://localhost)",
)
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(
"--accounts-only",
action="store_true",
@@ -721,6 +868,16 @@ def main():
action="store_true",
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()
@@ -736,13 +893,17 @@ def main():
# create client instances
gnucash_client = GnucashClient(args.gnucash_db)
firefly_client = FireflyClient(args.firefly_url,
firefly_token,
dry_run=args.dry_run)
firefly_client = FireflyClient(
args.firefly_url, firefly_token, dry_run=args.dry_run
)
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:
logger.info("Migration completed successfully!")