9b25718
# gnucash_core.py -- High level python wrapper classes for the core parts
9b25718
#                    of GnuCash
9b25718
#
9b25718
# Copyright (C) 2008 ParIT Worker Co-operative <paritinfo@parit.ca>
9b25718
# This program is free software; you can redistribute it and/or
9b25718
# modify it under the terms of the GNU General Public License as
9b25718
# published by the Free Software Foundation; either version 2 of
9b25718
# the License, or (at your option) any later version.
9b25718
#
9b25718
# This program is distributed in the hope that it will be useful,
9b25718
# but WITHOUT ANY WARRANTY; without even the implied warranty of
9b25718
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9b25718
# GNU General Public License for more details.
9b25718
#
9b25718
# You should have received a copy of the GNU General Public License
9b25718
# along with this program; if not, contact:
9b25718
# Free Software Foundation           Voice:  +1-617-542-5942
9b25718
# 51 Franklin Street, Fifth Floor    Fax:    +1-617-542-2652
9b25718
# Boston, MA  02110-1301,  USA       gnu@gnu.org
9b25718
#
9b25718
# @author Mark Jenkins, ParIT Worker Co-operative <mark@parit.ca>
9b25718
# @author Jeff Green,   ParIT Worker Co-operative <jeff@parit.ca>
9b25718
9b25718
# The following is for doxygen
9b25718
## @file
9b25718
#  @brief High level python wrapper classes for the core parts of GnuCash
9b25718
#  @author Mark Jenkins, ParIT Worker Co-operative <mark@parit.ca>
9b25718
#  @author Jeff Green,   ParIT Worker Co-operative <jeff@parit.ca>
9b25718
#  @ingroup python_bindings
9b25718
9b25718
import gnucash_core_c
9b25718
9b25718
from function_class import \
9b25718
     ClassFromFunctions, extract_attributes_with_prefix, \
9b25718
     default_arguments_decorator, method_function_returns_instance, \
9b25718
     methods_return_instance, process_list_convert_to_instance, \
9b25718
     method_function_returns_instance_list, methods_return_instance_lists
9b25718
9b25718
from gnucash_core_c import gncInvoiceLookup, gncInvoiceGetInvoiceFromTxn, \
9b25718
    gncInvoiceGetInvoiceFromLot, gncEntryLookup, gncInvoiceLookup, \
9b25718
    gncCustomerLookup, gncVendorLookup, gncJobLookup, gncEmployeeLookup, \
9b25718
    gncTaxTableLookup, gncTaxTableLookupByName, gnc_search_invoice_on_id, \
9b25718
    gnc_search_customer_on_id, gnc_search_bill_on_id , gnc_search_vendor_on_id, \
9b25718
    gncInvoiceNextID, gncCustomerNextID, gncTaxTableGetTables, gncVendorNextID
9b25718
9b25718
class GnuCashCoreClass(ClassFromFunctions):
9b25718
    _module = gnucash_core_c
9b25718
9b25718
    def do_lookup_create_oo_instance(self, lookup_function, cls, *args):
9b25718
        thing = lookup_function(self.get_instance(), *args)
9b25718
        if thing != None:
9b25718
            thing = cls(instance=thing)
9b25718
        return thing
9b25718
9b25718
9b25718
class GnuCashBackendException(Exception):
9b25718
    def __init__(self, msg, errors):
9b25718
        Exception.__init__(self, msg)
9b25718
        self.errors = errors
9b25718
9b25718
class Session(GnuCashCoreClass):
9b25718
    """A GnuCash book editing session
9b25718
9b25718
    To commit changes to the session you may need to call save,
9b25718
    (this is always the case with the file backend).
9b25718
9b25718
    When you're down with a session you may need to call end()
9b25718
9b25718
    Every Session has a Book in the book attribute, which you'll definitely
9b25718
    be interested in, as every GnuCash entity (Transaction, Split, Vendor,
9b25718
    Invoice..) is associated with a particular book where it is stored.
9b25718
    """
9b25718
9b25718
    def __init__(self, book_uri=None, ignore_lock=False, is_new=False,
9b25718
                 force_new= False):
9b25718
        """A convenient constructor that allows you to specify a book URI,
9b25718
        begin the session, and load the book.
9b25718
9b25718
        This can give you the power of calling
9b25718
        qof_session_new, qof_session_begin, and qof_session_load all in one!
9b25718
9b25718
        book_uri can be None to skip the calls to qof_session_begin and
9b25718
        qof_session_load, or it can be a string like "file:/test.xac"
9b25718
9b25718
        qof_session_load is only called if is_new is set to False
9b25718
9b25718
        is_new is passed to qof_session_begin as the argument create,
9b25718
        and force_new as the argument force. Is_new will create a new
9b25718
        database or file; force will force creation even if it will
9b25718
        destroy an existing dataset.
9b25718
9b25718
        ignore_lock is passed to qof_session_begin's argument of the
9b25718
        same name and is used to break an existing lock on a dataset.
9b25718
9b25718
9b25718
9b25718
        This function can raise a GnuCashBackendException. If it does,
9b25718
        you don't need to cleanup and call end() and destroy(), that is handled
9b25718
        for you, and the exception is raised.
9b25718
        """
