def setUp(self): self.domain1 = "gnc.engine" self.domain2 = "gnc.engine.scrub" level = G_LOG_LEVEL_CRITICAL check1 = TestErrorStruct() check1.log_domain = self.domain1 check1.log_level = level check1.msg = "[xaccScrubUtilityGetOrMakeAccount()] No currency specified!" test_add_error(check1) check2 = TestErrorStruct() check2.log_domain = self.domain1 check2.log_level = level check2.msg = "[xaccTransScrubSplits()] Transaction doesn't have a currency!" test_add_error(check2) self.hdlr1 = test_set_list_handler(self.domain1, level, None) check3 = TestErrorStruct() check3.log_domain = "gnc.engine.scrub" check3.log_level = level check3.msg = "[xaccScrubUtilityGetOrMakeAccount()] No currency specified!" self.hdlr2 = test_set_checked_handler(self.domain2, level, check3) BookSession.setUp(self) self.trans = Transaction(self.book) #Evil bug means we must set a split for the transaction before making #any other changes (is slightly useful for later tests) self.split = Split(self.book) self.split.SetParent(self.trans) ############ self.trans.SetCurrency(self.currency)
def setUp(self): BookSession.setUp(self) self.trans = Transaction(self.book) #Evil bug means we must set a split for the transaction before making #any other changes (is slightly useful for later tests) self.split = Split(self.book) self.split.SetParent(self.trans)
def _insert_transaction(session, record, currency, rec_date, account_to, account_from): book = session.book # set currency comm_table = book.get_table() currency = comm_table.lookup("CURRENCY", currency) transaction = gnucash.Transaction(book) transaction.BeginEdit() split_to = Split(book) # TODO - create money representation based on fractions value = GncNumeric(record.value.cents(), 100) split_to.SetValue(value) split_to.SetAccount(account_to) split_to.SetParent(transaction) split_from = Split(book) split_from.SetValue(value.neg()) split_from.SetAccount(account_from) split_from.SetParent(transaction) # set transaction values transaction.SetDate(rec_date.day, rec_date.month, rec_date.year) transaction.SetDescription(record.description) transaction.SetCurrency(currency) transaction.CommitEdit()
def get_splits_without_lot(account=None, split_list=None): """Returns a list of those Splits in split_list or account which do not have an according lot. options: account: (optional) Account to search in. split_list: (optional) List of Splits to search in. one or the other has to be provided. """ if split_list == None: if account == None: return [] else: split_list = account.GetSplitList() rlist = [] for split in split_list: if type(split).__name__ == 'SwigPyObject': split = Split(instance=split) lot = split.GetLot() if lot == None: rlist.append(split) return rlist
def test_equal(self): TRANS = self.trans self.assertTrue( TRANS.Equal(self.trans, True, False, False, False) ) # test __eq__ implementation SPLIT = Split(self.book) SPLIT.SetParent(TRANS) self.assertTrue( self.trans == SPLIT.GetParent() ) self.assertTrue( self.trans != Transaction(self.book) )
def find_transaction(account, name, ignore_case=True, transaction_list=None): """Searches the transactions of an account for name. Searches in description and in memo of each split. returns a list of transactions that match criteria. options: account: Account to search in. name: String to search for. ignore_case: (optional, default=True) Ignore case if True. transaction_list: (optional) list of transactions to search in. """ if not transaction_list: transaction_list = get_transaction_list(account) ret = [] if ignore_case: name = name.lower() for transaction in transaction_list: found = False desc = transaction.GetDescription() if ignore_case: desc = desc.lower() if name in desc: found = True sl = transaction.GetSplitList() for split in sl: if type(split) != Split: split = Split(instance=split) memo = split.GetMemo() if ignore_case: memo = memo.lower() if name in memo: found = True if found: ret.append(transaction) return ret
def _query(self, date=None, date_from=None, date_to=None, filters=[]): book = self._session.book query = gnucash.Query() query.search_for("Split") query.set_book(book) account_guid = self._account.GetGUID() query.add_guid_match([SPLIT_ACCOUNT, QOF_PARAM_GUID], account_guid, QOF_QUERY_AND) if date: pred_data = gnucash.gnucash_core.QueryDatePredicate( QOF_COMPARE_EQUAL, QOF_DATE_MATCH_DAY, date) query.add_term(PARAM_LIST, pred_data, QOF_QUERY_AND) else: if date_from: pred_data = gnucash.gnucash_core.QueryDatePredicate( QOF_COMPARE_GTE, QOF_DATE_MATCH_NORMAL, date_from) query.add_term(PARAM_LIST, pred_data, QOF_QUERY_AND) if date_to: pred_data = gnucash.gnucash_core.QueryDatePredicate( QOF_COMPARE_LTE, QOF_DATE_MATCH_NORMAL, date_to) query.add_term(PARAM_LIST, pred_data, QOF_QUERY_AND) return (split_to_transaction(Split(instance=split), self.categories) for split in query.run())
def test_equal(self): COPY = self.split self.assertTrue(self.split.Equal(COPY, True, False, False)) # test __eq__ implementation TRANS = Transaction(self.book) self.split.SetParent(TRANS) self.assertTrue(self.split == TRANS.GetSplitList()[0]) self.assertTrue(self.split != Split(self.book))
def get_transaction_list(account): """Returns all transactions in account. Splits are derived from account.GetSplitList(). options: account: Account to get transactions from. """ split_list = account.GetSplitList() transaction_list = [] for split in split_list: if type(split) != Split: split = Split(instance=split) transaction = split.GetParent() if not (transaction in transaction_list): # this check may not be necessary. transaction_list.append(transaction) return transaction_list
def NewSplit(self, txn, acct, amount): s = Split(self._book) s.SetParent(txn) s.SetAccount(acct) s.SetAmount(self.rat(amount)) s.SetValue(self.rat(amount)) return s
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
def query_splits(book, terms=[]): query = Query() query.search_for('Split') query.set_book(book) if terms: for term in terms: query.add_term(*term) splits = [] for split in query.run(): split = Split( instance=split) # ToDo: query.run() should return objects splits.append(split) query.destroy() return splits
def write_transactions(self, transactions): for transaction in transactions: tx = Transaction(self.book) tx.BeginEdit() tx.SetCurrency(self.currency) tx.SetDateEnteredTS(datetime.datetime.now()) tx.SetDatePostedTS(transaction.datetime) tx.SetDescription(transaction.description) tx.SetNotes(transaction.note) for split in transaction.splits: sp = Split(self.book) sp.SetParent(tx) sp.SetAccount(GnucashBook.lookup_account(self, split.account)) sp.SetMemo(split.memo) amount = int( Decimal(split.amount) * self.currency.get_fraction()) sp.SetValue(GncNumeric(amount, self.currency.get_fraction())) sp.SetAmount(GncNumeric(amount, self.currency.get_fraction())) tx.CommitEdit()
def setUp(self): BookSession.setUp(self) self.split = Split(self.book)
def add_transaction(book, item, currency): logging.info('Adding transaction for account "%s" (%s %s)..', item.account, item.split_amount, currency.get_mnemonic()) root = book.get_root_account() acc = lookup_account(root, item.account) tx = Transaction(book) tx.BeginEdit() tx.SetCurrency(currency) tx.SetDateEnteredTS(datetime.datetime.now()) tx.SetDatePostedTS(item.date) tx.SetDescription(item.memo) s1 = Split(book) s1.SetParent(tx) s1.SetAccount(acc) amount = int( Decimal(item.split_amount.replace(',', '.')) * currency.get_fraction()) s1.SetValue(GncNumeric(amount, currency.get_fraction())) s1.SetAmount(GncNumeric(amount, currency.get_fraction())) acc2 = lookup_account(root, item.split_category) s2 = Split(book) s2.SetParent(tx) s2.SetAccount(acc2) s2.SetValue(GncNumeric(amount * -1, currency.get_fraction())) s2.SetAmount(GncNumeric(amount * -1, currency.get_fraction())) tx.CommitEdit()
def initialize_split(book, value, account, trans): split = Split(book) split.SetValue(value) split.SetAccount(account) split.SetParent(trans) return split
def create_split_transaction(book, bank_acc_name, exp_acc_name, trans_date, description, amount, vat_incl=True): """ @todo: more generic handling of assets/income/expenses/liabilities """ root = book.get_root_account() comm_table = book.get_table() currency = comm_table.lookup("CURRENCY", settings.GNUCASH_CURRENCY) bank_acc = root.lookup_by_name(bank_acc_name) exp_acc = root.lookup_by_name(exp_acc_name) if vat_incl: vat_acc = root.lookup_by_name(settings.GNUCASH_VAT_ACCOUNT) trans1 = Transaction(book) trans1.BeginEdit() num1 = gnc_numeric_from_decimal(amount) # total if vat_incl: num2 = gnc_numeric_from_decimal( (amount / Decimal(settings.GNUCASH_VAT_RATE)).quantize( Decimal("0.01"))) # subtotal num3 = gnc_numeric_from_decimal( amount - (amount / Decimal(settings.GNUCASH_VAT_RATE)).quantize( Decimal("0.01"))) # vat else: num2 = num1 # total if bank_acc_name == settings.GNUCASH_CARD_ACCOUNT: num1 = num1.neg() num2 = num2.neg() try: num3 = num3.neg() except NameError: pass split1 = Split(book) split1.SetAccount(exp_acc) split1.SetParent(trans1) split1.SetValue(num2.neg()) if vat_incl: split2 = Split(book) split2.SetAccount(vat_acc) split2.SetParent(trans1) split2.SetValue(num3.neg()) split3 = Split(book) split3.SetAccount(bank_acc) split3.SetParent(trans1) split3.SetValue(num1) trans1.SetCurrency(currency) trans1.SetDate(trans_date.day, trans_date.month, trans_date.year) trans1.SetDescription(description) trans1.CommitEdit()
def _initialize_split(self, book, amount, account, trans): split = Split(book) split.SetValue(GncNumeric(amount)) split.SetAccount(account) split.SetParent(trans) return split
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 _transfer(self, book, d): from_ac = book.get_root_account().lookup_by_code(d['TransferFromAC']) if not from_ac: raise LookupError('TransferFromAC ({0}) not found'.format( d['TransferFromAC'])) to_ac = book.get_root_account().lookup_by_code(d['TransferToAC']) if not to_ac: raise LookupError('TransferToAC ({0}) not found'.format( d['TransferToAC'])) if 'Currency' in d: currency = book.get_table().lookup('CURRENCY', d['Currency']) else: currency = book.get_table().lookup('CURRENCY', 'CHF') if not currency: raise LookupError('Currency ({0}) not found'.format(d['Currency'])) trans = Transaction(book) trans.BeginEdit() trans.SetCurrency(currency) date = d.get('Date', datetime.date.today()) trans.SetDate(date.day, date.month, date.year) # trans.SetDateEnteredTS(datetime.datetime.now()) # trans.SetDatePostedTS(item.date) trans.SetDescription( d.get('Description', 'Auto Generated by Json import')) amount = int(d.get('Amount', 0) * currency.get_fraction()) split1 = Split(book) split1.SetParent(trans) split1.SetAccount(from_ac) split1.SetValue(GncNumeric(amount, currency.get_fraction())) split1.SetAmount(GncNumeric(amount, currency.get_fraction())) split2 = Split(book) split2.SetParent(trans) split2.SetAccount(to_ac) split2.SetValue(GncNumeric(amount * -1, currency.get_fraction())) split2.SetAmount(GncNumeric(amount * -1, currency.get_fraction())) trans.CommitEdit() logging.info( 'New Transfer: Amount {0} , from:{1}, to:{2}, memo: {3}'.format( d.get('Amount', 0), d['TransferFromAC'], d['TransferToAC'], d.get('Description', 'Auto Generated by Json import')))
continue if dest_acc == None: print "Couldn't find dest account '%s'" % tx['dest_account'] continue gtx = Transaction(book) gtx.BeginEdit() gtx.SetCurrency(currency) gtx.SetDateEnteredTS(today) gtx.SetDatePostedTS(tx['date']) # or another datetime object for the transaction's "register date" gtx.SetDescription(str(tx['label'])) amount = tx['amount'] * 100 sp1 = Split(book) # First half of transaction sp1.SetParent(gtx) # The lookup string needs to match your account path exactly. sp1.SetAccount(dest_acc) # amount is an int (no $ or .), so $5.23 becomes amount=523 sp1.SetValue(GncNumeric(amount, 100)) # Assuming you only have one split # For multiple splits, you need to make sure the totals all balance out. sp1.SetAmount(GncNumeric(amount, 100)) sp1.SetMemo(str(tx['label'] + ' - Destiny')) sp2 = Split(book) # Need a balancing split sp2.SetParent(gtx) sp2.SetAccount(src_acc) sp2.SetValue(sp1.GetValue().neg()) sp2.SetAmount(sp1.GetValue().neg())
# 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) root_acct.append_child(savings_acct)
def copy_split(a): from .Reflect import chain_mutations b = Split(a.GetBook()) #hack to copy the data over since Split doesn't have Clone() chain_mutations(b, a) return b
def add_transaction(self, item): """ add new transaction item must have following keys """ assert "date" in item.keys() assert "description" in item.keys() assert "notes" in item.keys() assert "soll" in item.keys() assert "soll_value" in item.keys() assert "haben" in item.keys() assert "haben_value" in item.keys() commod_tab = self.__book.get_table() currency = commod_tab.lookup('ISO4217', "EUR") logging.info('Adding transaction for account "%s" (%s %s)..', item["soll"], item["soll_value"], currency.get_mnemonic()) tx = Transaction(self.__book) tx.BeginEdit() tx.SetCurrency(currency) tx.SetDateEnteredTS(datetime.datetime.now()) tx.SetDatePostedTS(item["date"]) tx.SetDescription(item["description"]) tx.SetNotes(item["notes"]) if "num" in item.keys(): tx.SetNum(item["num"]) # soll acc = self.account_from_path(self.get_root(), item["soll"].split(".")) s1 = Split(self.__book) s1.SetParent(tx) s1.SetAccount(acc) amount = int(item["soll_value"] * currency.get_fraction()) s1.SetValue(GncNumeric(amount, currency.get_fraction())) s1.SetAmount(GncNumeric(amount, currency.get_fraction())) # haben acc2 = self.account_from_path(self.get_root(), item["haben"].split(".")) s2 = Split(self.__book) s2.SetParent(tx) s2.SetAccount(acc2) amount = int(item["haben_value"] * currency.get_fraction()) s2.SetValue(GncNumeric(amount, currency.get_fraction())) s2.SetAmount(GncNumeric(amount, currency.get_fraction())) tx.CommitEdit()
def test_split(self): SPLIT = Split(self.book) self.assertTrue(self.account.insert_split(SPLIT)) self.assertTrue(self.account.remove_split(SPLIT))
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) #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) root_acct.append_child(savings_acct)
debug_print('Adding transaction %s' % get_transaction_string(txinfo)) gnc_amount = decimal_to_gnc_numeric( txinfo['amount']) # From example script 'test_imbalance_transaction.py' trans = Transaction(book) trans.BeginEdit() trans.SetCurrency(USD) trans.SetDescription(str(txinfo['description'])) trans.SetDate(txinfo['date'].day, txinfo['date'].month, txinfo['date'].year) split1 = Split(book) split1.SetParent(trans) split1.SetAccount(acct) if txinfo.has_key('memo'): split1.SetMemo(str(txinfo['memo'])) # The docs say both of these are needed: # http://svn.gnucash.org/docs/HEAD/group__Transaction.html split1.SetValue(gnc_amount) split1.SetAmount(gnc_amount) split1.SetReconcile('c') if opposing_acct != None: debug_print( 'Categorizing transaction %s as %s' % (get_transaction_string(txinfo), opposing_acct_path))
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) s2 = Split(book) s2.SetParent(a) a.SetCurrency(CAD) s.SetAccount(account) s.SetValue(GncNumeric(2)) s.SetAmount(GncNumeric(2)) s2.SetAccount(account2) s2.SetValue(GncNumeric(4)) s2.SetAmount(GncNumeric(4)) print 'overall imbalance', a.GetImbalanceValue().to_string() print 'per-currency imbalances'
def createRandomTransactions(book, accountA, accountB): split = Split(book) currency = book.get_table().lookup("CURRENCY", "EUR") print("Create 100 random transactions") for i in range(100): trans = Transaction(book) trans.BeginEdit() trans.SetCurrency(currency) trans.SetDate(randint(1, 28), randint(1, 12), randint(1900, 2000)) trans.SetDescription("Transaction " + str(i)) value = randint(0, 10000) value1 = GncNumeric(value, 100) value2 = GncNumeric(-value, 100) split1 = Split(book) split1.SetValue(value1) split1.SetAccount(accountA) split1.SetMemo("A" + str(i)) split1.SetParent(trans) split2 = Split(book) split2.SetValue(value2) split2.SetAccount(accountB) split2.SetMemo("B" + str(i)) split2.SetParent(trans) trans.CommitEdit()
acct1 = root.lookup_by_name(acct1_name) acct2 = root.lookup_by_name(acct2_name) # acct1 = root.lookup_by_code(acct1_code) # type_acct1 = acct1.GetTypeStr() # type_acct2 = acct2.GetTypeStr() # create a new Tx tx = Transaction(book) # gets a guid on construction print("tx guid = {0}".format(tx.GetGUID().to_string())) tx.BeginEdit() # create two splits for the Tx s1 = Split(book) s1.SetParent(tx) # gets a guid on construction print("s1 guid = {0}".format(s1.GetGUID().to_string())) s2 = Split(book) s2.SetParent(tx) # gets a guid on construction print("s2 guid = {0}".format(s2.GetGUID().to_string())) tx.SetCurrency(CAD) tx.SetDate(13, 2, 2013) tx.SetDescription(argv[5]) tx.SetNotes("Python {0}".format(argv[0])) # tx: set action ? # set the account and amount of split1