GnuCash  3.7-552-g279a5fcde
gnucash_core.py
Go to the documentation of this file.
1 # gnucash_core.py -- High level python wrapper classes for the core parts
2 # of GnuCash
3 #
4 # Copyright (C) 2008 ParIT Worker Co-operative <paritinfo@parit.ca>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License as
7 # published by the Free Software Foundation; either version 2 of
8 # the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, contact:
17 # Free Software Foundation Voice: +1-617-542-5942
18 # 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652
19 # Boston, MA 02110-1301, USA gnu@gnu.org
20 #
21 # @author Mark Jenkins, ParIT Worker Co-operative <mark@parit.ca>
22 # @author Jeff Green, ParIT Worker Co-operative <jeff@parit.ca>
23 
24 # The following is for doxygen
25 
30 
31 import gnucash.gnucash_core_c as gnucash_core_c
32 
33 from gnucash.function_class import \
34  ClassFromFunctions, extract_attributes_with_prefix, \
35  default_arguments_decorator, method_function_returns_instance, \
36  methods_return_instance, process_list_convert_to_instance, \
37  method_function_returns_instance_list, methods_return_instance_lists
38 
39 from gnucash.gnucash_core_c import gncInvoiceLookup, gncInvoiceGetInvoiceFromTxn, \
40  gncInvoiceGetInvoiceFromLot, gncEntryLookup, gncInvoiceLookup, \
41  gncCustomerLookup, gncVendorLookup, gncJobLookup, gncEmployeeLookup, \
42  gncTaxTableLookup, gncTaxTableLookupByName, gnc_search_invoice_on_id, \
43  gnc_search_customer_on_id, gnc_search_bill_on_id , \
44  gnc_search_vendor_on_id, gncInvoiceNextID, gncCustomerNextID, \
45  gncVendorNextID, gncTaxTableGetTables, gnc_numeric_zero, \
46  gnc_numeric_create, double_to_gnc_numeric, string_to_gnc_numeric, \
47  gnc_numeric_to_string
48 
49 class GnuCashCoreClass(ClassFromFunctions):
50  _module = gnucash_core_c
51 
52  def do_lookup_create_oo_instance(self, lookup_function, cls, *args):
53  thing = lookup_function(self.get_instance(), *args)
54  if thing != None:
55  thing = cls(instance=thing)
56  return thing
57 
58 
59 class GnuCashBackendException(Exception):
60  def __init__(self, msg, errors):
61  Exception.__init__(self, msg)
62  self.errors = errors
63 
65  """A GnuCash book editing session
66 
67  To commit changes to the session you may need to call save,
68  (this is always the case with the file backend).
69 
70  When you're down with a session you may need to call end()
71 
72  Every Session has a Book in the book attribute, which you'll definitely
73  be interested in, as every GnuCash entity (Transaction, Split, Vendor,
74  Invoice..) is associated with a particular book where it is stored.
75  """
76 
77  def __init__(self, book_uri=None, ignore_lock=False, is_new=False,
78  force_new= False):
79  """A convenient constructor that allows you to specify a book URI,
80  begin the session, and load the book.
81 
82  This can give you the power of calling
83  qof_session_new, qof_session_begin, and qof_session_load all in one!
84 
85  book_uri can be None to skip the calls to qof_session_begin and
86  qof_session_load, or it can be a string like "file:/test.xac"
87 
88  qof_session_load is only called if is_new is set to False
89 
90  is_new is passed to qof_session_begin as the argument create,
91  and force_new as the argument force. Is_new will create a new
92  database or file; force will force creation even if it will
93  destroy an existing dataset.
94 
95  ignore_lock is passed to qof_session_begin's argument of the
96  same name and is used to break an existing lock on a dataset.
97 
98 
99 
100  This function can raise a GnuCashBackendException. If it does,
101  you don't need to cleanup and call end() and destroy(), that is handled
102  for you, and the exception is raised.
103  """
104  GnuCashCoreClass.__init__(self)
105  if book_uri is not None:
106  try:
107  self.begin(book_uri, ignore_lock, is_new, force_new)
108  # Take care of backend inconsistency
109  # New xml file can't be loaded, new sql store
110  # has to be loaded before it can be altered
111  # Any existing store obviously has to be loaded
112  # More background: https://bugs.gnucash.org/show_bug.cgi?id=726891
113  if book_uri[:3] != "xml" or not is_new:
114  self.load()
115  except GnuCashBackendException as backend_exception:
116  self.end()
117  self.destroy()
118  raise
119 
120  def raise_backend_errors(self, called_function="qof_session function"):
121  """Raises a GnuCashBackendException if there are outstanding
122  QOF_BACKEND errors.
123 
124  set called_function to name the function that was last called
125  """
126  errors = self.pop_all_errors()
127  if errors != ():
129  "call to %s resulted in the "
130  "following errors, %s" % (called_function, backend_error_dict[errors[0]]),
131  errors )
132 
133  def generate_errors(self):
134  """A generator that yields any outstanding QofBackend errors
135  """
136  while self.get_error() is not ERR_BACKEND_NO_ERR:
137  error = self.pop_error()
138  yield error
139 
140  def pop_all_errors(self):
141  """Returns any accumulated qof backend errors as a tuple
142  """
143  return tuple( self.generate_errors() )
144 
145  # STATIC METHODS
146  @staticmethod
148  """A function decorator that results in a call to
149  raise_backend_errors after execution.
150  """
151  def new_function(self, *args):
152  return_value = function(self, *args)
153  self.raise_backend_errors(function.__name__)
154  return return_value
155  return new_function
156 
158  """A Book encapsulates all of the GnuCash data, it is the place where
159  all GnuCash entities (Transaction, Split, Vendor, Invoice...), are
160  stored. You'll notice that all of the constructors for those entities
161  need a book to be associated with.
162 
163  The most common way to get a book is through the book property in the
164  Session class, that is, create a session that connects to some storage,
165  such as through 'my_session = Session('file:my_books.xac')', and access
166  the book via the book property, 'my_session.book'
167 
168  If you would like to create a Book without any backing storage, call the
169  Book constructor without any parameters, 'Book()'. You can later merge
170  such a book into a book with actual store by using merge_init.
171 
172  Methods of interest
173  get_root_account -- Returns the root level Account
174  get_table -- Returns a commodity lookup table, of type GncCommodityTable
175  """
176  def InvoiceLookup(self, guid):
177  from gnucash.gnucash_business import Invoice
178  return self.do_lookup_create_oo_instance(
179  gncInvoiceLookup, Invoice, guid.get_instance() )
180 
181  def EntryLookup(self, guid):
182  from gnucash.gnucash_business import Entry
183  return self.do_lookup_create_oo_instance(
184  gncEntryLookup, Entry, guid.get_instance() )
185 
186  def CustomerLookup(self, guid):
187  from gnucash.gnucash_business import Customer
188  return self.do_lookup_create_oo_instance(
189  gncCustomerLookup, Customer, guid.get_instance())
190 
191  def JobLookup(self, guid):
192  from gnucash.gnucash_business import Job
193  return self.do_lookup_create_oo_instance(
194  gncJobLookup, Job, guid.get_instance() )
195 
196  def VendorLookup(self, guid):
197  from gnucash.gnucash_business import Vendor
198  return self.do_lookup_create_oo_instance(
199  gncVendorLookup, Vendor, guid.get_instance() )
200 
201  def EmployeeLookup(self, guid):
202  from gnucash.gnucash_business import Employee
203  return self.do_lookup_create_oo_instance(
204  gncEmployeeLookup, Employee, guid.get_instance() )
205 
206  def TaxTableLookup(self, guid):
207  from gnucash.gnucash_business import TaxTable
208  return self.do_lookup_create_oo_instance(
209  gncTaxTableLookup, TaxTable, guid.get_instance() )
210 
211  def TaxTableLookupByName(self, name):
212  from gnucash.gnucash_business import TaxTable
213  return self.do_lookup_create_oo_instance(
214  gncTaxTableLookupByName, TaxTable, name)
215 
216  def TaxTableGetTables(self):
217  from gnucash.gnucash_business import TaxTable
218  return [ TaxTable(instance=item) for item in gncTaxTableGetTables(self.instance) ]
219 
220  def BillLookupByID(self, id):
221  from gnucash.gnucash_business import Bill
222  return self.do_lookup_create_oo_instance(
223  gnc_search_bill_on_id, Bill, id)
224 
225  def InvoiceLookupByID(self, id):
226  from gnucash.gnucash_business import Invoice
227  return self.do_lookup_create_oo_instance(
228  gnc_search_invoice_on_id, Invoice, id)
229 
230  def CustomerLookupByID(self, id):
231  from gnucash.gnucash_business import Customer
232  return self.do_lookup_create_oo_instance(
233  gnc_search_customer_on_id, Customer, id)
234 
235  def VendorLookupByID(self, id):
236  from gnucash.gnucash_business import Vendor
237  return self.do_lookup_create_oo_instance(
238  gnc_search_vendor_on_id, Vendor, id)
239 
240  def InvoiceNextID(self, customer):
241  ''' Return the next invoice ID.
242  '''
243  from gnucash.gnucash_core_c import gncInvoiceNextID
244  return gncInvoiceNextID(self.get_instance(),customer.GetEndOwner().get_instance()[1])
245 
246  def BillNextID(self, vendor):
247  ''' Return the next Bill ID. '''
248  from gnucash.gnucash_core_c import gncInvoiceNextID
249  return gncInvoiceNextID(self.get_instance(),vendor.GetEndOwner().get_instance()[1])
250 
251  def CustomerNextID(self):
252  ''' Return the next Customer ID. '''
253  from gnucash.gnucash_core_c import gncCustomerNextID
254  return gncCustomerNextID(self.get_instance())
255 
256  def VendorNextID(self):
257  ''' Return the next Vendor ID. '''
258  from gnucash.gnucash_core_c import gncVendorNextID
259  return gncVendorNextID(self.get_instance())
260 
262  """Object used by GnuCash to store all numbers. Always consists of a
263  numerator and denominator.
264 
265  The constants GNC_DENOM_AUTO,
266  GNC_HOW_RND_FLOOR, GNC_HOW_RND_CEIL, GNC_HOW_RND_TRUNC,
267  GNC_HOW_RND_PROMOTE, GNC_HOW_RND_ROUND_HALF_DOWN,
268  GNC_HOW_RND_ROUND_HALF_UP, GNC_HOW_RND_ROUND, GNC_HOW_RND_NEVER,
269  GNC_HOW_DENOM_EXACT, GNC_HOW_DENOM_REDUCE, GNC_HOW_DENOM_LCD,
270  and GNC_HOW_DENOM_FIXED are available for arithmetic
271  functions like GncNumeric.add
272 
273  Look at gnc-numeric.h to see how to use these
274  """
275 
276  def __init__(self, *args, **kargs):
277  """Constructor that supports the following formats:
278  * No arguments defaulting to zero: eg. GncNumeric() == 0/1
279  * A integer: e.g. GncNumeric(1) == 1/1
280  * Numerator and denominator intager pair: eg. GncNumeric(1, 2) == 1/2
281  * A floating point number: e.g. GncNumeric(0.5) == 1/2
282  * A floating point number with defined conversion: e.g.
283  GncNumeric(0.5, GNC_DENOM_AUTO,
284  GNC_HOW_DENOM_FIXED | GNC_HOW_RND_NEVER) == 1/2
285  * A string: e.g. GncNumeric("1/2") == 1/2
286  """
287  if 'instance' not in kargs:
288  kargs['instance'] = GncNumeric.__args_to_instance(args)
289  GnuCashCoreClass.__init__(self, [], **kargs)
290 
291  @staticmethod
292  def __args_to_instance(args):
293  if len(args) == 0:
294  return gnc_numeric_zero()
295  elif len(args) == 1:
296  arg = args[0]
297  if isinstance(arg, int):
298  return gnc_numeric_create(arg ,1)
299  elif isinstance(arg, float):
300  return double_to_gnc_numeric(arg, GNC_DENOM_AUTO, GNC_HOW_DENOM_FIXED | GNC_HOW_RND_NEVER)
301  elif isinstance(arg, str):
302  instance = gnc_numeric_zero()
303  if not string_to_gnc_numeric(arg, instance):
304  raise TypeError('Failed to convert to GncNumeric: ' + str(args))
305  return instance
306  else:
307  raise TypeError('Only single int/float/str allowed: ' + str(args))
308  elif len(args) == 2:
309  if isinstance(args[0], int) and isinstance(args[1], int):
310  return gnc_numeric_create(*args)
311  else:
312  raise TypeError('Only two ints allowed: ' + str(args))
313  elif len(args) == 3:
314  if isinstance(args[0], float) \
315  and isinstance(args[1], int) \
316  and type(args[2]) == type(GNC_HOW_DENOM_FIXED):
317  return double_to_gnc_numeric(*args)
318  else:
319  raise TypeError('Only (float, int, GNC_HOW_RND_*) allowed: ' + str(args))
320  else:
321  raise TypeError('Required single int/float/str or two ints: ' + str(args))
322 
323  def to_fraction(self):
324  from fractions import Fraction
325  return Fraction(self.num(), self.denom())
326 
327  def __str__(self):
328  """Returns a human readable numeric value string as UTF8."""
329  return gnc_numeric_to_string(self.instance)
330 
332  '''
333  Each priceEach price in the database represents an "instantaneous"
334  quote for a given commodity with respect to another commodity.
335  For example, a given price might represent the value of LNUX in USD on 2001-02-03.
336 
337  Fields:
338  * commodity: the item being priced.
339  * currency: the denomination of the value of the item being priced.
340  * value: the value of the item being priced.
341  * time: the time the price was valid.
342  * source: a string describing the source of the quote. These strings will be something like this:
343  "Finance::Quote", "user:misc", "user:foo", etc. If the quote came from a user, as a matter of policy,
344  you *must* prefix the string you give with "user:". For now, the only other reserved values are
345  "Finance::Quote" and "old-file-import". Any string used must be added to the source_list array in
346  dialog-price-edit-db.c so that it can be properly translated. (There are unfortunately many strings
347  in users' databases, so this string must be translated on output instead of always being used in untranslated form).
348  * type: the type of quote - types possible right now are bid, ask, last, nav, and
349  unknown.Each price in the database represents an "instantaneous" quote for a given
350  commodity with respect to another commodity.
351  For example, a given price might represent the value of LNUX in USD on 2001-02-03.
352 
353  See also https://code.gnucash.org/docs/head/group__Price.html
354  '''
355  _new_instance = 'gnc_price_create'
356 GncPrice.add_methods_with_prefix('gnc_price_')
357 
358 
360  '''
361  a simple price database for gnucash.
362  The PriceDB is intended to be a database of price quotes, or more specifically,
363  a database of GNCPrices. For the time being, it is still a fairly simple
364  database supporting only fairly simple queries. It is expected that new
365  queries will be added as needed, and that there is some advantage to delaying
366  complex queries for now in the hope that we get a real DB implementation
367  before they're really needed.
368 
369  Every QofBook contains a GNCPriceDB, accessible via gnc_pricedb_get_db.
370 
371  Definition in file gnc-pricedb.h.
372  See also https://code.gnucash.org/docs/head/gnc-pricedb_8h.html
373  '''
374 
375 GncPriceDB.add_methods_with_prefix('gnc_pricedb_')
376 PriceDB_dict = {
377  'lookup_latest' : GncPrice,
378  'lookup_nearest_in_time64' : GncPrice,
379  'lookup_latest_before_t64' : GncPrice,
380  'convert_balance_latest_price' : GncNumeric,
381  'convert_balance_nearest_price_t64' : GncNumeric,
382  }
383 methods_return_instance(GncPriceDB,PriceDB_dict)
384 GncPriceDB.get_prices = method_function_returns_instance_list(
385  GncPriceDB.get_prices, GncPrice )
386 
387 
389 
391  """A CommodityTable provides a way to store and lookup commodities.
392  Commodities are primarily currencies, but other tradable things such as
393  stocks, mutual funds, and material substances are possible.
394 
395  Users of this library should not create their own CommodityTable, instead
396  the get_table method from the Book class should be used.
397 
398  This table is automatically populated with the GnuCash default commodity's
399  which includes most of the world's currencies.
400  """
401 
402  def _get_namespaces_py(self):
403  return [ns.get_name() for ns in self.get_namespaces_list()]
404 
406  pass
407 
408 class GncLot(GnuCashCoreClass):
409  def GetInvoiceFromLot(self):
410  from gnucash.gnucash_business import Invoice
411  return self.do_lookup_create_oo_instance(
412  gncInvoiceGetInvoiceFromLot, Invoice )
413 
415  """A GnuCash Transaction
416 
417  Consists of at least one (generally two) splits to represent a transaction
418  between two accounts.
419 
420 
421  Has a GetImbalance() method that returns a list of all the imbalanced
422  currencies. Each list item is a two element tuple, the first element is
423  the imbalanced commodity, the second element is the value.
424 
425  Warning, the commodity.get_instance() value can be None when there
426  is no currency set for the transaction.
427  """
428  _new_instance = 'xaccMallocTransaction'
429  def GetNthSplit(self, n):
430  return self.GetSplitList().pop(n)
431 
432  def GetInvoiceFromTxn(self):
433  from gnucash.gnucash_business import Transaction
434  return self.do_lookup_create_oo_instance(
435  gncInvoiceGetInvoiceFromTxn, Transaction )
436 
437 def decorate_monetary_list_returning_function(orig_function):
438  def new_function(self, *args):
439  """decorate function that returns list of gnc_monetary to return tuples of GncCommodity and GncNumeric
440 
441  Args:
442  *args: Variable length argument list. Will get passed to orig_function
443 
444  Returns:
445  array of tuples: (GncCommodity, GncNumeric)
446 
447  ToDo:
448  Maybe this function should better reside in module function_class (?)"""
449  # warning, item.commodity has been shown to be None
450  # when the transaction doesn't have a currency
451  return [(GncCommodity(instance=item.commodity),
452  GncNumeric(instance=item.value))
453  for item in orig_function(self, *args) ]
454  return new_function
455 
457  """A GnuCash Split
458 
459  The most basic representation of a movement of currency from one account to
460  another.
461  """
462  _new_instance = 'xaccMallocSplit'
463 
465  """A GnuCash Account.
466 
467  A fundamental entity in accounting, an Account provides representation
468  for a financial object, such as a ACCT_TYPE_BANK account, an
469  ACCT_TYPE_ASSET (like a building),
470  a ACCT_TYPE_LIABILITY (such as a bank loan), a summary of some type of
471  ACCT_TYPE_EXPENSE, or a summary of some source of ACCT_TYPE_INCOME .
472 
473  The words in upper case are the constants that GnuCash and this library uses
474  to describe account type. Here is the full list:
475  ACCT_TYPE_ASSET, ACCT_TYPE_BANK, ACCT_TYPE_CASH, ACCT_TYPE_CHECKING, \
476  ACCT_TYPE_CREDIT, ACCT_TYPE_EQUITY, ACCT_TYPE_EXPENSE, ACCT_TYPE_INCOME, \
477  ACCT_TYPE_LIABILITY, ACCT_TYPE_MUTUAL, ACCT_TYPE_PAYABLE, \
478  ACCT_TYPE_RECEIVABLE, ACCT_TYPE_STOCK, ACCT_TYPE_ROOT, ACCT_TYPE_TRADING
479 
480  These are not strings, they are attributes you can import from this
481  module
482  """
483  _new_instance = 'xaccMallocAccount'
484 
486  _new_instance = 'guid_new_return'
487 
488 # Session
489 Session.add_constructor_and_methods_with_prefix('qof_session_', 'new')
490 
491 def one_arg_default_none(function):
492  return default_arguments_decorator(function, None, None)
493 Session.decorate_functions(one_arg_default_none, "load", "save")
494 
495 Session.decorate_functions( Session.raise_backend_errors_after_call,
496  "begin", "load", "save", "end")
497 Session.get_book = method_function_returns_instance(
498  Session.get_book, Book )
499 
500 Session.book = property( Session.get_book )
501 
502 # import all of the session backend error codes into this module
503 this_module_dict = globals()
504 for error_name, error_value, error_name_after_prefix in \
505  extract_attributes_with_prefix(gnucash_core_c, 'ERR_'):
506  this_module_dict[ error_name ] = error_value
507 
508 #backend error codes used for reverse lookup
509 backend_error_dict = {}
510 for error_name, error_value, error_name_after_prefix in \
511  extract_attributes_with_prefix(gnucash_core_c, 'ERR_'):
512  backend_error_dict[ error_value ] = error_name
513 
514 # GncNumeric denominator computation schemes
515 # Used for the denom argument in arithmetic functions like GncNumeric.add
516 from gnucash.gnucash_core_c import GNC_DENOM_AUTO
517 
518 # GncNumeric rounding instructions
519 # used for the how argument in arithmetic functions like GncNumeric.add
520 from gnucash.gnucash_core_c import \
521  GNC_HOW_RND_FLOOR, GNC_HOW_RND_CEIL, GNC_HOW_RND_TRUNC, \
522  GNC_HOW_RND_PROMOTE, GNC_HOW_RND_ROUND_HALF_DOWN, \
523  GNC_HOW_RND_ROUND_HALF_UP, GNC_HOW_RND_ROUND, GNC_HOW_RND_NEVER
524 
525 # GncNumeric denominator types
526 # used for the how argument in arithmetic functions like GncNumeric.add
527 from gnucash.gnucash_core_c import \
528  GNC_HOW_DENOM_EXACT, GNC_HOW_DENOM_REDUCE, GNC_HOW_DENOM_LCD, \
529  GNC_HOW_DENOM_FIXED
530 
531 # import account types
532 from gnucash.gnucash_core_c import \
533  ACCT_TYPE_ASSET, ACCT_TYPE_BANK, ACCT_TYPE_CASH, ACCT_TYPE_CHECKING, \
534  ACCT_TYPE_CREDIT, ACCT_TYPE_EQUITY, ACCT_TYPE_EXPENSE, ACCT_TYPE_INCOME, \
535  ACCT_TYPE_LIABILITY, ACCT_TYPE_MUTUAL, ACCT_TYPE_PAYABLE, \
536  ACCT_TYPE_RECEIVABLE, ACCT_TYPE_STOCK, ACCT_TYPE_ROOT, ACCT_TYPE_TRADING
537 
538 #Book
539 Book.add_constructor_and_methods_with_prefix('qof_book_', 'new')
540 Book.add_method('gnc_book_get_root_account', 'get_root_account')
541 Book.add_method('gnc_book_set_root_account', 'set_root_account')
542 Book.add_method('gnc_commodity_table_get_table', 'get_table')
543 Book.add_method('gnc_pricedb_get_db', 'get_price_db')
544 Book.add_method('qof_book_increment_and_format_counter', 'increment_and_format_counter')
545 
546 #Functions that return Account
547 Book.get_root_account = method_function_returns_instance(
548  Book.get_root_account, Account )
549 #Functions that return GncCommodityTable
550 Book.get_table = method_function_returns_instance(
551  Book.get_table, GncCommodityTable )
552 #Functions that return GNCPriceDB
553 Book.get_price_db = method_function_returns_instance(
554  Book.get_price_db, GncPriceDB)
555 
556 # GncNumeric
557 GncNumeric.add_constructor_and_methods_with_prefix('gnc_numeric_', 'create')
558 
559 gncnumeric_dict = {
560  'same' : GncNumeric,
561  'add' : GncNumeric,
562  'sub' : GncNumeric,
563  'mul' : GncNumeric,
564  'div' : GncNumeric,
565  'neg' : GncNumeric,
566  'abs' : GncNumeric,
567  'add_fixed' : GncNumeric,
568  'sub_fixed' : GncNumeric,
569  'convert' : GncNumeric,
570  'reduce' : GncNumeric
571  }
572 methods_return_instance(GncNumeric, gncnumeric_dict)
573 
574 # GncCommodity
575 GncCommodity.add_constructor_and_methods_with_prefix('gnc_commodity_', 'new')
576 #Functions that return GncCommodity
577 GncCommodity.clone = method_function_returns_instance(
578  GncCommodity.clone, GncCommodity )
579 
580 # GncCommodityTable
581 GncCommodityTable.add_methods_with_prefix('gnc_commodity_table_')
582 commoditytable_dict = {
583  'lookup' : GncCommodity,
584  'lookup_unique' : GncCommodity,
585  'find_full' : GncCommodity,
586  'insert' : GncCommodity,
587  'add_namespace': GncCommodityNamespace,
588  'find_namespace': GncCommodityNamespace,
589  }
590 methods_return_instance(GncCommodityTable, commoditytable_dict)
591 
592 methods_return_instance_lists(
593  GncCommodityTable, { 'get_namespaces_list': GncCommodityNamespace,
594  'get_commodities': GncCommodity,
595  'get_quotable_commodities': GncCommodity,
596 
597  } )
598 setattr(GncCommodityTable, 'get_namespaces', getattr(GncCommodityTable, '_get_namespaces_py'))
599 
600 # GncCommodityNamespace
601 GncCommodityNamespace.add_methods_with_prefix('gnc_commodity_namespace_')
602 GncCommodityNamespace.get_commodity_list = \
603  method_function_returns_instance_list(
604  GncCommodityNamespace.get_commodity_list, GncCommodity )
605 
606 # GncLot
607 GncLot.add_constructor_and_methods_with_prefix('gnc_lot_', 'new')
608 
609 gnclot_dict = {
610  'get_account' : Account,
611  'get_book' : Book,
612  'get_earliest_split' : Split,
613  'get_latest_split' : Split,
614  'get_balance' : GncNumeric,
615  'lookup' : GncLot,
616  'make_default' : GncLot
617  }
618 methods_return_instance(GncLot, gnclot_dict)
619 
620 # Transaction
621 Transaction.add_methods_with_prefix('xaccTrans')
622 Transaction.add_method('gncTransGetGUID', 'GetGUID')
623 
624 Transaction.add_method('xaccTransGetDescription', 'GetDescription')
625 Transaction.add_method('xaccTransDestroy', 'Destroy')
626 
627 trans_dict = {
628  'GetSplit': Split,
629  'FindSplitByAccount': Split,
630  'Clone': Transaction,
631  'Reverse': Transaction,
632  'GetReversedBy': Transaction,
633  'GetImbalanceValue': GncNumeric,
634  'GetAccountValue': GncNumeric,
635  'GetAccountAmount': GncNumeric,
636  'GetAccountConvRate': GncNumeric,
637  'GetAccountBalance': GncNumeric,
638  'GetCurrency': GncCommodity,
639  'GetGUID': GUID
640  }
641 
642 methods_return_instance(Transaction, trans_dict)
643 methods_return_instance_lists(
644  Transaction, { 'GetSplitList': Split,
645  })
646 Transaction.decorate_functions(
647  decorate_monetary_list_returning_function, 'GetImbalance')
648 
649 # Split
650 Split.add_methods_with_prefix('xaccSplit')
651 Split.add_method('gncSplitGetGUID', 'GetGUID')
652 Split.add_method('xaccSplitDestroy', 'Destroy')
653 
654 split_dict = {
655  'GetBook': Book,
656  'GetAccount': Account,
657  'GetParent': Transaction,
658  'Lookup': Split,
659  'GetOtherSplit': Split,
660  'GetAmount': GncNumeric,
661  'GetValue': GncNumeric,
662  'GetSharePrice': GncNumeric,
663  'ConvertAmount': GncNumeric,
664  'GetBaseValue': GncNumeric,
665  'GetBalance': GncNumeric,
666  'GetClearedBalance': GncNumeric,
667  'GetReconciledBalance': GncNumeric,
668  'VoidFormerAmount': GncNumeric,
669  'VoidFormerValue': GncNumeric,
670  'GetGUID': GUID
671  }
672 methods_return_instance(Split, split_dict)
673 
674 Split.account = property( Split.GetAccount, Split.SetAccount )
675 Split.parent = property( Split.GetParent, Split.SetParent )
676 
677 # Account
678 Account.add_methods_with_prefix('xaccAccount')
679 Account.add_methods_with_prefix('gnc_account_')
680 Account.add_method('gncAccountGetGUID', 'GetGUID')
681 Account.add_method('xaccAccountGetPlaceholder', 'GetPlaceholder')
682 
683 account_dict = {
684  'get_book' : Book,
685  'Lookup' : Account,
686  'get_parent' : Account,
687  'get_root' : Account,
688  'nth_child' : Account,
689  'lookup_by_code' : Account,
690  'lookup_by_name' : Account,
691  'lookup_by_full_name' : Account,
692  'FindTransByDesc' : Transaction,
693  'FindSplitByDesc' : Split,
694  'GetBalance' : GncNumeric,
695  'GetClearedBalance' : GncNumeric,
696  'GetReconciledBalance' : GncNumeric,
697  'GetPresentBalance' : GncNumeric,
698  'GetProjectedMinimumBalance' : GncNumeric,
699  'GetBalanceAsOfDate' : GncNumeric,
700  'ConvertBalanceToCurrency' : GncNumeric,
701  'ConvertBalanceToCurrencyAsOfDate' : GncNumeric,
702  'GetBalanceInCurrency' : GncNumeric,
703  'GetClearedBalanceInCurrency' : GncNumeric,
704  'GetReconciledBalanceInCurrency' : GncNumeric,
705  'GetPresentBalanceInCurrency' : GncNumeric,
706  'GetProjectedMinimumBalanceInCurrency' : GncNumeric,
707  'GetBalanceAsOfDateInCurrency' : GncNumeric,
708  'GetBalanceChangeForPeriod' : GncNumeric,
709  'GetCommodity' : GncCommodity,
710  'GetGUID': GUID
711  }
712 methods_return_instance(Account, account_dict)
713 methods_return_instance_lists(
714  Account, { 'GetSplitList': Split,
715  'get_children': Account,
716  'get_children_sorted': Account,
717  'get_descendants': Account,
718  'get_descendants_sorted': Account
719  })
720 Account.name = property( Account.GetName, Account.SetName )
721 
722 #GUID
723 GUID.add_methods_with_prefix('guid_')
724 GUID.add_method('xaccAccountLookup', 'AccountLookup')
725 GUID.add_method('xaccTransLookup', 'TransLookup')
726 GUID.add_method('xaccSplitLookup', 'SplitLookup')
727 
728 
729 GUID.add_method('guid_to_string', 'to_string')
730 #GUID.add_method('string_to_guid', 'string_to_guid')
731 
732 guid_dict = {
733  'copy' : GUID,
734  'TransLookup': Transaction,
735  'AccountLookup': Account,
736  'SplitLookup': Split
737  }
738 methods_return_instance(GUID, guid_dict)
739 
740 #GUIDString
742  pass
743 
744 GUIDString.add_constructor_and_methods_with_prefix('string_', 'to_guid')
745 
746 #Query
747 from gnucash.gnucash_core_c import \
748  QOF_QUERY_AND, \
749  QOF_QUERY_OR, \
750  QOF_QUERY_NAND, \
751  QOF_QUERY_NOR, \
752  QOF_QUERY_XOR
753 
754 from gnucash.gnucash_core_c import \
755  QOF_STRING_MATCH_NORMAL, \
756  QOF_STRING_MATCH_CASEINSENSITIVE
757 
758 from gnucash.gnucash_core_c import \
759  QOF_COMPARE_LT, \
760  QOF_COMPARE_LTE, \
761  QOF_COMPARE_EQUAL, \
762  QOF_COMPARE_GT, \
763  QOF_COMPARE_GTE, \
764  QOF_COMPARE_NEQ
765 
766 from gnucash.gnucash_core_c import \
767  INVOICE_TYPE
768 
769 from gnucash.gnucash_core_c import \
770  INVOICE_IS_PAID
771 
773 
774  def search_for(self, obj_type):
775  """Set search_for to obj_type
776 
777  calls qof_query_search_for. Buffers search string for queries lifetime.
778  @see https://bugs.gnucash.org/show_bug.cgi?id=796137"""
779  self.__search_for_buf = obj_type
780  self._search_for(self.__search_for_buf)
781 
782 Query.add_constructor_and_methods_with_prefix('qof_query_', 'create', exclude=["qof_query_search_for"])
783 
784 Query.add_method('qof_query_set_book', 'set_book')
785 Query.add_method('qof_query_search_for', '_search_for')
786 Query.add_method('qof_query_run', 'run')
787 Query.add_method('qof_query_add_term', 'add_term')
788 Query.add_method('qof_query_add_boolean_match', 'add_boolean_match')
789 Query.add_method('qof_query_add_guid_list_match', 'add_guid_list_match')
790 Query.add_method('qof_query_add_guid_match', 'add_guid_match')
791 Query.add_method('qof_query_destroy', 'destroy')
792 
794  pass
795 
796 QueryStringPredicate.add_constructor_and_methods_with_prefix(
797  'qof_query_','string_predicate')
798 
800  pass
801 
802 QueryBooleanPredicate.add_constructor_and_methods_with_prefix(
803  'qof_query_', 'boolean_predicate')
804 
806  pass
807 
808 QueryInt32Predicate.add_constructor_and_methods_with_prefix(
809  'qof_query_', 'int32_predicate')
810 
812  pass
813 
814 QueryDatePredicate.add_constructor_and_methods_with_prefix(
815  'qof_query_', 'date_predicate', exclude=["qof_query_date_predicate_get_date"])
816 QueryDatePredicate.add_method('qof_query_date_predicate_get_date', 'get_date')
817 
819  pass
820 
821 QueryGuidPredicate.add_constructor_and_methods_with_prefix(
822  'qof_query_', 'guid_predicate')
gnc_numeric double_to_gnc_numeric(double in, gint64 denom, gint how)
Convert a floating-point number to a gnc_numeric.
def search_for(self, obj_type)
def __init__(self, book_uri=None, ignore_lock=False, is_new=False, force_new=False)
Definition: gnucash_core.py:78
gchar * gnc_numeric_to_string(gnc_numeric n)
Convert to string.
gboolean string_to_gnc_numeric(const gchar *str, gnc_numeric *n)
Read a gnc_numeric from str, skipping any leading whitespace.
def BillNextID(self, vendor)
def raise_backend_errors(self, called_function="qof_session function")
def do_lookup_create_oo_instance(self, lookup_function, cls, args)
Definition: gnucash_core.py:52
def InvoiceNextID(self, customer)
def __init__(self, args, kargs)
def raise_backend_errors_after_call(function)