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