33 from 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
39 from 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
48 _module = gnucash_core_c
50 def do_lookup_create_oo_instance(self, lookup_function, cls, *args):
51 thing = lookup_function(self.get_instance(), *args)
53 thing = cls(instance=thing)
58 def __init__(self, msg, errors):
59 Exception.__init__(self, msg)
63 """A GnuCash book editing session
65 To commit changes to the session you may need to call save,
66 (this is always the case with the file backend).
68 When you're down with a session you may need to call end()
70 Every Session has a Book in the book attribute, which you'll definitely
71 be interested in, as every GnuCash entity (Transaction, Split, Vendor,
72 Invoice..) is associated with a particular book where it is stored.
75 def __init__(self, book_uri=None, ignore_lock=False, is_new=False,
77 """A convenient constructor that allows you to specify a book URI,
78 begin the session, and load the book.
80 This can give you the power of calling
81 qof_session_new, qof_session_begin, and qof_session_load all in one!
83 book_uri can be None to skip the calls to qof_session_begin and
84 qof_session_load, or it can be a string like "file:/test.xac"
86 qof_session_load is only called if is_new is set to False
88 is_new is passed to qof_session_begin as the argument create,
89 and force_new as the argument force. Is_new will create a new
90 database or file; force will force creation even if it will
91 destroy an existing dataset.
93 ignore_lock is passed to qof_session_begin's argument of the
94 same name and is used to break an existing lock on a dataset.
98 This function can raise a GnuCashBackendException. If it does,
99 you don't need to cleanup and call end() and destroy(), that is handled
100 for you, and the exception is raised.
102 GnuCashCoreClass.__init__(self)
103 if book_uri
is not None:
105 self.begin(book_uri, ignore_lock, is_new, force_new)
111 if book_uri[:3] !=
"xml" or not is_new:
113 except GnuCashBackendException, backend_exception:
119 """Raises a GnuCashBackendException if there are outstanding
122 set called_function to name the function that was last called
127 "call to %s resulted in the "
128 "following errors, %s" % (called_function, backend_error_dict[errors[0]]),
132 """A generator that yields any outstanding QofBackend errors
134 while self.get_error()
is not ERR_BACKEND_NO_ERR:
135 error = self.pop_error()
139 """Returns any accumulated qof backend errors as a tuple
146 """A function decorator that results in a call to
147 raise_backend_errors after execution.
149 def new_function(self, *args):
150 return_value = function(self, *args)
156 """A Book encapsulates all of the GnuCash data, it is the place where
157 all GnuCash entities (Transaction, Split, Vendor, Invoice...), are
158 stored. You'll notice that all of the constructors for those entities
159 need a book to be associated with.
161 The most common way to get a book is through the book property in the
162 Session class, that is, create a session that connects to some storage,
163 such as through 'my_session = Session('file:my_books.xac')', and access
164 the book via the book property, 'my_session.book'
166 If you would like to create a Book without any backing storage, call the
167 Book constructor without any parameters, 'Book()'. You can later merge
168 such a book into a book with actual store by using merge_init.
171 get_root_account -- Returns the root level Account
172 get_table -- Returns a commodity lookup table, of type GncCommodityTable
174 def InvoiceLookup(self, guid):
175 from gnucash_business
import Invoice
177 gncInvoiceLookup, Invoice, guid.get_instance() )
179 def EntryLookup(self, guid):
180 from gnucash_business
import Entry
182 gncEntryLookup, Entry, guid.get_instance() )
184 def CustomerLookup(self, guid):
185 from gnucash_business
import Customer
187 gncCustomerLookup, Customer, guid.get_instance())
189 def JobLookup(self, guid):
190 from gnucash_business
import Job
192 gncJobLookup, Job, guid.get_instance() )
194 def VendorLookup(self, guid):
195 from gnucash_business
import Vendor
197 gncVendorLookup, Vendor, guid.get_instance() )
199 def EmployeeLookup(self, guid):
200 from gnucash_business
import Employee
202 gncEmployeeLookup, Employee, guid.get_instance() )
204 def TaxTableLookup(self, guid):
205 from gnucash_business
import TaxTable
207 gncTaxTableLookup, TaxTable, guid.get_instance() )
209 def TaxTableLookupByName(self, name):
210 from gnucash_business
import TaxTable
212 gncTaxTableLookupByName, TaxTable, name)
214 def TaxTableGetTables(self):
215 from gnucash_business
import TaxTable
216 return [ TaxTable(instance=item)
for item
in gncTaxTableGetTables(self.instance) ]
218 def BillLookupByID(self, id):
219 from gnucash_business
import Bill
221 gnc_search_bill_on_id, Bill, id)
223 def InvoiceLookupByID(self, id):
224 from gnucash_business
import Invoice
226 gnc_search_invoice_on_id, Invoice, id)
228 def CustomerLookupByID(self, id):
229 from gnucash_business
import Customer
231 gnc_search_customer_on_id, Customer, id)
233 def VendorLookupByID(self, id):
234 from gnucash_business
import Vendor
236 gnc_search_vendor_on_id, Vendor, id)
239 ''' Return the next invoice ID.
240 This works but I'm not entirely happy with it. FIX ME'''
241 from gnucash.gnucash_core_c
import gncInvoiceNextID
242 return gncInvoiceNextID(self.get_instance(),customer.GetEndOwner().get_instance()[1])
245 ''' Return the next Bill ID. '''
246 from gnucash.gnucash_core_c
import gncInvoiceNextID
247 return gncInvoiceNextID(self.get_instance(),vendor.GetEndOwner().get_instance()[1])
250 ''' Return the next Customer ID. '''
251 from gnucash.gnucash_core_c
import gncCustomerNextID
252 return gncCustomerNextID(self.get_instance())
255 ''' Return the next Vendor ID. '''
256 from gnucash.gnucash_core_c
import gncVendorNextID
257 return gncVendorNextID(self.get_instance())
260 """Object used by GnuCash to store all numbers. Always consists of a
261 numerator and denominator.
263 The constants GNC_DENOM_AUTO,
264 GNC_HOW_RND_FLOOR, GNC_HOW_RND_CEIL, GNC_HOW_RND_TRUNC,
265 GNC_HOW_RND_PROMOTE, GNC_HOW_RND_ROUND_HALF_DOWN,
266 GNC_HOW_RND_ROUND_HALF_UP, GNC_HOW_RND_ROUND, GNC_HOW_RND_NEVER,
267 GNC_HOW_DENOM_EXACT, GNC_HOW_DENOM_REDUCE, GNC_HOW_DENOM_LCD,
268 and GNC_HOW_DENOM_FIXED are available for arithmetic
269 functions like GncNumeric.add
271 Look at gnc-numeric.h to see how to use these
275 """Constructor that allows you to set the numerator and denominator or
276 leave them blank with a default value of 0 (not a good idea since there
277 is currently no way to alter the value after instantiation)
279 GnuCashCoreClass.__init__(self, num, denom, **kargs)
287 """Returns a human readable numeric value string as UTF8."""
288 if self.denom() == 0:
289 return "Division by zero"
291 value_float = self.to_double()
292 value_str =
u"{0:.{1}f}".format(value_float,2)
296 """returns a human readable numeric value string as bytes."""
297 return unicode(self).encode(
'utf-8')
301 Each priceEach price in the database represents an "instantaneous"
302 quote for a given commodity with respect to another commodity.
303 For example, a given price might represent the value of LNUX in USD on 2001-02-03.
306 * commodity: the item being priced.
307 * currency: the denomination of the value of the item being priced.
308 * value: the value of the item being priced.
309 * time: the time the price was valid.
310 * source: a string describing the source of the quote. These strings will be something like this:
311 "Finance::Quote", "user:misc", "user:foo", etc. If the quote came from a user, as a matter of policy,
312 you *must* prefix the string you give with "user:". For now, the only other reserved values are
313 "Finance::Quote" and "old-file-import". Any string used must be added to the source_list array in
314 dialog-price-edit-db.c so that it can be properly translated. (There are unfortunately many strings
315 in users' databases, so this string must be translated on output instead of always being used in untranslated form).
316 * type: the type of quote - types possible right now are bid, ask, last, nav, and
317 unknown.Each price in the database represents an "instantaneous" quote for a given
318 commodity with respect to another commodity.
319 For example, a given price might represent the value of LNUX in USD on 2001-02-03.
321 See also http://code.gnucash.org/docs/head/group__Price.html
324 GncPrice.add_methods_with_prefix(
'gnc_price_')
329 a simple price database for gnucash.
330 The PriceDB is intended to be a database of price quotes, or more specifically,
331 a database of GNCPrices. For the time being, it is still a fairly simple
332 database supporting only fairly simple queries. It is expected that new
333 queries will be added as needed, and that there is some advantage to delaying
334 complex queries for now in the hope that we get a real DB implementation
335 before they're really needed.
337 Every QofBook contains a GNCPriceDB, accessible via gnc_pricedb_get_db.
339 Definition in file gnc-pricedb.h.
340 See also http://code.gnucash.org/docs/head/gnc-pricedb_8h.html
343 GncPriceDB.add_methods_with_prefix(
'gnc_pricedb_')
345 'lookup_latest' : GncPrice,
346 'lookup_nearest_in_time' : GncPrice,
347 'lookup_latest_before' : GncPrice,
348 'convert_balance_latest_price' : GncNumeric,
349 'convert_balance_nearest_price' : GncNumeric,
351 methods_return_instance(GncPriceDB,PriceDB_dict)
352 GncPriceDB.get_prices = method_function_returns_instance_list(
353 GncPriceDB.get_prices, GncPrice )
359 """A CommodityTable provides a way to store and lookup commodities.
360 Commodities are primarily currencies, but other tradable things such as
361 stocks, mutual funds, and material substances are possible.
363 Users of this library should not create their own CommodityTable, instead
364 the get_table method from the Book class should be used.
366 This table is automatically populated with the GnuCash default commodity's
367 which includes most of the world's currencies.
376 def GetInvoiceFromLot(self):
377 from gnucash_business
import Invoice
378 return self.do_lookup_create_oo_instance(
379 gncInvoiceGetInvoiceFromLot, Invoice )
382 """A GnuCash Transaction
384 Consists of at least one (generally two) splits to represent a transaction
385 between two accounts.
388 Has a GetImbalance() method that returns a list of all the imbalanced
389 currencies. Each list item is a two element tuple, the first element is
390 the imbalanced commodity, the second element is the value.
392 Warning, the commodity.get_instance() value can be None when there
393 is no currency set for the transaction.
395 _new_instance =
'xaccMallocTransaction'
396 def GetNthSplit(self, n):
397 return self.GetSplitList().pop(n)
399 def GetInvoiceFromTxn(self):
400 from gnucash_business
import Transaction
402 gncInvoiceGetInvoiceFromTxn, Transaction )
404 def decorate_monetary_list_returning_function(orig_function):
405 def new_function(self):
410 for item
in orig_function(self) ]
416 The most basic representation of a movement of currency from one account to
419 _new_instance =
'xaccMallocSplit'
422 """A GnuCash Account.
424 A fundamental entity in accounting, an Account provides representation
425 for a financial object, such as a ACCT_TYPE_BANK account, an
426 ACCT_TYPE_ASSET (like a building),
427 a ACCT_TYPE_LIABILITY (such as a bank loan), a summary of some type of
428 ACCT_TYPE_EXPENSE, or a summary of some source of ACCT_TYPE_INCOME .
430 The words in upper case are the constants that GnuCash and this library uses
431 to describe account type. Here is the full list:
432 ACCT_TYPE_ASSET, ACCT_TYPE_BANK, ACCT_TYPE_CASH, ACCT_TYPE_CHECKING, \
433 ACCT_TYPE_CREDIT, ACCT_TYPE_EQUITY, ACCT_TYPE_EXPENSE, ACCT_TYPE_INCOME, \
434 ACCT_TYPE_LIABILITY, ACCT_TYPE_MUTUAL, ACCT_TYPE_PAYABLE, \
435 ACCT_TYPE_RECEIVABLE, ACCT_TYPE_STOCK, ACCT_TYPE_ROOT, ACCT_TYPE_TRADING
437 These are not strings, they are attributes you can import from this
440 _new_instance =
'xaccMallocAccount'
443 _new_instance =
'guid_new_return'
446 Session.add_constructor_and_methods_with_prefix(
'qof_session_',
'new')
448 def one_arg_default_none(function):
449 return default_arguments_decorator(function,
None,
None)
450 Session.decorate_functions(one_arg_default_none,
"load",
"save")
452 Session.decorate_functions( Session.raise_backend_errors_after_call,
453 "begin",
"load",
"save",
"end")
454 Session.get_book = method_function_returns_instance(
455 Session.get_book, Book )
457 Session.book = property( Session.get_book )
460 this_module_dict = globals()
461 for error_name, error_value, error_name_after_prefix
in \
462 extract_attributes_with_prefix(gnucash_core_c,
'ERR_'):
463 this_module_dict[ error_name ] = error_value
466 backend_error_dict = {}
467 for error_name, error_value, error_name_after_prefix
in \
468 extract_attributes_with_prefix(gnucash_core_c,
'ERR_'):
469 backend_error_dict[ error_value ] = error_name
473 from gnucash.gnucash_core_c
import GNC_DENOM_AUTO
477 from gnucash.gnucash_core_c
import \
478 GNC_HOW_RND_FLOOR, GNC_HOW_RND_CEIL, GNC_HOW_RND_TRUNC, \
479 GNC_HOW_RND_PROMOTE, GNC_HOW_RND_ROUND_HALF_DOWN, \
480 GNC_HOW_RND_ROUND_HALF_UP, GNC_HOW_RND_ROUND, GNC_HOW_RND_NEVER
484 from gnucash.gnucash_core_c
import \
485 GNC_HOW_DENOM_EXACT, GNC_HOW_DENOM_REDUCE, GNC_HOW_DENOM_LCD, \
489 from gnucash.gnucash_core_c
import \
490 ACCT_TYPE_ASSET, ACCT_TYPE_BANK, ACCT_TYPE_CASH, ACCT_TYPE_CHECKING, \
491 ACCT_TYPE_CREDIT, ACCT_TYPE_EQUITY, ACCT_TYPE_EXPENSE, ACCT_TYPE_INCOME, \
492 ACCT_TYPE_LIABILITY, ACCT_TYPE_MUTUAL, ACCT_TYPE_PAYABLE, \
493 ACCT_TYPE_RECEIVABLE, ACCT_TYPE_STOCK, ACCT_TYPE_ROOT, ACCT_TYPE_TRADING
496 Book.add_constructor_and_methods_with_prefix(
'qof_book_',
'new')
497 Book.add_method(
'gnc_book_get_root_account',
'get_root_account')
498 Book.add_method(
'gnc_book_set_root_account',
'set_root_account')
499 Book.add_method(
'gnc_commodity_table_get_table',
'get_table')
500 Book.add_method(
'gnc_pricedb_get_db',
'get_price_db')
501 Book.add_method(
'qof_book_increment_and_format_counter',
'increment_and_format_counter')
504 Book.get_root_account = method_function_returns_instance(
505 Book.get_root_account, Account )
507 Book.get_table = method_function_returns_instance(
508 Book.get_table, GncCommodityTable )
510 Book.get_price_db = method_function_returns_instance(
511 Book.get_price_db, GncPriceDB)
514 GncNumeric.add_constructor_and_methods_with_prefix(
'gnc_numeric_',
'create')
524 'add_fixed' : GncNumeric,
525 'sub_fixed' : GncNumeric,
526 'add_with_error' : GncNumeric,
527 'sub_with_error' : GncNumeric,
528 'mul_with_error' : GncNumeric,
529 'div_with_error' : GncNumeric,
530 'convert' : GncNumeric,
531 'reduce' : GncNumeric
533 methods_return_instance(GncNumeric, gncnumeric_dict)
536 GncCommodity.add_constructor_and_methods_with_prefix(
'gnc_commodity_',
'new')
538 GncCommodity.clone = method_function_returns_instance(
539 GncCommodity.clone, GncCommodity )
542 GncCommodityTable.add_methods_with_prefix(
'gnc_commodity_table_')
543 commoditytable_dict = {
544 'lookup' : GncCommodity,
545 'lookup_unique' : GncCommodity,
546 'find_full' : GncCommodity,
547 'insert' : GncCommodity,
548 'add_namespace': GncCommodityNamespace,
549 'find_namespace': GncCommodityNamespace,
551 methods_return_instance(GncCommodityTable, commoditytable_dict)
553 methods_return_instance_lists(
554 GncCommodityTable, {
'get_namespaces': GncCommodityNamespace,
555 'get_namespaces_list': GncCommodityNamespace,
556 'get_commodities': GncCommodity,
557 'get_quotable_commodities': GncCommodity,
562 GncCommodityNamespace.add_methods_with_prefix(
'gnc_commodity_namespace_')
563 GncCommodityNamespace.get_commodity_list = \
564 method_function_returns_instance_list(
565 GncCommodityNamespace.get_commodity_list, GncCommodity )
568 GncLot.add_constructor_and_methods_with_prefix(
'gnc_lot_',
'new')
571 'get_account' : Account,
573 'get_earliest_split' : Split,
574 'get_latest_split' : Split,
575 'get_balance' : GncNumeric,
577 'make_default' : GncLot
579 methods_return_instance(GncLot, gnclot_dict)
582 Transaction.add_methods_with_prefix(
'xaccTrans')
583 Transaction.add_method(
'gncTransGetGUID',
'GetGUID');
585 Transaction.add_method(
'xaccTransGetDescription',
'GetDescription')
586 Transaction.add_method(
'xaccTransDestroy',
'Destroy')
590 'FindSplitByAccount': Split,
591 'Clone': Transaction,
592 'Reverse': Transaction,
593 'GetReversedBy': Transaction,
594 'GetImbalanceValue': GncNumeric,
595 'GetAccountValue': GncNumeric,
596 'GetAccountAmount': GncNumeric,
597 'GetAccountConvRate': GncNumeric,
598 'GetAccountBalance': GncNumeric,
599 'GetCurrency': GncCommodity,
603 methods_return_instance(Transaction, trans_dict)
604 methods_return_instance_lists(
605 Transaction, {
'GetSplitList': Split,
607 Transaction.decorate_functions(
608 decorate_monetary_list_returning_function,
'GetImbalance')
611 Split.add_methods_with_prefix(
'xaccSplit')
612 Split.add_method(
'gncSplitGetGUID',
'GetGUID');
613 Split.add_method(
'xaccSplitDestroy',
'Destroy')
617 'GetAccount': Account,
618 'GetParent': Transaction,
620 'GetOtherSplit': Split,
621 'GetAmount': GncNumeric,
622 'GetValue': GncNumeric,
623 'GetSharePrice': GncNumeric,
624 'ConvertAmount': GncNumeric,
625 'GetBaseValue': GncNumeric,
626 'GetBalance': GncNumeric,
627 'GetClearedBalance': GncNumeric,
628 'GetReconciledBalance': GncNumeric,
629 'VoidFormerAmount': GncNumeric,
630 'VoidFormerValue': GncNumeric,
633 methods_return_instance(Split, split_dict)
635 Split.account = property( Split.GetAccount, Split.SetAccount )
636 Split.parent = property( Split.GetParent, Split.SetParent )
639 Account.add_methods_with_prefix(
'xaccAccount')
640 Account.add_methods_with_prefix(
'gnc_account_')
641 Account.add_method(
'gncAccountGetGUID',
'GetGUID');
642 Account.add_method(
'xaccAccountGetPlaceholder',
'GetPlaceholder')
647 'get_parent' : Account,
648 'get_root' : Account,
649 'nth_child' : Account,
650 'lookup_by_code' : Account,
651 'lookup_by_name' : Account,
652 'lookup_by_full_name' : Account,
653 'FindTransByDesc' : Transaction,
654 'FindSplitByDesc' : Split,
655 'GetBalance' : GncNumeric,
656 'GetClearedBalance' : GncNumeric,
657 'GetReconciledBalance' : GncNumeric,
658 'GetPresentBalance' : GncNumeric,
659 'GetProjectedMinimumBalance' : GncNumeric,
660 'GetBalanceAsOfDate' : GncNumeric,
661 'ConvertBalanceToCurrency' : GncNumeric,
662 'ConvertBalanceToCurrencyAsOfDate' : GncNumeric,
663 'GetBalanceInCurrency' : GncNumeric,
664 'GetClearedBalanceInCurrency' : GncNumeric,
665 'GetReconciledBalanceInCurrency' : GncNumeric,
666 'GetPresentBalanceInCurrency' : GncNumeric,
667 'GetProjectedMinimumBalanceInCurrency' : GncNumeric,
668 'GetBalanceAsOfDateInCurrency' : GncNumeric,
669 'GetBalanceChangeForPeriod' : GncNumeric,
670 'GetCommodity' : GncCommodity,
673 methods_return_instance(Account, account_dict)
674 methods_return_instance_lists(
675 Account, {
'GetSplitList': Split,
676 'get_children': Account,
677 'get_children_sorted': Account,
678 'get_descendants': Account,
679 'get_descendants_sorted': Account
681 Account.name = property( Account.GetName, Account.SetName )
684 GUID.add_methods_with_prefix(
'guid_')
685 GUID.add_method(
'xaccAccountLookup',
'AccountLookup')
686 GUID.add_method(
'xaccTransLookup',
'TransLookup')
687 GUID.add_method(
'xaccSplitLookup',
'SplitLookup')
690 GUID.add_method(
'guid_to_string',
'to_string')
695 'TransLookup': Transaction,
696 'AccountLookup': Account,
699 methods_return_instance(GUID, guid_dict)
705 GUIDString.add_constructor_and_methods_with_prefix(
'string_',
'to_guid')
708 from gnucash_core_c
import \
715 from gnucash_core_c
import \
716 QOF_STRING_MATCH_NORMAL, \
717 QOF_STRING_MATCH_CASEINSENSITIVE
719 from gnucash_core_c
import \
727 from gnucash_core_c
import \
730 from gnucash_core_c
import \
736 Query.add_constructor_and_methods_with_prefix(
'qof_query_',
'create')
738 Query.add_method(
'qof_query_set_book',
'set_book')
739 Query.add_method(
'qof_query_search_for',
'search_for')
740 Query.add_method(
'qof_query_run',
'run')
741 Query.add_method(
'qof_query_add_term',
'add_term')
742 Query.add_method(
'qof_query_add_boolean_match',
'add_boolean_match')
743 Query.add_method(
'qof_query_add_guid_list_match',
'add_guid_list_match')
744 Query.add_method(
'qof_query_add_guid_match',
'add_guid_match')
745 Query.add_method(
'qof_query_destroy',
'destroy')
750 QueryStringPredicate.add_constructor_and_methods_with_prefix(
751 'qof_query_',
'string_predicate')
756 QueryBooleanPredicate.add_constructor_and_methods_with_prefix(
757 'qof_query_',
'boolean_predicate')
762 QueryInt32Predicate.add_constructor_and_methods_with_prefix(
763 'qof_query_',
'int32_predicate')
768 QueryDatePredicate.add_constructor_and_methods_with_prefix(
769 'qof_query_',
'date_predicate')
774 QueryGuidPredicate.add_constructor_and_methods_with_prefix(
775 'qof_query_',
'guid_predicate')
def raise_backend_errors_after_call
def do_lookup_create_oo_instance