示例#1
0
    def test_session_with_new_file(self):
        """create Session with new xml file"""
        from tempfile import TemporaryDirectory
        from urllib.parse import urlunparse
        with TemporaryDirectory() as tempdir:
            uri = urlunparse(("xml", tempdir, "tempfile", "", "", ""))
            with Session(uri, SessionOpenMode.SESSION_NEW_STORE) as ses:
                pass

            # try to open nonexistent file without NEW mode - should raise Exception
            uri = urlunparse(("xml", tempdir, "tempfile2", "", "", ""))
            with Session() as ses:
                with self.assertRaises(GnuCashBackendException):
                    ses.begin(uri, mode=SessionOpenMode.SESSION_NORMAL_OPEN)

            # try to open nonexistent file without NEW mode - should raise Exception
            # use deprecated arg is_new
            uri = urlunparse(("xml", tempdir, "tempfile2", "", "", ""))
            with Session() as ses:
                with self.assertRaises(GnuCashBackendException):
                    ses.begin(uri, is_new=False)

            uri = urlunparse(("xml", tempdir, "tempfile3", "", "", ""))
            with Session() as ses:
                ses.begin(uri, mode=SessionOpenMode.SESSION_NEW_STORE)

            # test using deprecated args
            uri = urlunparse(("xml", tempdir, "tempfile4", "", "", ""))
            with Session() as ses:
                ses.begin(uri, is_new=True)
示例#2
0
def main():

    if len(argv) < 3:
        print 'not enough parameters'
        print 'usage: new_book_with_opening_balances.py {source_book_url} {destination_book_url}'
        print 'examples:'
        print "gnucash-env python new_book_with_opening_balances.py '/home/username/test.gnucash' 'sqlite3:///home/username/new_test.gnucash'"
        print "gnucash-env python new_book_with_opening_balances.py '/home/username/test.gnucash' 'xml:///crypthome/username/finances/new_test.gnucash'"
        return

    #have everything in a try block to unable us to release our hold on stuff to the extent possible
    try:
        original_book_session = Session(argv[1], is_new=False)
        new_book_session = Session(argv[2], is_new=True)
        new_book = new_book_session.get_book()
        new_book_root = new_book.get_root_account()

        commodtable = new_book.get_table()
        # we discovered that if we didn't have this save early on, there would
        # be trouble later
        new_book_session.save()

        opening_balance_per_currency = {}
        recursivly_build_account_tree(
            original_book_session.get_book().get_root_account(), new_book_root,
            new_book, commodtable, opening_balance_per_currency,
            ACCOUNT_TYPES_TO_OPEN)

        (namespace, mnemonic) = PREFERED_CURRENCY_FOR_SIMPLE_OPENING_BALANCE
        if (namespace, mnemonic) in opening_balance_per_currency:
            opening_trans, opening_amount = opening_balance_per_currency[(
                namespace, mnemonic)]
            simple_opening_name_used = create_opening_balance_transaction(
                commodtable, namespace, mnemonic, new_book_root, new_book,
                opening_trans, opening_amount, False)
            del opening_balance_per_currency[
                PREFERED_CURRENCY_FOR_SIMPLE_OPENING_BALANCE]
        else:
            simple_opening_name_used = False

        for (namespace, mnemonic), (opening_trans, opening_amount) in \
                opening_balance_per_currency.iteritems() :
            simple_opening_name_used = create_opening_balance_transaction(
                commodtable, namespace, mnemonic, new_book_root, new_book,
                opening_trans, opening_amount, simple_opening_name_used)

        new_book_session.save()
        new_book_session.end()
        original_book_session.end()
    except:
        if "original_book_session" in locals():
            original_book_session.end()

        if "new_book_session" in locals():
            new_book_session.end()

        raise
示例#3
0
    def runTest(self):
        self.instrument_main()

        try:
            from accregex import Account
            from accregex.AccountUtil import gnc_numeric_to_python_Decimal
            from gnucash import Session
            session = Session(AccregexTest.reg_doc_example, is_new=False, ignore_lock=False)
            parking_expense_account = Account.get_account(session.book.get_root_account(), parking_expense_account_full_name)
            actual_balance = gnc_numeric_to_python_Decimal(parking_expense_account.GetBalance())
            expected_balance = Decimal(25)

            self.assertEqual(actual_balance, expected_balance)
            
            #TODO: check that the actual transaction in Assets:Current Assets:Checking Account was changed
            session.end()
            
            #put the gnucash file back the way we found it
            shutil.move(AccregexTest.reg_doc_example + ".bak", AccregexTest.reg_doc_example)
        except:
            #in case of error close the session and re-raise
            #equivalent to a "finally" block
            if "session" in locals():
                session.end()
            raise
