"""Transaction deduplication rules. Determines whether two transaction records likely represent the same underlying financial event captured from different screenshots / pages. """ from datetime import timedelta from app.models.transaction import TransactionRecord TIME_WINDOW = timedelta(minutes=5) def is_duplicate_pair(a: TransactionRecord, b: TransactionRecord) -> bool: # Rule 1: exact order_no match if a.order_no and b.order_no and a.order_no == b.order_no: return True # Rule 2: same amount + close time + same account tail if ( float(a.amount) == float(b.amount) and a.trade_time and b.trade_time and abs(a.trade_time - b.trade_time) <= TIME_WINDOW ): if a.self_account_tail_no and b.self_account_tail_no: if a.self_account_tail_no == b.self_account_tail_no: return True # same counterparty and close time is also strong signal if a.counterparty_name and a.counterparty_name == b.counterparty_name: return True return False