9b25718
        GnuCashCoreClass.__init__(self)
9b25718
        if book_uri is not None:
9b25718
            try:
9b25718
                self.begin(book_uri, ignore_lock, is_new, force_new)
9b25718
                # Take care of backend inconsistency
9b25718
                # New xml file can't be loaded, new sql store
9b25718
                # has to be loaded before it can be altered
9b25718
                # Any existing store obviously has to be loaded
9b25718
                # More background: https://bugzilla.gnome.org/show_bug.cgi?id=726891
9b25718
                if book_uri[:3] != "xml" or not is_new:
9b25718
                    self.load()
9b25718
            except GnuCashBackendException, backend_exception:
9b25718
                self.end()
9b25718
                self.destroy()
9b25718
                raise
9b25718
9b25718
    def raise_backend_errors(self, called_function="qof_session function"):
9b25718
        """Raises a GnuCashBackendException if there are outstanding
9b25718
        QOF_BACKEND errors.
9b25718
9b25718
        set called_function to name the function that was last called
9b25718
        """
9b25718
        errors = self.pop_all_errors()
9b25718
        if errors != ():
9b25718
            raise GnuCashBackendException(
9b25718
                "call to %s resulted in the "
9b25718
                "following errors, %s" % (called_function, backend_error_dict[errors[0]]),
9b25718
                errors )
9b25718
9b25718
    def generate_errors(self):
9b25718
        """A generator that yields any outstanding QofBackend errors
9b25718
        """
9b25718
        while self.get_error() is not ERR_BACKEND_NO_ERR:
9b25718
            error = self.pop_error()
9b25718
            yield error
9b25718
9b25718
    def pop_all_errors(self):
9b25718
        """Returns any accumulated qof backend errors as a tuple
9b25718
        """
9b25718
        return tuple( self.generate_errors() )
9b25718
9b25718
    # STATIC METHODS
9b25718
    @staticmethod
9b25718
    def raise_backend_errors_after_call(function):
9b25718
        """A function decorator that results in a call to
9b25718
        raise_backend_errors after execution.
9b25718
        """
9b25718
        def new_function(self, *args):
9b25718
            return_value = function(self, *args)
9b25718
            self.raise_backend_errors(function.__name__)
9b25718
            return return_value
9b25718
        return new_function
9b25718
9b25718
class Book(GnuCashCoreClass):
9b25718
    """A Book encapsulates all of the GnuCash data, it is the place where
9b25718
    all GnuCash entities (Transaction, Split, Vendor, Invoice...), are
9b25718
    stored. You'll notice that all of the constructors for those entities
9b25718
    need a book to be associated with.
9b25718
9b25718
    The most common way to get a book is through the book property in the
9b25718
    Session class, that is, create a session that connects to some storage,
9b25718
    such as through 'my_session = Session('file:my_books.xac')', and access
9b25718
    the book via the book property, 'my_session.book'
9b25718
9b25718
    If you would like to create a Book without any backing storage, call the
9b25718
    Book constructor without any parameters, 'Book()'. You can later merge
9b25718
    such a book into a book with actual store by using merge_init.
9b25718
9b25718
    Methods of interest
9b25718
    get_root_account -- Returns the root level Account
9b25718
    get_table -- Returns a commodity lookup table, of type GncCommodityTable
9b25718
    """
9b25718
    def InvoiceLookup(self, guid):
9b25718
        from gnucash_business import Invoice
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncInvoiceLookup, Invoice, guid.get_instance() )
9b25718
9b25718
    def EntryLookup(self, guid):
9b25718
        from gnucash_business import Entr
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncEntryLookup, Entry, guid.get_instance() )
9b25718
9b25718
    def CustomerLookup(self, guid):
9b25718
        from gnucash_business import Customer
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncCustomerLookup, Customer, guid.get_instance())
9b25718
9b25718
    def JobLookup(self, guid):
9b25718
        from gnucash_business import Job
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncJobLookup, Job, guid.get_instance() )
9b25718
9b25718
    def VendorLookup(self, guid):
9b25718
        from gnucash_business import Vendor
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncVendorLookup, Vendor, guid.get_instance() )
9b25718
9b25718
    def EmployeeLookup(self, guid):
9b25718
        from gnucash_business import Employee
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncEmployeeLookup, Employee, guid.get_instance() )
9b25718
9b25718
    def TaxTableLookup(self, guid):
