#!/usr/bin/env python # An example that show how to use the python-gnucash bindings to make a # simple vendor report. # Copyright (C) 2007 ParIT Worker Co-operative # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA # # Authors: Mark Jenkins # You need to start this with a suitable envionment for loading the gnucash # libraries. Run as # $ gnucash-env python example_AP_report.py # # instead of # $ python example_AP_report.py from gnucash import Session, GncNumeric import sys AP_ACCOUNT_NAME = "A/P" VENDOR_NAME = "Electric Company" ZERO = GncNumeric('0') NEG_ONE = GncNumeric('-1') def gnc_sum( iterable, start=ZERO ): """Like the built-in sum, but it uses a GncNumeric 0 as the default start value """ return sum( iterable, start ) def extract_AP_parts_of_transaction( transaction ): """Go through a transaction, if the transaction involves the Vendor VENDOR_NAME, return the sum of any splits that apply to the AP account. Otherwise return GncNumeric 0 """ if transaction.description == VENDOR_NAME: return gnc_sum( split.value for split in transaction.get_splits() if split.account.name == AP_ACCOUNT_NAME ) else: return ZERO session = Session("example_books.xac") try: AP = session.book.account_group.account_from_path( ("Liabilities", AP_ACCOUNT_NAME) ) # Calculate the balance by going through every transaction and summing # the splits against the AP account that associated with VENDOR_NAME balance = gnc_sum( extract_AP_parts_of_transaction(transaction) for transaction in AP.get_transactions() ) # negate the balance because we want to view liability balances as # positive values balance *= NEG_ONE print "Your balance with %s is $%s" % ( VENDOR_NAME, balance ) except Exception, (error): print sys.exc_info() # even if there is an error we want to still try to close the session to # get rid of any lock files session.end()