def get_account_by_guid(acct, guid): for a in acct.get_descendants(): if not isinstance(a, Account): # Older versions of GnuCash just used a pointer to an Account here. a = Account(instance=a) if a.GetGUID().to_string() == guid: return a return None
def get_accounts(root, list=None): if list is None: list = [] for child in root.get_children(): account = Account(instance=child) if not account.get_children(): list.append(account) get_accounts(account, list) return list
def find_account(account, name, account_list=None): """Recursively searches full names of account and descendents returns a list of accounts which contain name. options: account: account to start search in. name: name to search for. account_list: (optional) list to append accounts to. """ if not account_list: account_list = [] for child in account.get_children(): if type(child) != Account: child = Account(instance=child) account_list = find_account(child, name, account_list) account_name = account.GetName() if name in account_name: account_list.append(account) return account_list
def _recursiveCopyAccounts(session, session_new, account, account_new, commodtable): attributes = [ 'Hidden', 'ReconcileChildrenStatus', 'TaxUSCode', 'Code', 'LastNum', 'TaxUSCopyNumber', 'Color', 'TaxUSPayerNameSource', 'Name', 'Type', 'NonStdSCU', 'Description', 'Notes', 'SortOrder', 'Filter', 'Placeholder', 'TaxRelated' ] for acc in account.get_children(): acc_new = Account(session_new.book) account_new.append_child(acc_new) _recursiveCopyAccounts(session, session_new, acc, acc_new, commodtable) for attrib in attributes: getattr(account_new, 'Set' + attrib)(getattr(account, 'Get' + attrib)()) # copy commodity orig_commodity = account.GetCommodity() if orig_commodity: namespace = orig_commodity.get_namespace() mnemonic = orig_commodity.get_mnemonic() new_commodity = commodtable.lookup(namespace, mnemonic) account_new.SetCommodity(new_commodity)
def test_assignlots(self): abc = GncCommodity(self.book, 'ABC Fund', 'COMMODITY','ABC','ABC',100000) self.table.insert(abc) self.account.SetCommodity(abc) other = Account(self.book) other.SetCommodity(self.currency) tx = Transaction(self.book) tx.BeginEdit() tx.SetCurrency(self.currency) tx.SetDateEnteredSecs(datetime.now()) tx.SetDatePostedSecs(datetime.now()) s1a = Split(self.book) s1a.SetParent(tx) s1a.SetAccount(self.account) s1a.SetAmount(GncNumeric(1.3)) s1a.SetValue(GncNumeric(100.0)) s1b = Split(self.book) s1b.SetParent(tx) s1b.SetAccount(other) s1b.SetAmount(GncNumeric(-100.0)) s1b.SetValue(GncNumeric(-100.0)) s2a = Split(self.book) s2a.SetParent(tx) s2a.SetAccount(self.account) s2a.SetAmount(GncNumeric(-1.3)) s2a.SetValue(GncNumeric(-100.0)) s2b = Split(self.book) s2b.SetParent(tx) s2b.SetAccount(other) s2b.SetAmount(GncNumeric(100.0)) s2b.SetValue(GncNumeric(100.0)) tx.CommitEdit() self.account.ScrubLots() self.assertEqual(len(self.account.GetLotList()),1)
def recursivly_build_account_tree(original_parent_account, new_parent_account, new_book, new_commodity_table, opening_balance_per_currency, account_types_to_open): for child in original_parent_account.get_children(): original_account = child new_account = Account(new_book) # attach new account to its parent new_parent_account.append_child(new_account) # copy simple attributes for attribute in ('Name', 'Type', 'Description', 'Notes', 'Code', 'TaxRelated', 'Placeholder'): # new_account.SetAttribute( original_account.GetAttribute() ) getattr(new_account, 'Set' + attribute)(getattr(original_account, 'Get' + attribute)()) # copy commodity orig_commodity = original_account.GetCommodity() namespace = orig_commodity.get_namespace() mnemonic = orig_commodity.get_mnemonic() new_commodity = new_commodity_table.lookup(namespace, mnemonic) if new_commodity == None: new_commodity = orig_commodity.clone(new_book) new_commodity_table.insert(new_commodity) new_account.SetCommodity(new_commodity) record_opening_balance( original_account, new_account, new_book, opening_balance_per_currency, (namespace, mnemonic), ) recursivly_build_account_tree(original_account, new_account, new_book, new_commodity_table, opening_balance_per_currency, account_types_to_open)
def find_or_make_account(account_tuple, root_account, book, currency): current_account_name, account_path = account_tuple[0], account_tuple[1:] current_account = root_account.lookup_by_name(current_account_name) if current_account == None: current_account = Account(book) current_account.SetName(current_account_name) current_account.SetCommodity(currency) root_account.append_child(current_account) if len(account_path) > 0: return find_or_make_account(account_path, current_account, book, currency) else: account_commod = current_account.GetCommodity() if (account_commod.get_mnemonic(), account_commod.get_namespace() ) == \ (currency.get_mnemonic(), currency.get_namespace()) : return current_account else: return None
def setUp(self): BookSession.setUp(self) self.today = datetime.today() self.bank = Account(self.book) self.bank.SetType(ACCT_TYPE_BANK) self.bank.SetCommodity(self.currency) self.income = Account(self.book) self.income.SetType(ACCT_TYPE_INCOME) self.income.SetCommodity(self.currency) self.receivable = Account(self.book) self.receivable.SetType(ACCT_TYPE_RECEIVABLE) self.receivable.SetCommodity(self.currency) self.customer = Customer(self.book,'CustomerID',self.currency) self.vendor = Vendor(self.book,'VendorID',self.currency) self.employee = Employee(self.book,'EmployeeID',self.currency) self.job = Job(self.book,'JobID',self.customer) self.invoice = Invoice(self.book,'InvoiceID',self.currency,self.customer) self.invoice.SetDateOpened(self.today) entry = Entry(self.book) entry.SetDate(self.today) entry.SetDescription("Some income") entry.SetQuantity(GncNumeric(1)) entry.SetInvAccount(self.income) entry.SetInvPrice(GncNumeric(100)) self.invoice.AddEntry(entry) self.invoice.PostToAccount(self.receivable, self.today, self.today, "", True, False)
def new_tax(root, book, USD, row): if row['type'] == 'Sales Tax Item': tablename = row['item'] parent = root.lookup_by_name(row['account']) account = Account(book) parent.append_child(account) account.SetName(tablename) account.SetType(ACCT_TYPE_LIABILITY) account.SetCommodity(USD) rate = gnc_numeric_from(row['rate']) # Skip existing tax table and create new ones try: assert ( not isinstance(book.TaxTableLookupByName(tablename), TaxTable) ) TaxTable(book, tablename, TaxTableEntry(account, True, rate)) except AssertionError: print '"%s" tax table already exists, skipping' \ % tablename # Add method to update rate return 0 return 1
def mark_account_with_code_as_tax_related(account, target_code): """Looks at account to see if it has the target_account_code, if so set the account tax related flag to True and return True. If not, recursively tries to do the same to all children accounts of account. Returns False when recursion fails to find it. """ if account.GetCode() == target_code: account.SetTaxRelated(True) return True else: for child in account.get_children(): child = Account(instance=child) if mark_account_with_code_as_tax_related(child, target_code): return True return False
def createAccounts(book): root_account = book.get_root_account() commodtable = book.get_table() currency = commodtable.lookup("CURRENCY", "EUR") ses.save() print('Create two accounts ("Account A", "Account B")') accountA = Account(book) accountA.SetCommodity(currency) accountA.SetName("Account A") root_account.append_child(accountA) accountB = Account(book) accountB.SetCommodity(currency) accountB.SetName("Account B") root_account.append_child(accountB) #ses.save() return accountA, accountB
def get_accounts(self, ast_parent:Account, asset_acct_name:str, rev_acct:Account): """ Find the proper Asset and Revenue accounts :param ast_parent: Asset account parent :param asset_acct_name: Asset account name :param rev_acct: Revenue account :return: Gnucash account, Gnucash account """ self.logger.print_info('get_accounts()', BLUE) asset_parent = ast_parent # special locations for Trust Revenue and Asset accounts if asset_acct_name == TRUST_AST_ACCT: asset_parent = self.root_acct.lookup_by_name(TRUST) self.logger.print_info("asset_parent = {}".format(asset_parent.GetName())) rev_acct = self.root_acct.lookup_by_name(TRUST_REV_ACCT) self.logger.print_info("MODIFIED rev_acct = {}".format(rev_acct.GetName())) # get the asset account asset_acct = asset_parent.lookup_by_name(asset_acct_name) if asset_acct is None: raise Exception("[164] Could NOT find acct '{}' under parent '{}'" .format(asset_acct_name, asset_parent.GetName())) self.logger.print_info("asset_acct = {}".format(asset_acct.GetName()), color=CYAN) return asset_acct, rev_acct
def find_split_recursive(account, search_string): """Searches account and descendants for Splits containing search_string returns a list of splits that have search_string as part of memo or description of parent transaction. options: account: Account to search in. search_string: String to search for. """ rlist = [] child_account_splits = [] # Get all splits in descendants for child in account.get_children(): if type(child) != Account: child = Account(instance=child) childsplits = find_split_recursive(child, search_string) for split in childsplits: if type(split) != Split: split = Split(instance=split) child_account_splits += childsplits # Get all splits in account splits = account.GetSplitList() for split in splits: if type(split) != Split: split = Split(instance=split) basic_account_splits = find_split(splits, search_string) rlist = child_account_splits + basic_account_splits return rlist
#!/usr/bin/env python3 ## @file # @brief Example Script simple sqlite create # @ingroup python_bindings_examples from gnucash import Session, Account from os.path import abspath from gnucash.gnucash_core_c import ACCT_TYPE_ASSET s = Session('sqlite3://%s' % abspath('test.blob'), is_new=True) # this seems to make a difference in more complex cases s.save() book = s.book root = book.get_root_account() a = Account(book) root.append_child(a) a.SetName('wow') a.SetType(ACCT_TYPE_ASSET) commod_table = book.get_table() a.SetCommodity( commod_table.lookup('CURRENCY', 'CAD') ) s.save() s.end()
#!/usr/bin/env python # Creates a basic set of accounts and a couple of transactions from gnucash import Session, Account, Transaction, Split, GncNumeric FILE_1 = "/tmp/example.gnucash" session = Session("xml:%s" % FILE_1, True) book = session.book root_acct = Account(book) expenses_acct = Account(book) savings_acct = Account(book) opening_acct = Account(book) trans1 = Transaction(book) trans2 = Transaction(book) split1 = Split(book) split3 = Split(book) comm_table = book.get_table() cad = comm_table.lookup("CURRENCY", "CAD") num1 = GncNumeric(4, 1) num2 = GncNumeric(100, 1) #Set new root account book.set_root_account(root_acct) #Set up root account and add sub-accounts root_acct.SetName("Root") root_acct.SetType(13) #ACCT_TYPE_ROOT = 13 root_acct.append_child(expenses_acct)
def setUp(self): BookSession.setUp(self) self.account = Account(self.book)
print "not enough parameters" print "usage: simple_business_create.py {new_book_url}" print "example:" print "gnucash-env python simple_business_create.py sqlite3:///home/blah/blah.gnucash" exit() try: s = Session(argv[1], is_new=True) book = s.book root = book.get_root_account() commod_table = book.get_table() CAD = commod_table.lookup("CURRENCY", "CAD") a = Account(book) root.append_child(a) a.SetName("Assets") a.SetType(ACCT_TYPE_ASSET) a.SetCommodity(CAD) a2 = Account(book) a.append_child(a2) a2.SetName("Receivables") a2.SetType(ACCT_TYPE_RECEIVABLE) a2.SetCommodity(CAD) a3 = Account(book) root.append_child(a3) a3.SetName("Income") a3.SetType(ACCT_TYPE_INCOME)
def test_account(self): ACCT = Account(self.book) ACCT.SetCommodity(self.currency) self.split.SetAccount(ACCT) self.assertTrue(ACCT.Equal(self.split.GetAccount(), True))
#!/usr/bin/env python ## @file # @brief Creates a basic set of accounts and a couple of transactions # @ingroup python_bindings_examples from gnucash import Session, Account, Transaction, Split, GncNumeric FILE_1 = "/tmp/example.gnucash" session = Session("xml://%s" % FILE_1, is_new=True) book = session.book root_acct = Account(book) expenses_acct = Account(book) savings_acct = Account(book) opening_acct = Account(book) trans1 = Transaction(book) trans1.BeginEdit() trans2 = Transaction(book) trans2.BeginEdit() split1 = Split(book) split3 = Split(book) comm_table = book.get_table() cad = comm_table.lookup("CURRENCY", "CAD") num1 = GncNumeric(4, 1) num2 = GncNumeric(100, 1) #Set new root account book.set_root_account(root_acct)
# for a file, simply pass the pathname, for a database you can use # these forms: # mysql://user:password@host/dbname # postgres://user:password@host[:port]/dbname (the port is optional) # # You should try it out with a gnucash file with tranding accounts enabled # and trading accounts disabled session = Session(argv[1]) book = session.book root = book.get_root_account() root.get_instance() commod_tab = session.book.get_table() CAD = commod_tab.lookup("ISO4217", "CAD") USD = commod_tab.lookup("ISO4217", "USD") account = Account(book) account2 = Account(book) root.append_child(account) root.append_child(account2) account.SetCommodity(CAD) account.SetName("blahblah") account.SetType(3) account2.SetCommodity(USD) account2.SetName("blahblahsdfs ") account2.SetType(3) a = Transaction(book) a.BeginEdit() s = Split(book) s.SetParent(a)
def test_findsplit(self): ACCT = Account(self.book) ACCT.SetCommodity(self.currency) self.split.SetAccount( ACCT ) SPLIT = self.trans.FindSplitByAccount( ACCT ) self.assertTrue( SPLIT.Equal(self.split, True, False, False) )
print('not enough parameters') print('usage: simple_business_create.py {new_book_url}') print('example:') print( "python3 simple_business_create.py sqlite3:///home/blah/blah.gnucash") exit() try: s = Session(argv[1], SessionOpenMode.SESSION_NEW_STORE) book = s.book root = book.get_root_account() commod_table = book.get_table() CAD = commod_table.lookup('CURRENCY', 'CAD') a = Account(book) root.append_child(a) a.SetName('Assets') a.SetType(ACCT_TYPE_ASSET) a.SetCommodity(CAD) a2 = Account(book) a.append_child(a2) a2.SetName('Receivables') a2.SetType(ACCT_TYPE_RECEIVABLE) a2.SetCommodity(CAD) a3 = Account(book) root.append_child(a3) a3.SetName('Income') a3.SetType(ACCT_TYPE_INCOME)
def test_account(self): ACCT = Account(self.book) self.split.SetAccount(ACCT) self.assertTrue( ACCT.Equal(self.split.GetAccount(), True) )