9b25718
        from gnucash_business import TaxTable
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncTaxTableLookup, TaxTable, guid.get_instance() )
9b25718
9b25718
    def TaxTableLookupByName(self, name):
9b25718
        from gnucash_business import TaxTable
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncTaxTableLookupByName, TaxTable, name)
9b25718
9b25718
    def TaxTableGetTables(self):
9b25718
        from gnucash_business import TaxTable
9b25718
        return [ TaxTable(instance=item) for item in gncTaxTableGetTables(self.instance) ]
9b25718
9b25718
    def BillLoookupByID(self, id):
9b25718
        from gnucash_business import Bill
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gnc_search_bill_on_id, Bill, id)
9b25718
9b25718
    def InvoiceLookupByID(self, id):
9b25718
        from gnucash_business import Invoice
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gnc_search_invoice_on_id, Invoice, id)
9b25718
9b25718
    def CustomerLookupByID(self, id):
9b25718
        from gnucash_business import Customer
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gnc_search_customer_on_id, Customer, id)
9b25718
9b25718
    def VendorLookupByID(self, id):
9b25718
        from gnucash_business import Vendor
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gnc_search_vendor_on_id, Vendor, id)
9b25718
            
9b25718
    def InvoiceNextID(self, customer):
9b25718
      ''' Return the next invoice ID. 
9b25718
      This works but I'm not entirely happy with it.  FIX ME'''
9b25718
      from gnucash.gnucash_core_c import gncInvoiceNextID
9b25718
      return gncInvoiceNextID(self.get_instance(),customer.GetEndOwner().get_instance()[1])
9b25718
      
9b25718
    def BillNextID(self, vendor):
9b25718
      ''' Return the next Bill ID. '''
9b25718
      from gnucash.gnucash_core_c import gncInvoiceNextID
9b25718
      return gncInvoiceNextID(self.get_instance(),vendor.GetEndOwner().get_instance()[1])
9b25718
9b25718
    def CustomerNextID(self):
9b25718
      ''' Return the next Customer ID. '''
9b25718
      from gnucash.gnucash_core_c import gncCustomerNextID
9b25718
      return gncCustomerNextID(self.get_instance())
9b25718
    
9b25718
    def VendorNextID(self):
9b25718
      ''' Return the next Vendor ID. '''
9b25718
      from gnucash.gnucash_core_c import gncVendorNextID
9b25718
      return gncVendorNextID(self.get_instance())
9b25718
9b25718
class GncNumeric(GnuCashCoreClass):
9b25718
    """Object used by GnuCash to store all numbers. Always consists of a
9b25718
    numerator and denominator.
9b25718
9b25718
    The constants GNC_DENOM_AUTO,
9b25718
    GNC_HOW_RND_FLOOR, GNC_HOW_RND_CEIL, GNC_HOW_RND_TRUNC,
9b25718
    GNC_HOW_RND_PROMOTE, GNC_HOW_RND_ROUND_HALF_DOWN,
9b25718
    GNC_HOW_RND_ROUND_HALF_UP, GNC_HOW_RND_ROUND, GNC_HOW_RND_NEVER,
9b25718
    GNC_HOW_DENOM_EXACT, GNC_HOW_DENOM_REDUCE, GNC_HOW_DENOM_LCD,
9b25718
    and GNC_HOW_DENOM_FIXED are available for arithmetic
9b25718
    functions like GncNumeric.add
9b25718
9b25718
    Look at gnc-numeric.h to see how to use these
9b25718
    """
9b25718
9b25718
    def __init__(self, num=0, denom=1, **kargs):
9b25718
        """Constructor that allows you to set the numerator and denominator or
9b25718
        leave them blank with a default value of 0 (not a good idea since there
9b25718
        is currently no way to alter the value after instantiation)
9b25718
        """
9b25718
        GnuCashCoreClass.__init__(self, num, denom, **kargs)
9b25718
        #if INSTANCE_ARG in kargs:
9b25718
        #    GnuCashCoreClass.__init__(**kargs)
9b25718
        #else:
9b25718
        #    self.set_denom(denom) # currently undefined
9b25718
        #    self.set_num(num)     # currently undefined
9b25718
9b25718
    def __unicode__(self):
9b25718
        """Returns a human readable numeric value string as UTF8."""
9b25718
        if self.denom() == 0:
9b25718
            return "Division by zero"
9b25718
        else:
9b25718
            value_float = self.to_double() 
9b25718
            value_str   = u"{0:.{1}f}".format(value_float,2) ## The second argument is the precision. It would be nice to be able to make it configurable.
9b25718
            return value_str
9b25718
9b25718
    def __str__(self):
9b25718
        """returns a human readable numeric value string as bytes."""
9b25718
        return unicode(self).encode('utf-8')
