fix(import): leave QIF headers out of the hash and skip non-transaction sections

The !Type header line was buffered into the first transaction's raw
lines, so a transaction hashed differently depending on whether it
opened the export. An overlapping export with a different first
transaction imported it twice. Header lines are now left out of the
internal ID. The previous-hash check still hashes the full lines,
headers included, and runs on the first appearance of each of those,
so a first transaction and an identical later one imported before
this change are both still recognized.

Account blocks (!Account and !Option:AutoSwitch account lists) and
non-transaction sections (!Type:Cat, !Type:Class, !Type:Memorized and
any type not in QIF_TRANSACTION_SECTIONS) were read with the
transaction codes, where T is an account's type and D a description,
so files containing them failed to import. They are now skipped, and
each skipped section is logged.
This commit is contained in:
Herculino Trotta committed 2026-11-14 12:16:15 -03:00
1 parent 70be7b3161
commit d763d0ffb8
2 files changed
+163 -5

No files matched your search

+49 -5
View File
@@ -41,6 +41,17 @@ from apps.import_app.schemas.v1 import (
logger = logging.getLogger(__name__)
# QIF sections that hold transactions. Others, like category lists (!Type:Cat)
# or memorized transactions (!Type:Memorized), are skipped
QIF_TRANSACTION_SECTIONS = {
"!type:bank",
"!type:cash",
"!type:ccard",
"!type:invst",
"!type:oth a",
"!type:oth l",
}
class ImportService:
def __init__(self, import_run: ImportRun):
@@ -992,6 +1003,10 @@ class ImportService:
raw_lines_buffer = []
# How many times each transaction's raw lines have been seen in this file
occurrences = Counter()
legacy_contents_seen = set()
in_account_list = False
in_account_block = False
in_other_section = False
account = (
self.import_run.account or Account.objects.filter(name=account_name).first()
@@ -1006,12 +1021,39 @@ class ImportService:
if not line:
continue
# Account blocks (!Account, or an !Option:AutoSwitch account list)
# and non-transaction sections use codes that mean something else
# in a transaction, e.g. T is an account's type and D its description
header = line.lower()
if header == "!option:autoswitch":
in_account_list = True
elif header == "!clear:autoswitch":
in_account_list = False
elif header == "!account":
in_account_block = True
elif header.startswith("!type:"):
in_other_section = header not in QIF_TRANSACTION_SECTIONS
if in_other_section:
self._log("info", f"Skipped {line} section in {filename}")
if in_account_list or in_account_block or in_other_section:
if line == "^":
in_account_block = False
raw_lines_buffer = []
continue
raw_lines_buffer.append(line)
if line == "^":
if current_transaction:
# Deduplication using hash of raw lines
raw_content = "".join(raw_lines_buffer)
# Deduplication using hash of raw lines. Header lines (!Type,
# !Account) are left out so a transaction hashes the same
# whether or not it comes right after one
legacy_content = "".join(raw_lines_buffer)
raw_content = "".join(
raw_line
for raw_line in raw_lines_buffer
if not raw_line.startswith("!")
)
occurrence = occurrences[raw_content]
occurrences[raw_content] += 1
internal_id = self._qif_internal_id(
@@ -1022,13 +1064,15 @@ class ImportService:
raw_lines_buffer = []
duplicate_filter = Q(internal_id=internal_id)
if occurrence == 0:
if legacy_content not in legacy_contents_seen:
# Transactions imported before the account and the
# occurrence were part of the hash used the raw lines
# alone, and only ever kept the first of identical ones
# alone, headers included, and only ever kept the first
# of identical ones
legacy_contents_seen.add(legacy_content)
duplicate_filter |= Q(
internal_id=hashlib.sha256(
raw_content.encode("utf-8")
legacy_content.encode("utf-8")
).hexdigest(),
account=account,
)
@@ -375,6 +375,120 @@ mapping: {}
self.assertEqual(into_savings.skipped_rows, 0)
self.assertEqual(Transaction.objects.filter(account=savings).count(), 3)
def test_import_overlapping_exports_with_a_different_first_transaction(self):
# The first coffee opens the second export, right after the header
later_export = """!Type:Bank
D05/01/2015
T-4.50
PCoffee Shop
^
D06/01/2015
T-20.00
PMarket
^
"""
self._import_qif(IDENTICAL_TRANSACTIONS_CONTENT)
run = self._import_qif(later_export)
self.assertEqual(run.successful_rows, 1)
self.assertEqual(run.skipped_rows, 1)
self.assertEqual(Transaction.objects.count(), 4)
def test_import_skips_previous_hash_of_a_first_transaction_repeated_later(self):
# The previous hash included the header in the first transaction, so a
# first transaction and an identical later one were both imported
content = """!Type:Bank
D05/01/2015
T-4.50
PCoffee Shop
^
D05/01/2015
T-4.50
PCoffee Shop
^
"""
for raw_content in (
"!Type:BankD05/01/2015T-4.50PCoffee Shop^",
"D05/01/2015T-4.50PCoffee Shop^",
):
Transaction.objects.create(
account=self.account,
type=Transaction.Type.EXPENSE,
date=date(2015, 1, 5),
amount=Decimal("4.50"),
internal_id=hashlib.sha256(raw_content.encode("utf-8")).hexdigest(),
)
run = self._import_qif(content)
self.assertEqual(run.successful_rows, 0)
self.assertEqual(run.skipped_rows, 2)
self.assertEqual(Transaction.objects.count(), 2)
def test_import_skips_account_blocks(self):
# Quicken-style export: an account list, then an account block before
# the transactions. T and D mean the account type and description there
content = """!Option:AutoSwitch
!Account
NChecking
TBank
DMain checking account
^
NSavings
TBank
^
!Clear:AutoSwitch
!Account
NChecking
TBank
DMain checking account
^
!Type:Bank
D04/01/2015
T100.00
PSalary
^
"""
run = self._import_qif(content)
self.assertEqual(run.status, ImportRun.Status.FINISHED)
self.assertEqual(run.successful_rows, 1)
self.assertEqual(run.failed_rows, 0)
transaction = Transaction.objects.get()
self.assertEqual(transaction.amount, Decimal("100.00"))
self.assertEqual(transaction.date, date(2015, 1, 4))
def test_import_skips_non_transaction_sections(self):
# Category and class lists, and memorized transactions (templates, not
# real transactions), around a section of real ones
content = """!Type:Cat
NFood
DGroceries and restaurants
E
^
!Type:Class
NPersonal
DPersonal expenses
^
!Type:Bank
D04/01/2015
T100.00
PSalary
^
!Type:Memorized
KC
T-50.00
PRent
^
"""
run = self._import_qif(content)
self.assertEqual(run.status, ImportRun.Status.FINISHED)
self.assertEqual(run.successful_rows, 1)
self.assertEqual(run.failed_rows, 0)
self.assertEqual(Transaction.objects.get().amount, Decimal("100.00"))
@override_settings(ENABLE_SOFT_DELETE=True)
def test_import_skips_soft_deleted_transactions(self):
content = """!Type:Bank