# DrCr: Web-based double-entry bookkeeping framework # Copyright (C) 2022–2024 Lee Yingtong Li (RunasSudo) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from .database import db from .models import Transaction from .plugins import transaction_providers from .statements.models import StatementLine def limit_query_dt(query, field, start_date=None, end_date=None): """Helper function to limit the query between the start and end dates""" if start_date and end_date: return query.where((field >= start_date) & (field <= end_date)) if start_date: return query.where(field >= start_date) if end_date: return query.where(field <= end_date) return query def all_transactions(start_date=None, end_date=None, api_stage_until=None, join_postings=True): """Return all transactions, including from DB and API""" transactions = db_transactions(start_date=start_date, end_date=end_date, join_postings=join_postings) transactions.extend(api_transactions(start_date=start_date, end_date=end_date, api_stage_until=api_stage_until)) return transactions def db_transactions(start_date=None, end_date=None, join_postings=True): """Return only transactions from DB""" # All Transactions in database between start_date and end_date query = db.select(Transaction) query = limit_query_dt(query, Transaction.dt, start_date, end_date) if join_postings: query = query.options(db.selectinload(Transaction.postings)) transactions = db.session.scalars(query).all() return transactions def api_transactions(start_date=None, end_date=None, api_stage_until=None): """Return only transactions from API""" # Stage 0: DB transactions # Stage 100: Ordinary transactions # Stage 200: Closing entries prior to tax # Stage 300: Tax entries # Stage 400: Closing entries after tax transactions = [] # Unreconciled StatementLines query = db.select(StatementLine).where(StatementLine.reconciliation == None) query = limit_query_dt(query, StatementLine.dt, start_date, end_date) transactions.extend(line.into_transaction() for line in db.session.scalars(query).all()) # Plugins for transaction_provider in transaction_providers: transactions = transaction_provider(transactions, start_date=start_date, end_date=end_date, api_stage_until=api_stage_until) return transactions