9b25718
9b25718
class GncPrice(GnuCashCoreClass):
9b25718
    '''
9b25718
    Each priceEach price in the database represents an "instantaneous"
9b25718
    quote for a given commodity with respect to another commodity.
9b25718
    For example, a given price might represent the value of LNUX in USD on 2001-02-03.
9b25718
9b25718
    Fields:
9b25718
      * commodity: the item being priced.
9b25718
      * currency: the denomination of the value of the item being priced.
9b25718
      * value: the value of the item being priced.
9b25718
      * time: the time the price was valid.
9b25718
      * source: a string describing the source of the quote. These strings will be something like this:
9b25718
      "Finance::Quote", "user:misc", "user:foo", etc. If the quote came from a user, as a matter of policy,
9b25718
      you *must* prefix the string you give with "user:". For now, the only other reserved values are
9b25718
      "Finance::Quote" and "old-file-import". Any string used must be added to the source_list array in
9b25718
      dialog-price-edit-db.c so that it can be properly translated. (There are unfortunately many strings
9b25718
      in users' databases, so this string must be translated on output instead of always being used in untranslated form).
9b25718
      * type: the type of quote - types possible right now are bid, ask, last, nav, and
9b25718
      unknown.Each price in the database represents an "instantaneous" quote for a given
9b25718
      commodity with respect to another commodity.
9b25718
      For example, a given price might represent the value of LNUX in USD on 2001-02-03.
9b25718
9b25718
      See also http://code.gnucash.org/docs/head/group__Price.html
9b25718
    '''
9b25718
    pass
9b25718
GncPrice.add_methods_with_prefix('gnc_price_')
9b25718
9b25718
9b25718
class GncPriceDB(GnuCashCoreClass):
9b25718
    '''
9b25718
    a simple price database for gnucash.
9b25718
    The PriceDB is intended to be a database of price quotes, or more specifically,
9b25718
    a database of GNCPrices. For the time being, it is still a fairly simple
9b25718
    database supporting only fairly simple queries. It is expected that new
9b25718
    queries will be added as needed, and that there is some advantage to delaying
9b25718
    complex queries for now in the hope that we get a real DB implementation
9b25718
    before they're really needed.
9b25718
9b25718
    Every QofBook contains a GNCPriceDB, accessible via gnc_pricedb_get_db.
9b25718
9b25718
    Definition in file gnc-pricedb.h.
9b25718
    See also http://code.gnucash.org/docs/head/gnc-pricedb_8h.html
9b25718
    '''
9b25718
9b25718
GncPriceDB.add_methods_with_prefix('gnc_pricedb_')
9b25718
PriceDB_dict =  {
9b25718
                'lookup_latest' : GncPrice,
9b25718
                'lookup_nearest_in_time' : GncPrice,
9b25718
                'lookup_latest_before' : GncPrice,
9b25718
                'convert_balance_latest_price' : GncNumeric,
9b25718
                'convert_balance_nearest_price' : GncNumeric,
9b25718
                }
9b25718
methods_return_instance(GncPriceDB,PriceDB_dict)
9b25718
GncPriceDB.get_prices = method_function_returns_instance_list(
9b25718
    GncPriceDB.get_prices, GncPrice )
9b25718
9b25718
9b25718
class GncCommodity(GnuCashCoreClass): pass
9b25718
9b25718
class GncCommodityTable(GnuCashCoreClass):
9b25718
    """A CommodityTable provides a way to store and lookup commodities.
9b25718
    Commodities are primarily currencies, but other tradable things such as
9b25718
    stocks, mutual funds, and material substances are possible.
9b25718
9b25718
    Users of this library should not create their own CommodityTable, instead
9b25718
    the get_table method from the Book class should be used.
9b25718
9b25718
    This table is automatically populated with the GnuCash default commodity's
9b25718
    which includes most of the world's currencies.
9b25718
    """
9b25718
9b25718
    pass
9b25718
9b25718
class GncCommodityNamespace(GnuCashCoreClass):
9b25718
    pass
9b25718
9b25718
class GncLot(GnuCashCoreClass):
9b25718
    def GetInvoiceFromLot(self):
9b25718
        from gnucash_business import Invoice
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncInvoiceGetInvoiceFromLot, Invoice )
9b25718
9b25718
class Transaction(GnuCashCoreClass):
9b25718
    """A GnuCash Transaction
9b25718
9b25718
    Consists of at least one (generally two) splits to represent a transaction
9b25718
    between two accounts.
9b25718
9b25718
9b25718
    Has a GetImbalance() method that returns a list of all the imbalanced
9b25718
    currencies. Each list item is a two element tuple, the first element is
9b25718
    the imbalanced commodity, the second element is the value.
9b25718
9b25718
    Warning, the commodity.get_instance() value can be None when there
9b25718
    is no currency set for the transaction.
9b25718
    """
