def test_from_int(self): num = GncNumeric(3) self.assertEqual(str(num), "3/1") self.assertEqual(num.num(), 3) self.assertEqual(num.denom(), 1) with self.assertRaises(Exception) as context: GncNumeric((2**64) + 1) #On Linux it raises an OverflowError while on MacOS it's a TypeError. self.assertTrue( isinstance(context.exception, TypeError) or isinstance(context.exception, OverflowError))
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')))
def test_from_float(self): num = GncNumeric(3.1, 20, GNC_HOW_DENOM_FIXED | GNC_HOW_RND_NEVER) self.assertEqual(str(num), "62/20") self.assertEqual(num.num(), 62) self.assertEqual(num.denom(), 20) num = GncNumeric(1/3.0, 10000000000, GNC_HOW_RND_FLOOR) self.assertEqual(str(num), "3333333333/10000000000") self.assertEqual(num.num(), 3333333333) self.assertEqual(num.denom(), 10000000000) num = GncNumeric(1/3.0, 10000000000, GNC_HOW_RND_CEIL) self.assertEqual(str(num), "3333333334/10000000000") self.assertEqual(num.num(), 3333333334) self.assertEqual(num.denom(), 10000000000)
def record_opening_balance(original_account, new_account, new_book, opening_balance_per_currency, commodity_tuple ): # create an opening balance if the account type is right if new_account.GetType() in ACCOUNT_TYPES_TO_OPEN: final_balance = original_account.GetBalance() if final_balance.num() != 0: # if there is a new currency type, associate with the currency # a Transaction which will be the opening transaction for that # currency and a GncNumeric value which will be the opening # balance acccount amount if commodity_tuple not in opening_balance_per_currency: trans = Transaction(new_book) trans.BeginEdit() opening_balance_per_currency[commodity_tuple] = ( trans, GncNumeric(0, 1) ) trans, total = opening_balance_per_currency[commodity_tuple] new_total = total.sub( final_balance, GNC_DENOM_AUTO, GNC_HOW_DENOM_EXACT ) initialize_split( new_book, final_balance, new_account, trans) opening_balance_per_currency[commodity_tuple] = \ (trans, new_total )
def decimal_to_gnc_numeric(d): denom = 100 d = d * denom while d % 1: denom *= 10 d *= 10 return GncNumeric(int(d), denom)
def gnc_numeric_from_decimal(decimal_value): sign, digits, exponent = decimal_value.as_tuple() # convert decimal digits to a fractional numerator # equivlent to # numerator = int(''.join(digits)) # but without the wated conversion to string and back, # this is probably the same algorithm int() uses numerator = 0 TEN = int(Decimal(0).radix()) # this is always 10 numerator_place_value = 1 # add each digit to the final value multiplied by the place value # from least significant to most sigificant for i in range(len(digits) - 1, -1, -1): numerator += digits[i] * numerator_place_value numerator_place_value *= TEN if decimal_value.is_signed(): numerator = -numerator # if the exponent is negative, we use it to set the denominator if exponent < 0: denominator = TEN**(-exponent) # if the exponent isn't negative, we bump up the numerator # and set the denominator to 1 else: numerator *= TEN**exponent denominator = 1 return GncNumeric(numerator, denominator)
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_quote_onvista_bond(isin): url = 'http://www.onvista.de/anleihen/snapshot.html?ISIN={}'.format(isin) r = requests.get(url) soup = BeautifulSoup(r.text) price = soup.select( '.INHALT #KURSINFORMATIONEN ~ .t span:nth-of-type(2)')[0].get_text() currency = 'EUR' logging.info('Got quote for %s: %s%%', isin, price) return GncNumeric(int(price.replace(',', '')), 100 * 100), currency
def test_payment(self): self.assertFalse( self.invoice.IsPaid() ) self.customer.ApplyPayment( self.invoice, self.receivable, self.bank, GncNumeric(50), GncNumeric(50), self.today, "", "") self.assertFalse( self.invoice.IsPaid() ) BAL = self.invoice.GetPostedLot().get_balance() self.assertTrue( GncNumeric(50).equal( BAL ) ) self.customer.ApplyPayment( self.invoice, self.receivable, self.bank, GncNumeric(50), GncNumeric(50), self.today, "", "") self.assertTrue( self.invoice.IsPaid() )
def get_quote_onvista_stock(isin): url = 'http://www.onvista.de/suche/?searchValue={}'.format(isin) r = requests.get(url) soup = BeautifulSoup(r.text) spans = soup.select('.INHALT ul.KURSDATEN li:nth-of-type(1) span') price = spans[0].get_text() currency = str(spans[1].get_text()) logging.info('Got quote for %s: %s %s', isin, price, currency) return GncNumeric(int(price.replace(',', '')), 1000), currency
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 _payment(self, book, d): account = book.get_root_account().lookup_by_code(d['TransferAC']) if not account: raise LookupError('TransferAC not found') 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 not found') if 'BillID' in d: invoice = book.InvoiceLookupByID(to_str(d['BillID'], GC_ENC)) if not invoice: logging.error('Invoice {0} not found'.format( d.get('BillID', 'unknown'))) else: if not invoice.IsPosted(): logging.warn('Invoice {0} is not yet posted'.format( d.get('BillID', 'unknown'))) if invoice.IsPaid(): logging.warn( 'Invoice {0} is already paid, create credit note'.format( d.get('BillID', 'unknown'))) invoice.ApplyPayment( None, account, GncNumeric(int(d.get('Amount', 0) * currency.get_fraction()), currency.get_fraction()), GncNumeric(1), d.get('Date', datetime.date.today()), to_str(d.get('Memo', 'File Import'), GC_ENC), to_str(d.get('BillID', 'unknown'), GC_ENC)) logging.info( 'Payment of {0} for bill {1} entered (Memo: {2})'.format( d.get('Amount', 0), d['BillID'], d.get('Memo', 'File Import')))
def pay_invoice(book, invoice_id, amount, date): invoice = book.InvoiceLookupByID(invoice_id) if not invoice: raise InvoiceNotFound("Could not find invoice %s" % invoice_id) if invoice_id in queries.get_payment_refs(book): raise PaymentExists("Payment %s already exists" % invoice_id) bank = queries.get_bank_account(book) amount = gnc_numeric_from_decimal(amount) invoice.ApplyPayment(None, bank, amount, GncNumeric(1), date, "", invoice_id)
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 gnc_numeric_to_python_decimal(numeric): negative = numeric.negative_p() sign = 1 if negative else 0 val = GncNumeric(numeric.num(), numeric.denom()) result = val.to_decimal(None) if not result: raise Exception("gnc numeric value {} CAN'T be converted to decimal!".format(val.to_string())) digit_tuple = tuple(int(char) for char in str(val.num()) if char != '-') denominator = val.denom() exponent = int(log10(denominator)) assert( (10 ** exponent) == denominator ) return Decimal((sign, digit_tuple, -exponent))
def apply_payment(book, customer_id, amount, date): customer = book.CustomerLookupByID(customer_id) if not customer: raise CustomerNotFound("Could not find customer %s" % customer_id) posted_acc = queries.get_accounts_receivable(book) xfer_acc = queries.get_bank_account(book) check = queries.get_duplicate_check_data(xfer_acc) if [date, amount] in check: raise PaymentExists("Payment %s already exists" % customer_id) amount = gnc_numeric_from_decimal(amount) customer.ApplyPayment(None, None, posted_acc, xfer_acc, amount, GncNumeric(1), date, "", "", True)
def gnc_numeric_to_python_Decimal(numeric): negative = numeric.negative_p() if negative: sign = 1 else: sign = 0 copy = GncNumeric(numeric.num(), numeric.denom()) result = copy.to_decimal(None) if not result: raise Exception("gnc numeric value %s can't be converted to decimal" % copy.to_string()) digit_tuple = tuple(int(char) for char in str(copy.num()) if char != '-') denominator = copy.denom() exponent = int(log10(denominator)) assert ((10**exponent) == denominator) return Decimal((sign, digit_tuple, -exponent))
def gnc_numeric_from_decimal(decimal_value): sign, digits, exponent = decimal_value.as_tuple() numerator = 0 TEN = int(Decimal(0).radix()) # numerator_place_value = 1 for i in xrange(len(digits) - 1, -1, -1): numerator += digits[i] * numerator_place_value numerator_place_value *= TEN if decimal_value.is_signed(): numerator = -numerator if exponent < 0: denominator = TEN**(-exponent) else: numerator *= TEN**exponent denominator = 1 return GncNumeric(numerator, denominator)
def report(s, args): book = s.book table = book.get_table() pricedb = book.get_price_db() # FIXME: hard-coded currency currency_code = 'EUR' currency = table.lookup('ISO4217', currency_code) account = book.get_root_account() for acc in account.get_descendants(): if acc.GetType() == ACCT_TYPE_STOCK: commodity = acc.GetCommodity() namespace = commodity.get_namespace() if namespace != 'CURRENCY': print commodity.get_fullname(), commodity.get_cusip( ), acc.GetBalance() inst = pricedb.lookup_latest(commodity, currency).get_value() print GncNumeric(instance=inst).to_string()
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 create_gnc_price_txs(self, mtx:dict, ast_parent:Account, rev_acct:Account): """ Create and load Gnucash prices to the Gnucash PriceDB :param mtx: InvestmentRecord transaction :param ast_parent: Asset parent account :param rev_acct: Revenue account :return: nil """ self.logger.print_info('create_gnc_price_txs()', BLUE) conv_date = dt.strptime(mtx[DATE], "%d-%b-%Y") pr_date = dt(conv_date.year, conv_date.month, conv_date.day) datestring = pr_date.strftime("%Y-%m-%d") fund_name = mtx[FUND] if fund_name in MONEY_MKT_FUNDS: return int_price = int(mtx[PRICE].replace('.', '').replace('$', '')) val = GncNumeric(int_price, 10000) self.logger.print_info("Adding: {}[{}] @ ${}".format(fund_name, datestring, val)) pr1 = GncPrice(self.book) pr1.begin_edit() pr1.set_time64(pr_date) asset_acct, rev_acct = self.get_accounts(ast_parent, fund_name, rev_acct) comm = asset_acct.GetCommodity() self.logger.print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname())) pr1.set_commodity(comm) pr1.set_currency(self.currency) pr1.set_value(val) pr1.set_source_string("user:price") pr1.set_typestr('nav') pr1.commit_edit() if self.mode == PROD: self.logger.print_info("Mode = {}: Add Price to DB.".format(self.mode), GREEN) self.price_db.add_price(pr1) else: self.logger.print_info("Mode = {}: ABANDON Prices!\n".format(self.mode), RED)
def get_prices_and_save(self, tx_coll): """ create Gnucash prices, load and save to the Gnucash file's PriceDB :param tx_coll: InvestmentRecord object: transactions to use to extract Gnucash prices :return: message """ print_info('get_prices_and_save()', MAGENTA) gncu = GncUtilities() msg = TEST self.price_db.begin_edit() print_info("self.price_db.begin_edit()", MAGENTA) try: for plan_type in tx_coll.plans: print_info("\n\nPlan type = {}".format(plan_type)) for tx in tx_coll.plans[plan_type]: base = pow(10, len(tx[CENTS])) int_price = int(tx[DOLLARS] + tx[CENTS]) val = GncNumeric(int_price, base) ast_parent_path = copy.copy(ACCT_PATHS[ASSET]) ast_parent_path.append(plan_type) if plan_type != PL_OPEN: if tx_coll.get_owner() == UNKNOWN: raise Exception("PROBLEM!! Trying to process plan type '{}' but NO Owner information found" " in Tx Collection!!".format(plan_type)) ast_parent_path.append(ACCT_PATHS[tx_coll.get_owner()]) print_info("ast_parent_path = {}".format(str(ast_parent_path)), BLUE) asset_parent = gncu.account_from_path(self.root, ast_parent_path) # get the asset account name name_key = tx[FUND_CMPY].split(' ')[0] print_info("name_key = {}".format(name_key), YELLOW) if name_key in FUND_NAME_CODE.keys(): name_code = FUND_NAME_CODE[name_key] # special case if name_code == ATL: asset_acct_name = ATL_O59 else: asset_acct_name = name_code + " " + tx[FUND_CODE] else: raise Exception("Could NOT find name key {}!".format(name_key)) print_info("asset_acct_name = {}".format(asset_acct_name), BLUE) # special location for Trust Asset account if asset_acct_name == TRUST_AST_ACCT: asset_parent = self.root.lookup_by_name(TRUST) print_info("asset_parent = {}".format(asset_parent.GetName()), BLUE) # get the asset account asset_acct = asset_parent.lookup_by_name(asset_acct_name) if asset_acct is None: # just skip updating cash-holding funds if str(val) == '100000/10000': continue else: raise Exception( "Could NOT find acct '{}' under parent '{}'".format(asset_acct_name, asset_parent.GetName())) print_info("Adding: {}[{}] @ ${}".format(asset_acct_name, tx_coll.get_date_str(), val), GREEN) pr = GncPrice(self.book) pr.begin_edit() pr.set_time64(tx_coll.get_date()) comm = asset_acct.GetCommodity() print_info("Commodity = {}:{}".format(comm.get_namespace(), comm.get_printname()), YELLOW) pr.set_commodity(comm) pr.set_currency(self.currency) pr.set_value(val) pr.set_source_string("user:price") pr.set_typestr('last') pr.commit_edit() if self.prod: print_info("PROD: Add Price to DB.\n", GREEN) self.price_db.add_price(pr) else: print_info("PROD: ABANDON Prices!\n", RED) if self.prod: msg = "PROD: COMMIT Price DB edits and Save session." print_info("PROD: COMMIT Price DB edits and Save session.", GREEN) self.price_db.commit_edit() # only ONE session save for the entire run self.session.save() self.session.end() self.session.destroy() except Exception as e: msg = "get_prices_and_save() EXCEPTION!! '{}'".format(repr(e)) print_error(msg) if "session" in locals() and self.session is not None: self.session.end() self.session.destroy() raise return msg
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' imbalance_list = a.GetImbalance() for (commod, value) in imbalance_list: print value.to_string(), commod.get_mnemonic() a.CommitEdit() session.end()
def test_to_fraction(self): fraction = GncNumeric("1000/3").to_fraction() self.assertEqual(fraction.numerator, 1000) self.assertEqual(fraction.denominator, 3)
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()) sp2.SetMemo(str(tx['label'] + ' - Source')) gtx.CommitEdit() # Finish editing transaction session.save()
book = s.book root = book.get_root_account() commod_table = book.get_table() CAD = commod_table.lookup('CURRENCY', 'CAD') my_customer = book.CustomerLookupByID(argv[2]) assert (my_customer != None) assert (isinstance(my_customer, Customer)) assets = root.lookup_by_name("Assets") receivables = assets.lookup_by_name("Receivables") income = root.lookup_by_name("Income") invoice = Invoice(book, argv[3], CAD, my_customer) description = argv[4] invoice_value = gnc_numeric_from_decimal(Decimal(argv[5])) tax_table = book.TaxTableLookupByName('good tax') invoice_entry = Entry(book, invoice) invoice_entry.SetInvTaxTable(tax_table) invoice_entry.SetInvTaxIncluded(False) invoice_entry.SetDescription(description) invoice_entry.SetQuantity(GncNumeric(1)) invoice_entry.SetInvAccount(income) invoice_entry.SetInvPrice(invoice_value) invoice.PostToAccount(receivables, datetime.date.today(), datetime.date.today(), "", True, False) s.save() s.end()
def rat(self, value): s = int(round(value*100)) return GncNumeric(s, 100)
new_customer = Customer(book, "1", CAD, "Bill & Bob Industries") # not required, but a good idea because the GUI insists on basic address info address = new_customer.GetAddr() address.SetName("Bill & Bob") address.SetAddr1("201 Nowhere street") new_employee = Employee(book, "2", CAD, "Reliable employee") new_vendor = Vendor(book, "3", CAD, "Dependable vendor") new_job = Job(book, "4", new_vendor, "Good clean, fun") # 7% tax tax_table = TaxTable(book, "good tax", TaxTableEntry(a5, True, GncNumeric(700000, 100000))) invoice_customer = Invoice(book, "5", CAD, new_customer) customer_extract = invoice_customer.GetOwner() assert (isinstance(customer_extract, Customer)) assert (customer_extract.GetName() == new_customer.GetName()) invoice_employee = Invoice(book, "6", CAD, new_employee) employee_extract = invoice_employee.GetOwner() assert (isinstance(employee_extract, Employee)) assert (employee_extract.GetName() == new_employee.GetName()) invoice_vendor = Invoice(book, "7", CAD, new_vendor) vendor_extract = invoice_vendor.GetOwner() assert (isinstance(vendor_extract, Vendor)) assert (vendor_extract.GetName() == new_vendor.GetName())
splits_2 = query_splits(book, terms) print( "Query splits with transaction description containing 'Transaction 5': " + str(len(splits_2)) + " (Should be 22).") # query memo and desc isRegex = False terms = [(['memo'], gnucash_core.QueryStringPredicate(QOF_COMPARE_CONTAINS, "A22", QOF_STRING_MATCH_NORMAL, isRegex), QOF_QUERY_AND)] terms += [(['trans', 'desc'], gnucash_core.QueryStringPredicate(QOF_COMPARE_CONTAINS, "Transaction 55", QOF_STRING_MATCH_NORMAL, isRegex), QOF_QUERY_OR)] splits_4 = query_splits(book, terms) print( "Query splits with memo containing 'A22' or transaction desc containing 'Transaction 55': " + str(len(splits_4)) + " (Should be 3).") # query split value threshold = GncNumeric(5000, 100) terms = [(["amount"], gnucash_core.QueryNumericPredicate(QOF_COMPARE_GT, QOF_NUMERIC_MATCH_ANY, threshold), QOF_QUERY_AND)] splits_3 = query_splits(book, terms) print("Query splits with amount > " + str(threshold) + ": " + str(len(splits_3)) + " (Should be about 100).")
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) root_acct.append_child(opening_acct) #Set up Expenses account expenses_acct.SetCommodity(cad) expenses_acct.SetName("Expenses")