示例#4
0
 def test_get_book_from_current_session(self):
     from gnucash import _sw_app_utils
     from gnucash import Book
     self.ses_instance = _sw_app_utils.gnc_get_current_session()
     self.ses = Session(instance=self.ses_instance)
     self.book = self.ses.get_book()
     self.assertIsInstance(obj=self.book, cls=Book)
示例#5
0
文件: tax.py 项目: jfishe/qb2gnc
    def gnc_open(cls, path=None):

        if GncFile.status:
            return GncFile.status
        else:
            if path is not None:
                GncFile.path = path
            else:
                path = GncFile.path
            if not os.path.exists(path):
                print """GnuCash file (%s) does not exist. """ % path
                raise Exception('GnuCash file missing')
            if os.path.exists(path + '.LCK'):
                print """Lock file exists. Is GNUCash running?\n"""
                raise Exception('GnuCash locked')

            try:
                GncFile.s = Session(GncFile.path, is_new=False)
            except:
                raise Exception('Could not open GnuCash file')

            GncFile.book = GncFile.s.book
            GncFile.root = GncFile.book.get_root_account()
            GncFile.commod_table = GncFile.book.get_table()
            GncFile.USD = GncFile.commod_table.lookup('CURRENCY', 'USD')

            GncFile.status = True
            return GncFile.status
示例#6
0
def write_transactions_to_gnucash(gnucash_file,
                                  currency,
                                  all_items,
                                  dry_run=False,
                                  date_from=None):
    logging.debug('Opening GnuCash file %s..', gnucash_file)
    session = Session(gnucash_file)
    book = session.book
    commod_tab = book.get_table()
    currency = commod_tab.lookup('ISO4217', currency)

    if date_from:
        date_from = datetime.datetime.strptime(date_from, '%Y-%m-%d')

    imported_items = set()
    for item in all_items:
        if date_from and item.date < date_from:
            logging.info('Skipping entry %s (%s)',
                         item.date.strftime('%Y-%m-%d'), item.split_amount)
            continue
        if item.as_tuple() in imported_items:
            logging.info('Skipping entry %s (%s) --- already imported!',
                         item.date.strftime('%Y-%m-%d'), item.split_amount)
            continue
        add_transaction(book, item, currency)
        imported_items.add(item.as_tuple())

    if dry_run:
        logging.debug('** DRY-RUN **')
    else:
        logging.debug('Saving GnuCash file..')
        session.save()
    session.end()
示例#7
0
def main():
    args = parse_cmdline()
    if args.version:
        print VERSION
        exit(0)

    if args.verbose:
        loglevel = logging.DEBUG
    elif args.quiet:
        loglevel = logging.WARN
    else:
        loglevel = logging.INFO
    logging.basicConfig(level=loglevel)

    rules = readrules(args.rulesfile)
    account_path = re.split(':', args.ac2fix)

    gnucash_session = Session(args.gnucash_file, is_new=False)
    total = 0
    imbalance = 0
    fixed = 0
    try:
        root_account = gnucash_session.book.get_root_account()
        orig_account = account_from_path(root_account, account_path)

        imbalance_pattern = re.compile(args.imbalance_ac)

        for split in orig_account.GetSplitList():
            total += 1
            trans = split.parent
            splits = trans.GetSplitList()
            trans_date = date.fromtimestamp(trans.GetDate())
            trans_desc = trans.GetDescription()
            trans_memo = trans.GetNotes()
            for split in splits:
                ac = split.GetAccount()
                acname = ac.GetName()
                logging.debug('%s: %s => %s', trans_date, trans_desc, acname)
                if imbalance_pattern.match(acname):
                    imbalance += 1
                    search_str = trans_desc
                    if args.use_memo:
                        search_str = trans_memo
                    newac = get_ac_from_str(search_str, rules, root_account)
                    if newac != "":
                        logging.debug('\tChanging account to: %s',
                                      newac.GetName())
                        split.SetAccount(newac)
                        fixed += 1

        if not args.nochange:
            gnucash_session.save()

        logging.info('Total splits=%s, imbalance=%s, fixed=%s', total,
                     imbalance, fixed)

    except Exception as ex:
        logging.error(ex)

    gnucash_session.end()