9b25718
    _new_instance = 'xaccMallocTransaction'
9b25718
    def GetNthSplit(self, n):
9b25718
        return self.GetSplitList().pop(n)
9b25718
9b25718
    def GetInvoiceFromTxn(self):
9b25718
        from gnucash_business import Transaction
9b25718
        return self.do_lookup_create_oo_instance(
9b25718
            gncInvoiceGetInvoiceFromTxn, Transaction )
9b25718
9b25718
def decorate_monetary_list_returning_function(orig_function):
9b25718
    def new_function(self):
9b25718
        # warning, item.commodity has been shown to be None
9b25718
        # when the transaction doesn't have a currency
9b25718
        return [(GncCommodity(instance=item.commodity),
9b25718
                 GncNumeric(instance=item.value))
9b25718
                for item in orig_function(self) ]
9b25718
    return new_function
9b25718
9b25718
class Split(GnuCashCoreClass):
9b25718
    """A GnuCash Split
9b25718
9b25718
    The most basic representation of a movement of currency from one account to
9b25718
    another.
9b25718
    """
9b25718
    _new_instance = 'xaccMallocSplit'
9b25718
9b25718
class Account(GnuCashCoreClass):
9b25718
    """A GnuCash Account.
9b25718
9b25718
    A fundamental entity in accounting, an Account provides representation
9b25718
    for a financial object, such as a ACCT_TYPE_BANK account, an
9b25718
    ACCT_TYPE_ASSET (like a building),
9b25718
    a ACCT_TYPE_LIABILITY (such as a bank loan), a summary of some type of
9b25718
    ACCT_TYPE_EXPENSE, or a summary of some source of ACCT_TYPE_INCOME .
9b25718
9b25718
    The words in upper case are the constants that GnuCash and this library uses
9b25718
    to describe account type. Here is the full list:
9b25718
    ACCT_TYPE_ASSET, ACCT_TYPE_BANK, ACCT_TYPE_CASH, ACCT_TYPE_CHECKING, \
9b25718
    ACCT_TYPE_CREDIT, ACCT_TYPE_EQUITY, ACCT_TYPE_EXPENSE, ACCT_TYPE_INCOME, \
9b25718
    ACCT_TYPE_LIABILITY, ACCT_TYPE_MUTUAL, ACCT_TYPE_PAYABLE, \
9b25718
    ACCT_TYPE_RECEIVABLE, ACCT_TYPE_STOCK, ACCT_TYPE_ROOT, ACCT_TYPE_TRADING
9b25718
9b25718
    These are not strings, they are attributes you can import from this
9b25718
    module
9b25718
    """
9b25718
    _new_instance = 'xaccMallocAccount'
9b25718
9b25718
class GUID(GnuCashCoreClass):
9b25718
    _new_instance = 'guid_new_return'
9b25718
9b25718
# Session
9b25718
Session.add_constructor_and_methods_with_prefix('qof_session_', 'new')
9b25718
9b25718
def one_arg_default_none(function):
9b25718
    return default_arguments_decorator(function, None, None)
9b25718
Session.decorate_functions(one_arg_default_none, "load", "save")
9b25718
9b25718
Session.decorate_functions( Session.raise_backend_errors_after_call,
9b25718
                            "begin", "load", "save", "end")
9b25718
Session.get_book = method_function_returns_instance(
9b25718
    Session.get_book, Book )
9b25718
9b25718
Session.book = property( Session.get_book )
9b25718
9b25718
# import all of the session backend error codes into this module
9b25718
this_module_dict = globals()
9b25718
for error_name, error_value, error_name_after_prefix in \
9b25718
    extract_attributes_with_prefix(gnucash_core_c, 'ERR_'):
9b25718
    this_module_dict[ error_name ] = error_value
9b25718
9b25718
#backend error codes used for reverse lookup
9b25718
backend_error_dict = {}
9b25718
for error_name, error_value, error_name_after_prefix in \
9b25718
    extract_attributes_with_prefix(gnucash_core_c, 'ERR_'):
9b25718
    backend_error_dict[ error_value ] = error_name
9b25718
9b25718
# GncNumeric denominator computation schemes
9b25718
# Used for the denom argument in arithmetic functions like GncNumeric.add
9b25718
from gnucash.gnucash_core_c import GNC_DENOM_AUTO
9b25718
9b25718
# GncNumeric rounding instructions
9b25718
# used for the how argument in arithmetic functions like GncNumeric.add
9b25718
from gnucash.gnucash_core_c import \
9b25718
    GNC_HOW_RND_FLOOR, GNC_HOW_RND_CEIL, GNC_HOW_RND_TRUNC, \
9b25718
    GNC_HOW_RND_PROMOTE, GNC_HOW_RND_ROUND_HALF_DOWN, \
9b25718
    GNC_HOW_RND_ROUND_HALF_UP, GNC_HOW_RND_ROUND, GNC_HOW_RND_NEVER
9b25718
9b25718
# GncNumeric denominator types
9b25718
# used for the how argument in arithmetic functions like GncNumeric.add
9b25718
from gnucash.gnucash_core_c import \
9b25718
    GNC_HOW_DENOM_EXACT, GNC_HOW_DENOM_REDUCE, GNC_HOW_DENOM_LCD, \
9b25718
    GNC_HOW_DENOM_FIXED
9b25718
9b25718
# import account types
9b25718
from gnucash.gnucash_core_c import \
9b25718
    ACCT_TYPE_ASSET, ACCT_TYPE_BANK, ACCT_TYPE_CASH, ACCT_TYPE_CHECKING, \
9b25718
    ACCT_TYPE_CREDIT, ACCT_TYPE_EQUITY, ACCT_TYPE_EXPENSE, ACCT_TYPE_INCOME, \
9b25718
    ACCT_TYPE_LIABILITY, ACCT_TYPE_MUTUAL, ACCT_TYPE_PAYABLE, \
9b25718
    ACCT_TYPE_RECEIVABLE, ACCT_TYPE_STOCK, ACCT_TYPE_ROOT, ACCT_TYPE_TRADING
9b25718
9b25718
#Book
9b25718
Book.add_constructor_and_methods_with_prefix('qof_book_', 'new')
9b25718
Book.add_method('gnc_book_get_root_account', 'get_root_account')
9b25718
Book.add_method('gnc_book_set_root_account', 'set_root_account')
9b25718
Book.add_method('gnc_commodity_table_get_table', 'get_table')
9b25718
Book.add_method('gnc_pricedb_get_db', 'get_price_db')
9b25718
Book.add_method('qof_book_increment_and_format_counter', 'increment_and_format_counter')
9b25718
9b25718
#Functions that return Account
9b25718
Book.get_root_account = method_function_returns_instance(
9b25718
    Book.get_root_account, Account )
9b25718
#Functions that return GncCommodityTable
9b25718
Book.get_table = method_function_returns_instance(
9b25718
    Book.get_table, GncCommodityTable )
9b25718
#Functions that return GNCPriceDB
9b25718
Book.get_price_db = method_function_returns_instance(
9b25718
    Book.get_price_db, GncPriceDB)
9b25718
9b25718
# GncNumeric
9b25718
GncNumeric.add_constructor_and_methods_with_prefix('gnc_numeric_', 'create')
9b25718
9b25718
gncnumeric_dict =   {
9b25718
                        'same' : GncNumeric,
9b25718
                        'add' : GncNumeric,
9b25718
                        'sub' : GncNumeric,
9b25718
                        'mul' : GncNumeric,
9b25718
                        'div' : GncNumeric,
9b25718
                        'neg' : GncNumeric,
9b25718
                        'abs' : GncNumeric,
9b25718
                        'add_fixed' : GncNumeric,
9b25718
                        'sub_fixed' : GncNumeric,
9b25718
                        'add_with_error' : GncNumeric,
9b25718
                        'sub_with_error' : GncNumeric,
9b25718
                        'mul_with_error' : GncNumeric,
9b25718
                        'div_with_error' : GncNumeric,
9b25718
                        'convert' : GncNumeric,
9b25718
                        'reduce' : GncNumeric
9b25718
                    }
9b25718
methods_return_instance(GncNumeric, gncnumeric_dict)
9b25718
9b25718
# GncCommodity
9b25718
GncCommodity.add_constructor_and_methods_with_prefix('gnc_commodity_', 'new')
9b25718
#Functions that return GncCommodity
9b25718
GncCommodity.clone = method_function_returns_instance(
9b25718
    GncCommodity.clone, GncCommodity )
9b25718
9b25718
# GncCommodityTable
9b25718
GncCommodityTable.add_methods_with_prefix('gnc_commodity_table_')
9b25718
commoditytable_dict =   {
9b25718
                            'lookup' : GncCommodity,
9b25718
                            'lookup_unique' : GncCommodity,
9b25718
                            'find_full' : GncCommodity,
9b25718
                            'insert' : GncCommodity,
9b25718
                            'add_namespace': GncCommodityNamespace,
9b25718
                            'find_namespace': GncCommodityNamespace,
9b25718
                        }
9b25718
methods_return_instance(GncCommodityTable, commoditytable_dict)
9b25718
9b25718
methods_return_instance_lists(
9b25718
    GncCommodityTable, { 'get_namespaces': GncCommodityNamespace,
9b25718
                         'get_namespaces_list': GncCommodityNamespace,
9b25718
                         'get_commodities': GncCommodity,
9b25718
                         'get_quotable_commodities': GncCommodity,
9b25718
                         
9b25718
                       } )