示例#8
0
def create_transactions(args, conf, url, txs, dry_run):

  try:
    session = Session(url, ignore_lock=True)
  except GnuCashBackendException, backend_exception:
    print "Error: %s" % backend_exception
    exit(1)
示例#9
0
def sessionForFile(input_file):
    try:
        return Session(os.path.abspath(input_file))
    except GnuCashBackendException, backend_exception:
        if ERR_BACKEND_LOCKED in backend_exception.errors:
            eprint("Cannot open %s, file is locked." % input_file)
        raise
示例#10
0
 def __init__(self, file, currency, is_new=False):
     self.session = Session(file, is_new)
     try:
         self.book = self.session.book
         self.commod_tab = self.book.get_table()
         self.currency = self.commod_tab.lookup('ISO4217', currency)
         self.root = self.book.get_root_account()
     except Exception as ex:
         pass
示例#11
0
def account_choices(book=None):
    choices = [("", "---------")]
    if not book:
        session = Session(settings.GNUCASH_FILE)
        book = session.book
    for ac in queries.get_accounts(book.get_root_account()):
        choices.append((ac.name, ac.name))
    if "session" in locals():
        session.end()
    return choices
示例#12
0
    def __init__(self, book_uri):
        self._session = Session(book_uri=book_uri)
        self._book = self._session.book
        self._root_account = self._book.get_root_account()

        self._commodity_table = self._book.get_table()

        # todo: implement as class w/ getattr
        self.commods = {}
        self.commods['USD'] = self._commodity_table.lookup("ISO4217", "USD")
示例#13
0
def customer_choices(book=None):
    choices = [("", "---------")]
    if not book:
        session = Session(settings.GNUCASH_FILE)
        book = session.book
    for c in queries.get_customers(book):
        choices.append((c.GetID(), c.GetName()))
    if "session" in locals():
        session.end()
    return choices
示例#14
0
def find_av_main():
    exe = argv[0].split('/')[-1]
    if len(argv) < 6:
        print("NOT ENOUGH parameters!")
        print("usage: {} <book url> <year> <month> <day> <space-separated path to the account of interest>".format(exe))
        print("PROGRAM EXIT!")
        return

    print("\nrunning {} at run-time: {}\n".format(exe, str(datetime.now())))

    global gnucash_session
    try:
        (gnucash_file, str_year, str_month, str_day) = argv[1:5]
        print("find asset values in {} on {}-{}-{}".format(gnucash_file, str_year, str_month, str_day))

        val_year, val_month, val_day = [int(blah) for blah in (str_year, str_month, str_day)]
        date_of_interest = date(val_year, val_month, val_day)

        account_path = argv[5:]
        print("account_path = {}\n".format(str(account_path)))

        gnucash_session = Session(gnucash_file, is_new=False)
        book = gnucash_session.book

        commod_tab = book.get_table()
        # noinspection PyPep8Naming
        CAD = commod_tab.lookup("ISO4217", "CAD")

        root_account = book.get_root_account()

        account_of_interest = account_from_path(root_account, account_path)
        acct_name = account_of_interest.GetName()

        total = get_asset_balance(account_of_interest, date_of_interest, CAD)

        # get the list of all descendant accounts
        descendants = account_of_interest.get_descendants()

        if len(descendants) > 0:
            # get the values for EACH sub-account too
            print("\nDescendants of {}:".format(acct_name))
            for subAcct in descendants:
                total += get_asset_balance(subAcct, date_of_interest, CAD)

        print("total {} value = {}${}".format(acct_name, CAD.get_mnemonic(), total))

        # no save needed, we're just reading...
        gnucash_session.end()

    except Exception as ae:
        print("Exception: {}".format(ae))
        if "gnucash_session" in locals() and gnucash_session is not None:
            gnucash_session.end()

    print("\n >>> PROGRAM ENDED.")
示例#15
0
    def setUp(self):
        self.util = Util()
        self.account = Nubank(self.util.DEFAULT_ACCOUNT_SRC_FILE)
        self.ledger = Ledger(self.account, self.util.DEFAULT_CURRENCY, False,
                             self.util.DEFAULT_GNUCASH_FILE)

        session = Session(self.util.DEFAULT_GNUCASH_FILE)
        self.book = session.book
        self.currency = self.book.get_table().lookup(
            'ISO4217', self.util.DEFAULT_CURRENCY)
        session.end()