9b25718
9b25718
# GncCommodityNamespace
9b25718
GncCommodityNamespace.add_methods_with_prefix('gnc_commodity_namespace_')
9b25718
GncCommodityNamespace.get_commodity_list = \
9b25718
    method_function_returns_instance_list(
9b25718
    GncCommodityNamespace.get_commodity_list, GncCommodity )
9b25718
9b25718
# GncLot
9b25718
GncLot.add_constructor_and_methods_with_prefix('gnc_lot_', 'new')
9b25718
9b25718
gnclot_dict =   {
9b25718
                    'get_account' : Account,
9b25718
                    'get_book' : Book,
9b25718
                    'get_earliest_split' : Split,
9b25718
                    'get_latest_split' : Split,
9b25718
                    'get_balance' : GncNumeric,
9b25718
                    'lookup' : GncLot,
9b25718
                    'make_default' : GncLot
9b25718
                }
9b25718
methods_return_instance(GncLot, gnclot_dict)
9b25718
9b25718
# Transaction
9b25718
Transaction.add_methods_with_prefix('xaccTrans')
9b25718
Transaction.add_method('gncTransGetGUID', 'GetGUID');
9b25718
9b25718
trans_dict =    {
9b25718
                    'GetSplit': Split,
9b25718
                    'FindSplitByAccount': Split,
9b25718
                    'Clone': Transaction,
9b25718
                    'Reverse': Transaction,
9b25718
                    'GetReversedBy': Transaction,
9b25718
                    'GetImbalanceValue': GncNumeric,
9b25718
                    'GetAccountValue': GncNumeric,
9b25718
                    'GetAccountAmount': GncNumeric,
9b25718
                    'GetAccountConvRate': GncNumeric,
9b25718
                    'GetAccountBalance': GncNumeric,
9b25718
                    'GetCurrency': GncCommodity,
9b25718
                    'GetGUID': GUID
9b25718
                }
9b25718
 
9b25718
methods_return_instance(Transaction, trans_dict)
9b25718
methods_return_instance_lists(
9b25718
    Transaction, { 'GetSplitList': Split,
9b25718
                       })
9b25718
Transaction.decorate_functions(
9b25718
    decorate_monetary_list_returning_function, 'GetImbalance')
9b25718
9b25718
# Split
9b25718
Split.add_methods_with_prefix('xaccSplit')
9b25718
Split.add_method('gncSplitGetGUID', 'GetGUID');
9b25718
9b25718
split_dict =    {
9b25718
                    'GetBook': Book,
9b25718
                    'GetAccount': Account,
9b25718
                    'GetParent': Transaction,
9b25718
                    'Lookup': Split,
9b25718
                    'GetOtherSplit': Split,
9b25718
                    'GetAmount': GncNumeric,
9b25718
                    'GetValue': GncNumeric,
9b25718
                    'GetSharePrice': GncNumeric,
9b25718
                    'ConvertAmount': GncNumeric,
9b25718
                    'GetBaseValue': GncNumeric,
9b25718
                    'GetBalance': GncNumeric,
9b25718
                    'GetClearedBalance': GncNumeric,
9b25718
                    'GetReconciledBalance': GncNumeric,
9b25718
                    'VoidFormerAmount': GncNumeric,
9b25718
                    'VoidFormerValue': GncNumeric,
9b25718
                    'GetGUID': GUID
9b25718
                }
9b25718
methods_return_instance(Split, split_dict)
9b25718
9b25718
Split.account = property( Split.GetAccount, Split.SetAccount )
9b25718
Split.parent = property( Split.GetParent, Split.SetParent )
9b25718
9b25718
# Account
9b25718
Account.add_methods_with_prefix('xaccAccount')
9b25718
Account.add_methods_with_prefix('gnc_account_')
9b25718
Account.add_method('gncAccountGetGUID', 'GetGUID');
9b25718
9b25718
account_dict =  {
9b25718
                    'get_book' : Book,
9b25718
                    'Lookup' : Account,
9b25718
                    'get_parent' : Account,
9b25718
                    'get_root' : Account,
9b25718
                    'nth_child' : Account,
9b25718
                    'lookup_by_code' : Account,
9b25718
                    'lookup_by_name' : Account,
9b25718
                    'lookup_by_full_name' : Account,
9b25718
                    'FindTransByDesc' : Transaction,
9b25718
                    'FindSplitByDesc' : Split,
9b25718
                    'GetBalance' : GncNumeric,
9b25718
                    'GetClearedBalance' : GncNumeric,
9b25718
                    'GetReconciledBalance' : GncNumeric,
9b25718
                    'GetPresentBalance' : GncNumeric,
9b25718
                    'GetProjectedMinimumBalance' : GncNumeric,
9b25718
                    'GetBalanceAsOfDate' : GncNumeric,
9b25718
                    'ConvertBalanceToCurrency' : GncNumeric,
9b25718
                    'ConvertBalanceToCurrencyAsOfDate' : GncNumeric,
9b25718
                    'GetBalanceInCurrency' : GncNumeric,
9b25718
                    'GetClearedBalanceInCurrency' : GncNumeric,
9b25718
                    'GetReconciledBalanceInCurrency' : GncNumeric,
9b25718
                    'GetPresentBalanceInCurrency' : GncNumeric,
9b25718
                    'GetProjectedMinimumBalanceInCurrency' : GncNumeric,
9b25718
                    'GetBalanceAsOfDateInCurrency' : GncNumeric,
9b25718
                    'GetBalanceChangeForPeriod' : GncNumeric,
9b25718
                    'GetCommodity' : GncCommodity,
9b25718
                    'GetGUID': GUID
9b25718
                }