示例#16
0
def open_book(gnucashfile, account2fix):
    """Read a GNU Cash file

    :param gnucashfile: path to the GNU Cash file
    :param account2fix: list with the path of the account
    :returns: session object, root account and origin account
    :rtype:

    """
    gnucash_session = Session(gnucashfile, is_new=False)
    root_account = gnucash_session.book.get_root_account()
    orig_account = account_from_path(root_account, account2fix)
    return (gnucash_session, root_account, orig_account)
def main():
    original_book_session = Session(argv[1], is_new=False)
    new_book_session = Session(argv[2], in_new=True)
    new_book = new_book_session.get_book()
    new_book_root = new_book.get_root_account()

    commodtable = new_book.get_table()
    # we discovered that if we didn't have this save early on, there would
    # be trouble later
    new_book_session.save()

    opening_balance_per_currency = {}
    recursivly_build_account_tree(
        original_book_session.get_book().get_root_account(), new_book_root,
        new_book, commodtable, opening_balance_per_currency,
        ACCOUNT_TYPES_TO_OPEN)

    (namespace, mnemonic) = PREFERED_CURRENCY_FOR_SIMPLE_OPENING_BALANCE
    if (namespace, mnemonic) in opening_balance_per_currency:
        opening_trans, opening_amount = opening_balance_per_currency[(
            namespace, mnemonic)]
        simple_opening_name_used = create_opening_balance_transaction(
            commodtable, namespace, mnemonic, new_book_root, new_book,
            opening_trans, opening_amount, False)
        del opening_balance_per_currency[
            PREFERED_CURRENCY_FOR_SIMPLE_OPENING_BALANCE]
    else:
        simple_opening_name_used = False

    for (namespace, mnemonic), (opening_trans, opening_amount) in \
            opening_balance_per_currency.iteritems() :
        simple_opening_name_used = create_opening_balance_transaction(
            commodtable, namespace, mnemonic, new_book_root, new_book,
            opening_trans, opening_amount, simple_opening_name_used)

    new_book_session.save()
    new_book_session.end()
    original_book_session.end()
示例#18
0
    def __init__(self, fmon, gnc_file, mode):
        self.prod = (mode == PROD)
        self.mon_file = fmon

        self.session = Session(gnc_file)
        self.book = self.session.book

        self.root = self.book.get_root_account()
        self.root.get_instance()

        self.price_db = self.book.get_price_db()

        commod_tab = self.book.get_table()
        self.currency = commod_tab.lookup("ISO4217", "CAD")
示例#19
0
 def handle(self, *args, **options):
     try:
         s = Session(settings.GNUCASH_FILE)
         book = s.book
         with open(args[0], "r") as f:
             reader = csv.DictReader(f)
             for row in reader:
                 number = row["invoice"]
                 amount = Decimal(row["amount"])
                 date = parser.parse(row["date"])
                 try:
                     pay_invoice(book, number, amount, date)
                 except PaymentExists as e:
                     print("%s... skipping" % e)
         s.save()
     finally:
         s.end()
    def prepare_session(self):
        """
        initialization needed for a Gnucash session
        :return: message
        """
        self.logger.print_info("prepare_session()", BLUE)
        msg = TEST
        try:
            session = Session(self.gnc_file)
            self.book = session.book

            owner = self.monarch_record.get_owner()
            self.logger.print_info("Owner = {}".format(owner), GREEN)
            self.set_gnc_rec(InvestmentRecord(owner))

            self.create_gnucash_info()

            if self.mode == PROD:
                self.logger.print_info("Mode = {}: COMMIT Price DB edits and Save session.".format(self.mode), GREEN)

                if self.domain != TRADE:
                    self.price_db.commit_edit()

                # only ONE session save for the entire run
                session.save()

            session.end()
            session.destroy()

            msg = self.logger.get_log()

        except Exception as se:
            msg = "prepare_session() EXCEPTION!! '{}'".format(repr(se))
            self.logger.print_error(msg)
            if "session" in locals() and session is not None:
                session.end()
                session.destroy()
            raise se

        return msg
示例#21
0
def open_gnucash(gnucash_file):
    from gnucash import Session
    from financespy import gnucash_backend
    from financespy.gnucash_backend import GnucashBackend

    path = Path(gnucash_file)
    metadata_file = re.sub("[.]gnucash$", ".json", path.name)
    metadata = read_metadata(str(path.parent / metadata_file))

    session = Session(gnucash_file)

    gnucash_account = gnucash_backend.account_for(
        session, metadata.properties["account_backend"]
    )

    if not metadata.categories:
        metadata.categories = gnucash_backend.categories_from(
            session, metadata.properties["account_categories"]
        )

    backend = GnucashBackend(session=session, account=gnucash_account)

    return Account(backend, metadata)
示例#22
0
    def prepare_session(self):
        """
        Take the information from a transaction collection and produce Gnucash transactions to write to a Gnucash file
        :return: message
        """
        print_info("prepare_session()", MAGENTA)
        msg = TEST
        try:
            session = Session(self.gnc_file)
            self.book = session.book

            print_info("Owner = {}".format(self.tx_coll[OWNER]), GREEN)
            self.report_info = InvestmentRecord(self.tx_coll[OWNER])

            self.create_gnucash_info()

            if self.mode == PROD:
                msg = "Mode = {}: COMMIT Price DB edits and Save session.".format(
                    self.mode)
                print_info(msg, GREEN)
                self.price_db.commit_edit()
                # only ONE session save for the entire run
                session.save()

            session.end()
            session.destroy()

        except Exception as e:
            msg = "prepare_session() EXCEPTION!! '{}'".format(repr(e))
            print_error(msg)
            if "session" in locals() and session is not None:
                session.end()
                session.destroy()
            raise

        return msg
示例#23
0
    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


with Session(uri, SessionOpenMode.SESSION_NEW_STORE) as ses:

    book = ses.get_book()
    accountA, accountB = createAccounts(book)
    createRandomTransactions(book, accountA, accountB)

    # TRANSACTIONS
    #
    # get all transactions
    transactions_all = query_transactions(book)
    print("Query all: " + str(len(transactions_all)) + " transactions.")

    # query date
    threshold = datetime.datetime(1950, 1, 1)
    QOF_DATE_MATCH_NORMAL = 2
    terms = [(['date-posted'],
示例#24
0
#!/usr/bin/env python

##  @file
#   @brief Simple example for a book
#   @ingroup python_bindings_examples

import sys
from gnucash import Session

# We need to tell GnuCash the data format to create the new file as (xml://)
uri = "xml:///tmp/simple_book.gnucash"

print("uri:", uri)
ses = Session(uri, is_new=True)
book = ses.get_book()

#Call some methods that produce output to show that Book works
book.get_root_account().SetDescription("hello, book")
print("Book is saved:", not book.session_not_saved())

print("saving...")
ses.save()

print("Book is saved:", not book.session_not_saved())
ses.end()
示例#25
0
# Django setup
# from http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/
# This script needs to be callable from the command line, but it also needs
# to know about the Django project's database and other settings.
from django.core.management import setup_environ
import settings  # only works due to path fuckery above
setup_environ(settings)

from gnucash_data import models
from utils.AsciiDammit import asciiDammit

# make sure we can begin a session
models.Lock.check_can_obtain()

# begin GnuCash API session
session = Session(settings.GNUCASH_CONN_STRING)

debug = False


def debug_print(s):
    if debug:
        print s


def get_transaction_string(t):
    memo = txinfo.get('memo', '')
    if memo:
        memo = ' / ' + memo
    return "'%s%s' on %s for %s" \
      % (t['description'], memo,
示例#26
0
 def test_app_utils_get_current_session(self):
     from gnucash import _sw_app_utils
     self.ses_instance = _sw_app_utils.gnc_get_current_session()
     self.ses = Session(instance=self.ses_instance)
     self.assertIsInstance(obj=self.ses, cls=Session)
示例#27
0
#!/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()
示例#28
0
 def test_session_mode(self):
     """use mode argument"""
     self.ses = Session(mode=SessionOpenMode.SESSION_NORMAL_OPEN)
示例#29
0
 def test_session_deprecated_arguments(self):
     """use deprecated arguments ignore_lock, is_new, force_new"""
     self.ses = Session(ignore_lock=False, is_new=True, force_new=False)
示例#30
0
 def test_create_empty_session(self):
     self.ses = Session()