9b25718
methods_return_instance(Account, account_dict)
9b25718
methods_return_instance_lists(
9b25718
    Account, { 'GetSplitList': Split,
9b25718
               'get_children': Account,
9b25718
               'get_children_sorted': Account,
9b25718
               'get_descendants': Account,
9b25718
               'get_descendants_sorted': Account
9b25718
                       })
9b25718
Account.name = property( Account.GetName, Account.SetName )
9b25718
9b25718
#GUID
9b25718
GUID.add_methods_with_prefix('guid_')
9b25718
GUID.add_method('xaccAccountLookup', 'AccountLookup')
9b25718
GUID.add_method('xaccTransLookup', 'TransLookup')
9b25718
GUID.add_method('xaccSplitLookup', 'SplitLookup')
9b25718
9b25718
## define addition methods for GUID object - do we need these
9b25718
GUID.add_method('guid_to_string', 'to_string')
9b25718
#GUID.add_method('string_to_guid', 'string_to_guid')
9b25718
9b25718
guid_dict = {
9b25718
                'copy' : GUID,
9b25718
                'TransLookup': Transaction,
9b25718
                'AccountLookup': Account,
9b25718
                'SplitLookup': Split
9b25718
            }
9b25718
methods_return_instance(GUID, guid_dict)
9b25718
9b25718
#GUIDString
9b25718
class GUIDString(GnuCashCoreClass):
9b25718
    pass
9b25718
9b25718
GUIDString.add_constructor_and_methods_with_prefix('string_', 'to_guid')
9b25718
9b25718
#Query
9b25718
from gnucash_core_c import \
9b25718
    QOF_QUERY_AND, \
9b25718
    QOF_QUERY_OR, \
9b25718
    QOF_QUERY_NAND, \
9b25718
    QOF_QUERY_NOR, \
9b25718
    QOF_QUERY_XOR
9b25718
9b25718
from gnucash_core_c import \
9b25718
    QOF_STRING_MATCH_NORMAL, \
9b25718
    QOF_STRING_MATCH_CASEINSENSITIVE
9b25718
9b25718
from gnucash_core_c import \
9b25718
    QOF_COMPARE_LT, \
9b25718
    QOF_COMPARE_LTE, \
9b25718
    QOF_COMPARE_EQUAL, \
9b25718
    QOF_COMPARE_GT, \
9b25718
    QOF_COMPARE_GTE, \
9b25718
    QOF_COMPARE_NEQ
9b25718
9b25718
from gnucash_core_c import \
9b25718
    INVOICE_TYPE
9b25718
9b25718
from gnucash_core_c import \
9b25718
    INVOICE_IS_PAID
9b25718
9b25718
class Query(GnuCashCoreClass):
9b25718
    pass
9b25718
9b25718
Query.add_constructor_and_methods_with_prefix('qof_query_', 'create')
9b25718
9b25718
Query.add_method('qof_query_set_book', 'set_book')
9b25718
Query.add_method('qof_query_search_for', 'search_for')
9b25718
Query.add_method('qof_query_run', 'run')
9b25718
Query.add_method('qof_query_add_term', 'add_term')
9b25718
Query.add_method('qof_query_add_boolean_match', 'add_boolean_match')
9b25718
Query.add_method('qof_query_destroy', 'destroy')
9b25718
9b25718
class QueryStringPredicate(GnuCashCoreClass):
9b25718
    pass
9b25718
9b25718
QueryStringPredicate.add_constructor_and_methods_with_prefix('qof_query_', 'string_predicate')
9b25718
9b25718
class QueryBooleanPredicate(GnuCashCoreClass):
9b25718
    pass
9b25718
9b25718
QueryBooleanPredicate.add_constructor_and_methods_with_prefix('qof_query_', 'boolean_predicate')
9b25718
9b25718
class QueryInt32Predicate(GnuCashCoreClass):
9b25718
    pass
9b25718
9b25718
QueryInt32Predicate.add_constructor_and_methods_with_prefix('qof_query_', 'int32_predicate')