Example #1
0
    def test_create_specific_currency(self):
        b = create_book(currency="USD")
        CUR = b.commodities[0]
        assert CUR.mnemonic == "USD"
        assert CUR.namespace == "CURRENCY"

        b = create_book(currency="CHF")
        CUR = b.commodities[0]
        assert CUR.mnemonic == "CHF"
        assert CUR.namespace == "CURRENCY"

        with pytest.raises(ValueError):
            b = create_book(currency="ZIE")
Example #2
0
    def test_create_specific_currency(self):
        b = create_book(currency="USD")
        CUR = b.commodities[0]
        assert CUR.mnemonic == "USD"
        assert CUR.namespace == "CURRENCY"

        b = create_book(currency="CHF")
        CUR = b.commodities[0]
        assert CUR.mnemonic == "CHF"
        assert CUR.namespace == "CURRENCY"

        with pytest.raises(ValueError):
            b = create_book(currency="ZIE")
Example #3
0
def sql_create(book):
    """Create an empty book with gnucash

    """
    with piecash.create_book(book, overwrite=True,
                             keep_foreign_keys=False) as b:
        b.save()
Example #4
0
    def test_open_lock(self, book_uri):
        # create book and set a lock
        with create_book(uri_conn=book_uri) as b:
            b.session.create_lock()
            b.save()

        # try to open locked book
        with pytest.raises(GnucashException):
            b = open_book(uri_conn=book_uri)

        # open book specifying open_if_lock as True
        with open_book(uri_conn=book_uri, open_if_lock=True) as b:
            pass

        # open book specifying open_if_lock as True and RW to delete lock
        with open_book(uri_conn=book_uri,
                       open_if_lock=True,
                       readonly=False,
                       do_backup=False) as b:
            b.session.delete_lock()
            b.save()

        # open book specifying open_if_lock as False as lock has been removed
        with open_book(uri_conn=book_uri, open_if_lock=False) as b:
            pass
Example #5
0
def book_basic(request):
    name = request.param

    if name and database_exists(name):
        drop_database(name)
    # create new book
    with create_book(uri_conn=name, currency="EUR",
                     keep_foreign_keys=False) as b:
        # create some accounts
        curr = b.currencies[0]
        cdty = Commodity(namespace=u"échange",
                         mnemonic=u"ïoà",
                         fullname=u"Example of unicode déta")
        a = Account(name="asset",
                    type="ASSET",
                    commodity=curr,
                    parent=b.root_account)
        Account(name="broker", type="STOCK", commodity=cdty, parent=a)
        Account(name="exp",
                type="EXPENSE",
                commodity=curr,
                parent=b.root_account)
        Account(name="inc",
                type="INCOME",
                commodity=curr,
                parent=b.root_account)
        b.flush()

        yield b

    if name and database_exists(name):
        drop_database(name)
Example #6
0
    def test_open_default(self, book_uri):
        # open book that does not exists
        with pytest.raises(GnucashException):
            b = open_book(uri_conn=book_uri)

        # create book
        with create_book(uri_conn=book_uri):
            pass

        # assert error if both sqlite_file and uri_conn are defined on open_book
        with pytest.raises(ValueError):
            b = open_book(db_sqlite, db_sqlite_uri)

        # open book that exists
        with open_book(uri_conn=book_uri) as b:
            # try to save (raise as RO per default)
            with pytest.raises(GnucashException):
                b.save()

            # read default currency (to check reading)
            assert b.default_currency.mnemonic == "EUR"

        # open book with checking existence
        book_uri_fail = book_uri.replace("foo", "foofail")
        with pytest.raises(GnucashException,
                           match="Database .* does not exist"):
            open_book(uri_conn=book_uri_fail)

        # open book without checking existence
        with pytest.raises(OperationalError):
            open_book(uri_conn=book_uri_fail, check_exists=False)
Example #7
0
    def test_open_RW_backup(self, book_uri):
        # create book
        with create_book(uri_conn=book_uri) as b:
            engine_type = b.session.bind.name

        # open book with readonly = False (ie RW)
        if engine_type != "sqlite":
            # raise an exception as try to do a backup on postgres which is not supported yet
            with pytest.raises(GnucashException):
                b = open_book(uri_conn=book_uri, readonly=False)

        elif engine_type == "sqlite":
            # delete all potential existing backup files
            url = book_uri[len("sqlite:///"):]
            for fn in glob.glob("{}.[0-9]*.gnucash".format(url)):
                os.remove(fn)

            # open file in RW without a backup creation
            with open_book(uri_conn=book_uri, readonly=False, do_backup=False) as b:
                pass

            # check no backup file creation
            assert len(glob.glob("{}.[0-9]*.gnucash".format(url))) == 0

            # open file in RW without a backup creation
            with open_book(uri_conn=book_uri, readonly=False) as b:
                pass

            # check backup file creation
            assert len(glob.glob("{}.[0-9]*.gnucash".format(url))) == 1
Example #8
0
    def test_create_without_FK(self):
        # create without FK
        b = create_book(uri_conn=db_sqlite_uri, keep_foreign_keys=False, overwrite=True)
        b.session.close()

        insp = Inspector.from_engine(create_engine(db_sqlite_uri))
        for tbl in insp.get_table_names():
            fk = insp.get_foreign_keys(tbl)
            assert len(fk) == 0
Example #9
0
    def test_create_without_FK(self):
        # create without FK
        b = create_book(uri_conn=db_sqlite_uri, keep_foreign_keys=False, overwrite=True)
        b.session.close()

        insp = Inspector.from_engine(create_engine(db_sqlite_uri))
        for tbl in insp.get_table_names():
            fk = insp.get_foreign_keys(tbl)
            assert len(fk) == 0
Example #10
0
    def test_create_with_FK(self):
        # create and keep FK
        b = create_book(uri_conn=db_sqlite_uri, keep_foreign_keys=True, overwrite=True)
        b.session.close()

        insp = Inspector.from_engine(create_engine(db_sqlite_uri))
        fk_total = []
        for tbl in insp.get_table_names():
            fk_total.append(insp.get_foreign_keys(tbl))
        assert len(fk_total) == 25
Example #11
0
    def test_create_with_FK(self):
        # create and keep FK
        b = create_book(uri_conn=db_sqlite_uri, keep_foreign_keys=True, overwrite=True)
        b.session.close()

        insp = Inspector.from_engine(create_engine(db_sqlite_uri))
        fk_total = []
        for tbl in insp.get_table_names():
            fk_total.append(insp.get_foreign_keys(tbl))
        assert len(fk_total) == 25
Example #12
0
 def __init__(self, filename, sample_entries=False):
     if os.path.exists(filename):
         print("Opening GnuCash database.")
         self.book = piecash.open_book(filename, readonly=False)
     else:
         print("Creating GnuCash database.")
         self.book = piecash.create_book(sqlite_file=filename)
     self._enrich_database()
     if sample_entries:
         print("Adding sample entries.")
         self._add_sample_entries()
Example #13
0
def new_book_USD(request):
    name = request.param

    if name and database_exists(name):
        drop_database(name)

    with create_book(uri_conn=name, currency="USD", keep_foreign_keys=False) as b:
        yield b

    if name and database_exists(name):
        drop_database(name)
Example #14
0
    def test_create_named_sqlite_book(self):
        # remove file if left from previous test
        assert isinstance(db_sqlite, Path)
        if db_sqlite.exists():
            db_sqlite.unlink()

        # assert error if both sqlite_file and uri_conn are defined
        with pytest.raises(ValueError):
            b = create_book(db_sqlite, db_sqlite_uri)

        # assert creation of file
        b = create_book(db_sqlite)
        assert db_sqlite.exists()
        t = db_sqlite.stat().st_mtime

        # ensure error if no overwrite
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite)
        assert db_sqlite.stat().st_mtime == t
        with pytest.raises(GnucashException):
            b = create_book(uri_conn="sqlite:///{}".format(db_sqlite))
        assert db_sqlite.stat().st_mtime == t
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite, overwrite=False)
        assert db_sqlite.stat().st_mtime == t

        # if overwrite, DB is recreated
        b = create_book(db_sqlite, overwrite=True)
        assert db_sqlite.stat().st_mtime > t

        # clean test
        db_sqlite.unlink()
Example #15
0
    def test_create_named_sqlite_book(self):
        # remove file if left from previous test
        if os.path.exists(db_sqlite):
            os.remove(db_sqlite)

        # assert error if both sqlite_file and uri_conn are defined
        with pytest.raises(ValueError):
            b = create_book(db_sqlite, db_sqlite_uri)

        # assert creation of file
        b = create_book(db_sqlite)
        assert os.path.exists(db_sqlite)
        t = os.path.getmtime(db_sqlite)

        # ensure error if no overwrite
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite)
        assert os.path.getmtime(db_sqlite) == t
        with pytest.raises(GnucashException):
            b = create_book(uri_conn="sqlite:///{}".format(db_sqlite))
        assert os.path.getmtime(db_sqlite) == t
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite, overwrite=False)
        assert os.path.getmtime(db_sqlite) == t

        # if overwrite, DB is recreated
        b = create_book(db_sqlite, overwrite=True)
        assert os.path.getmtime(db_sqlite) > t

        # clean test
        os.remove(db_sqlite)
Example #16
0
    def test_create_named_sqlite_book(self):
        # remove file if left from previous test
        assert isinstance(db_sqlite, Path)
        if db_sqlite.exists():
            db_sqlite.unlink()

        # assert error if both sqlite_file and uri_conn are defined
        with pytest.raises(ValueError):
            b = create_book(db_sqlite, db_sqlite_uri)

        # assert creation of file
        b = create_book(db_sqlite)
        assert db_sqlite.exists()
        t = db_sqlite.stat().st_mtime

        # ensure error if no overwrite
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite)
        assert db_sqlite.stat().st_mtime == t
        with pytest.raises(GnucashException):
            b = create_book(uri_conn="sqlite:///{}".format(db_sqlite))
        assert db_sqlite.stat().st_mtime == t
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite, overwrite=False)
        assert db_sqlite.stat().st_mtime == t

        # if overwrite, DB is recreated
        b = create_book(db_sqlite, overwrite=True)
        assert db_sqlite.stat().st_mtime > t

        # clean test
        db_sqlite.unlink()
Example #17
0
    def test_create_named_sqlite_book(self):
        # remove file if left from previous test
        if os.path.exists(db_sqlite):
            os.remove(db_sqlite)

        # assert error if both sqlite_file and uri_conn are defined
        with pytest.raises(ValueError):
            b = create_book(db_sqlite, db_sqlite_uri)

        # assert creation of file
        b = create_book(db_sqlite)
        assert os.path.exists(db_sqlite)
        t = os.path.getmtime(db_sqlite)

        # ensure error if no overwrite
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite)
        assert os.path.getmtime(db_sqlite) == t
        with pytest.raises(GnucashException):
            b = create_book(uri_conn="sqlite:///{}".format(db_sqlite))
        assert os.path.getmtime(db_sqlite) == t
        with pytest.raises(GnucashException):
            b = create_book(db_sqlite, overwrite=False)
        assert os.path.getmtime(db_sqlite) == t

        # if overwrite, DB is recreated
        b = create_book(db_sqlite, overwrite=True)
        assert os.path.getmtime(db_sqlite) > t

        # clean test
        os.remove(db_sqlite)
Example #18
0
    def test_create_default(self, book_db_config):
        with create_book(keep_foreign_keys=False, **book_db_config) as b:
            a = Account(commodity=b.currencies(mnemonic="SEK"),
                        parent=b.root_account,
                        name="léviö",
                        type="ASSET")
            assert str(b.uri) == build_uri(**book_db_config)
            b.save()

        # reopen the DB except if sqlite_file is None
        if book_db_config.get("sqlite_file", True):
            with open_book(**book_db_config) as b:
                assert b.accounts(name="léviö").commodity == b.currencies(mnemonic="SEK")
Example #19
0
def book_basic(request):
    name = request.param

    if name and database_exists(name):
        drop_database(name)
    # create new book
    with create_book(uri_conn=name, currency="EUR", keep_foreign_keys=False) as b:
        # create some accounts
        curr = b.currencies[0]
        cdty = Commodity(namespace=u"échange", mnemonic=u"ïoà", fullname=u"Example of unicode déta")
        a = Account(name="asset", type="ASSET", commodity=curr, parent=b.root_account)
        Account(name="broker", type="STOCK", commodity=cdty, parent=a)
        Account(name="exp", type="EXPENSE", commodity=curr, parent=b.root_account)
        Account(name="inc", type="INCOME", commodity=curr, parent=b.root_account)

        yield b

    if name and database_exists(name):
        drop_database(name)
Example #20
0
    def test_open_default(self, book_uri):
        # open book that does not exists
        with pytest.raises(GnucashException):
            b = open_book(uri_conn=book_uri)

        # create book
        with create_book(uri_conn=book_uri):
            pass

        # assert error if both sqlite_file and uri_conn are defined on open_book
        with pytest.raises(ValueError):
            b = open_book(db_sqlite, db_sqlite_uri)

        # open book that exists
        with open_book(uri_conn=book_uri) as b:
            # try to save (raise as RO per default)
            with pytest.raises(GnucashException):
                b.save()

            # read default currency (to check reading)
            assert b.default_currency.mnemonic == "EUR"
Example #21
0
    def test_open_default(self, book_uri):
        # open book that does not exists
        with pytest.raises(GnucashException):
            b = open_book(uri_conn=book_uri)

        # create book
        with create_book(uri_conn=book_uri):
            pass

        # assert error if both sqlite_file and uri_conn are defined on open_book
        with pytest.raises(ValueError):
            b = open_book(db_sqlite, db_sqlite_uri)

        # open book that exists
        with open_book(uri_conn=book_uri) as b:
            # try to save (raise as RO per default)
            with pytest.raises(GnucashException):
                b.save()

            # read default currency (to check reading)
            assert b.default_currency.mnemonic == "EUR"
Example #22
0
    def test_open_lock(self, book_uri):
        # create book and set a lock
        with create_book(uri_conn=book_uri) as b:
            b.session.create_lock()
            b.save()

        # try to open locked book
        with pytest.raises(GnucashException):
            b = open_book(uri_conn=book_uri)

        # open book specifying open_if_lock as True
        with open_book(uri_conn=book_uri, open_if_lock=True) as b:
            pass

        # open book specifying open_if_lock as True and RW to delete lock
        with open_book(uri_conn=book_uri, open_if_lock=True, readonly=False, do_backup=False) as b:
            b.session.delete_lock()
            b.save()

        # open book specifying open_if_lock as False as lock has been removed
        with open_book(uri_conn=book_uri, open_if_lock=False) as b:
            pass
Example #23
0
def sql_create(book):
    """Create an empty book with gnucash

    """
    with piecash.create_book(book, overwrite=True,keep_foreign_keys=False) as b:
        b.save()
Example #24
0
#!/usr/bin/env python
##  @file
#   @brief Example Script simple sqlite create
#   @ingroup python_bindings_examples

from __future__ import print_function
import os

from piecash import create_book, Account, Commodity, open_book

filename = os.path.abspath('test.blob')
if os.path.exists(filename):
    os.remove(filename)

with create_book(filename) as s:
    a = Account(parent=s.book.root_account,
                name="wow",
                type="ASSET",
                commodity=s.book.create_currency_from_ISO("CAD"))

    s.save()

with open_book(filename) as s:
    print(s.book.root_account.children)
    print(s.commodities.get(mnemonic="CAD"))

os.remove(filename)
Example #25
0
import random
import pytest

from piecash import create_book, Account, Transaction, Split, GncValidationError

# create new book
with create_book() as s:
    ra = s.book.root_account
    eur = s.book.default_currency

    # number of accounts
    N = 5
    # number of transactions
    T = 100

    # create accounts
    accounts = [
        Account("account {}".format(i), "ASSET", eur, parent=ra)
        for i in range(N)
    ]

    # create transactions
    for i, v in enumerate(random.randrange(10) for j in range(T)):
        tx = Transaction(
            eur,
            "transaction {}".format(i),
        )
        Split(accounts[random.randrange(N)], value=v, transaction=tx)
        Split(accounts[random.randrange(N)], value=-v, transaction=tx)
    s.save()
Example #26
0
 def test_create_specific_format(self, format_version):
     b = create_book(version_format=format_version)
     v = b.session.query(Version).all()
     print(v)
Example #27
0
# coding=utf-8
from __future__ import print_function, unicode_literals

if False:
    from piecash import create_book, Customer, Address, Vendor

    # create a book (in memory)
    b = create_book(currency="EUR")
    # get the currency
    eur = b.default_currency

    # create a customer
    c1 = Customer(name="Mickey", currency=eur, address=Address(addr1="Sesame street 1", email="*****@*****.**"))
    # the customer has not yet an ID
    b.add(c1)

    # flush the book
    b.flush()

    # the customer gets its ID
    print(c1)

    # or create a customer directly in a book (by specifying the book argument)
    c2 = Customer(name="Mickey", currency=eur, address=Address(addr1="Sesame street 1", email="*****@*****.**"),
                  book=b)

    # the customer gets immediately its ID
    c2

    # the counter of the ID is accessible as
    b.counter_customer
def book():
    """Test piecash book Object"""
    book = piecash.create_book(currency="PLN")
    book.save()
    return book
Example #29
0
    def create_example_book(self):
        """Main function to create example gnucash file (piecash book).

            All Accounts and Transaction types are hardcoded.
            Some Transactions are fixed, meaning that their occurrence or price is always the same.
            Other Transaction days and/or prices are set at random,given the seed provided during initialization.

            What is more, some of the Transactions can also be a part of a Shop (Split) Transaction. The occurence
            of this is also subject to the random seed.

            Function doesn't return anything, but saves the created book in the file_path provided in __init__.
        """

        book = create_book(currency=self.currency, sqlite_file=self.file_path, overwrite=True)
        curr = book.default_currency

        # Accounts
        asset_acc = Account("Assets", "ASSET", curr, parent=book.root_account, placeholder=True)
        john_acc = Account("John", "ASSET", curr, parent=asset_acc)
        susan_acc = Account("Susan", "ASSET", curr, parent=asset_acc)
        family_acc = Account("Family", "ASSET", curr, parent=asset_acc)

        income = Account("Income", "INCOME", curr, parent=book.root_account, placeholder=True)
        john_income = Account("John's Income", "INCOME", curr, parent=income)
        susan_income = Account("Susan's Income", "INCOME", curr, parent=income)

        exp = Account("Expenses", "EXPENSE", curr, parent=book.root_account, placeholder=True)
        john_exp = Account("John's Expenses", "EXPENSE", curr, parent=exp, placeholder=True)
        clothes_john = Account("Clothes", "EXPENSE", curr, parent=john_exp)
        susan_exp = Account("Susan's Expenses", "EXPENSE", curr, parent=exp, placeholder=True)
        clothes_susan = Account("Clothes", "EXPENSE", curr, parent=susan_exp)
        family_exp = Account("Family", "EXPENSE", curr, parent=exp, placeholder=True)
        grocery = Account("Grocery", "EXPENSE", curr, parent=family_exp, placeholder=True)
        bread = Account("Bread", "EXPENSE", curr, parent=grocery)
        meat = Account("Meat", "EXPENSE", curr, parent=grocery)
        eggs = Account("Eggs", "EXPENSE", curr, parent=grocery)
        chips = Account("Chips", "EXPENSE", curr, parent=grocery)
        fruits = Account("Fruits and Vegetables", "EXPENSE", curr, parent=grocery)
        car = Account("Car", "EXPENSE", curr, parent=family_exp, placeholder=True)
        petrol = Account("Petrol", "EXPENSE", curr, parent=car)
        flat = Account("Flat", "EXPENSE", curr, parent=family_exp, placeholder=True)
        rent = Account("Rent", "EXPENSE", curr, parent=flat)
        water = Account("Water and Electricity", "EXPENSE", curr, parent=flat)
        bathroom = Account("Bathroom", "EXPENSE", curr, parent=family_exp, placeholder=True)
        toilet = Account("Toilet", "EXPENSE", curr, parent=bathroom)
        personal_john = Account("Personal - John", "EXPENSE", curr, parent=bathroom)
        personal_susan = Account("Personal - Susan", "EXPENSE", curr, parent=bathroom)
        other = Account("Other", "EXPENSE", curr, parent=family_exp)

        book.save()

        # Transactions
        acc_list = [john_acc, susan_acc, family_acc, clothes_john, clothes_susan, bread, meat, eggs,
                    chips, fruits, petrol, rent, water, toilet, personal_john, personal_susan, other]

        # Tuple(
        #       Tuple(
        #           Tuple(Name of Transaction/Split, From_Account),
        #           Tuple(Start of Price Range/Price, Stop of Price Range/ ),
        #           ),
        #       Tuple(...)
        #   ), ...
        planned_tr_list = [
            ((("Salary", john_income), (3000,)),),
            ((("Salary", susan_income), (3000,)),),
            ((("Transaction", john_acc), (500,)),
             (("Transaction", susan_acc), (500,))),
            ((("Clothes", john_acc), (100, 350)),),
            ((("Clothes", john_acc), (100, 350)),),
            ((("White Bread", family_acc), (1, 4)),
             (("Rye Bread", family_acc), (3, 6)),
             (("Butter", family_acc), (4, 7))),
            ((("Chicken", family_acc), (9, 16)),
             (("Cow", family_acc), (15, 30))),
            ((("Eggs", family_acc), (8, 16)),),
            ((("Chips", family_acc), (5, 17)),
             (("Lollipops", family_acc), (1, 2))),
            ((("Apple", family_acc), (3, 5)),
             (("Banana", family_acc), (5, 7)),
             (("Tomato", family_acc), (2, 4)),
             (("Pear", family_acc), (3, 5))),
            ((("Petrol", family_acc), (50, 250)),),
            ((("Rent", family_acc), (2000,)),),
            ((("Water and Electricity", family_acc), (20, 150)),),
            ((("Toilet Paper", family_acc), (5, 15)),
             (("Facial Tissues", family_acc), (2, 8))),
            ((("Beard Balm", john_acc), (15, 50)),),
            ((("Shampoo", susan_acc), (10, 15)),
             (("Face Cleanser", susan_acc), (10, 13))),
            ((("Other", family_acc), (1, 100)),)
        ]

        # Ordered Dict for reproducibility
        # key: Accounts, value: tuples of Transactions
        planned_tr_list = map(OrderedDict, planned_tr_list)
        stuff = OrderedDict(zip(acc_list, planned_tr_list))

        # Zipping Probabilities with Transactions
        low_proba_list = [clothes_john, clothes_susan, petrol, toilet, personal_john, personal_susan]
        medium_proba_list = [meat, chips, other]
        high_proba_list = [bread, eggs, fruits]

        probas = [
            (low_proba_list, self.low_proba),
            (medium_proba_list, self.medium_proba),
            (high_proba_list, self.high_proba)
        ]

        # Fixed Day Transactions
        fixed_transactions = [
            (20, (rent, water)),
            (25, (john_acc, susan_acc)),
            (26, (family_acc,))
        ]

        # Shops (Split Transaction Names)
        shops = ["Grocery Shop #1", "Grocery Shop #2"]
        shop_items = (high_proba_list,)

        self.__create_transactions(book, self.date_range, stuff, curr, probas, fixed_transactions, shops, shop_items)
        book.save()
Example #30
0
from __future__ import print_function
from piecash import create_book

# create by default an in memory sqlite version
ses = create_book(echo=False)
book = ses.book

print("Book is saved:", ses.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("changing description...")
book.root_account.description = "hello, book"
print("Book is saved:", ses.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

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

print("Book is saved:", ses.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("changing description...")
book.root_account.description = "nevermind, book"
print("Book is saved:", ses.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("cancel...")
ses.cancel()

print("Book is saved:", ses.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)
from piecash import create_book, Account

# create a book with some account tree structure
with create_book("../gnucash_books/simple_book_transaction_creation.gnucash", overwrite=True) as mybook:
    mybook.root_account.children = [
        Account(name="Expenses",
                type="EXPENSE",
                commodity=mybook.currencies(mnemonic="USD"),
                placeholder=True,
                children=[
                    Account(name="Some Expense Account",
                            type="EXPENSE",
                            commodity=mybook.currencies(mnemonic="USD")),
                ]),
        Account(name="Assets",
                type="ASSET",
                commodity=mybook.currencies(mnemonic="USD"),
                placeholder=True,
                children=[
                    Account(name="Current Assets",
                            type="BANK",
                            commodity=mybook.currencies(mnemonic="USD"),
                            placeholder=True,
                            children=[
                                Account(name="Checking",
                                        type="BANK",
                                        commodity=mybook.currencies(mnemonic="USD"))
                            ]),
                ]),
    ]
    # save the book
Example #32
0
def book_transactions(request):
    name = request.param

    if name and database_exists(name):
        drop_database(name)
    # create new book
    with create_book(uri_conn=name, currency="EUR", keep_foreign_keys=False) as b:
        # create some accounts
        curr = b.default_currency
        other_curr = b.currencies(mnemonic="USD")
        cdty = Commodity(namespace=u"BEL20", mnemonic=u"GnuCash Inc.", fullname=u"GnuCash Inc. stock")
        asset = Account(name="asset", type="ASSET", commodity=curr, parent=b.root_account)
        foreign_asset = Account(name="foreign asset", type="ASSET", commodity=other_curr, parent=b.root_account)
        stock = Account(name="broker", type="STOCK", commodity=cdty, parent=asset)
        expense = Account(name="exp", type="EXPENSE", commodity=curr, parent=b.root_account)
        income = Account(name="inc", type="INCOME", commodity=curr, parent=b.root_account)

        tr1 = Transaction(
            post_date=date(2015, 10, 21),
            description="my revenue",
            currency=curr,
            splits=[Split(account=asset, value=(1000, 1)), Split(account=income, value=(-1000, 1))],
        )
        tr2 = Transaction(
            post_date=date(2015, 10, 25),
            description="my expense",
            currency=curr,
            splits=[
                Split(account=asset, value=(-100, 1)),
                Split(account=expense, value=(20, 1), memo="cost of X"),
                Split(account=expense, value=(80, 1), memo="cost of Y"),
            ],
        )
        tr_stock = Transaction(
            post_date=date(2015, 10, 29),
            description="my purchase of stock",
            currency=curr,
            splits=[
                Split(account=asset, value=(-200, 1)),
                Split(account=expense, value=(15, 1), memo="transaction costs"),
                Split(account=stock, value=(185, 1), quantity=(6, 1), memo="purchase of stock"),
            ],
        )
        tr_to_foreign = Transaction(
            post_date=date(2015, 10, 30),
            description="transfer to foreign asset",
            currency=curr,
            splits=[
                Split(account=asset, value=(-200, 1)),
                Split(account=foreign_asset, value=(200, 1), quantity=(135, 1)),
            ],
        )
        tr_from_foreign = Transaction(
            post_date=date(2015, 10, 31),
            description="transfer from foreign asset",
            currency=other_curr,
            splits=[
                Split(account=asset, value=(135, 1), quantity=(215, 1)),
                Split(account=foreign_asset, value=(-135, 1)),
            ],
        )
        Price(commodity=cdty, currency=other_curr, date=date(2015, 11, 1), value=(123, 100))
        Price(commodity=cdty, currency=other_curr, date=date(2015, 11, 4), value=(127, 100))
        Price(commodity=cdty, currency=curr, date=date(2015, 11, 2), value=(234, 100))

        b.save()
        yield b

    if name and database_exists(name):
        drop_database(name)
Example #33
0
 def create_book(self):
     book = piecash.create_book(uri_conn=self.dbname, currency='USD')
     book.save()
     book.close()
Example #34
0
import random
import pytest

from piecash import create_book, Account, Transaction, Split, GncValidationError

# create new book
with create_book() as book:
    ra = book.root_account
    eur = book.default_currency

    # number of accounts
    N = 5
    # number of transactions
    T = 100

    # create accounts
    accounts = [
        Account("account {}".format(i), "ASSET", eur, parent=ra)
        for i in range(N)
    ]

    # create transactions
    for i, v in enumerate(random.randrange(10) for j in range(T)):
        tx = Transaction(
            eur,
            "transaction {}".format(i),
        )
        Split(accounts[random.randrange(N)], value=v, transaction=tx)
        Split(accounts[random.randrange(N)], value=-v, transaction=tx)
    book.save()
Example #35
0
#!/usr/bin/env python
# # @file
# @brief Creates a basic set of accounts and a couple of transactions
# @ingroup python_bindings_examples
from decimal import Decimal
import os
import tempfile

from piecash import create_book, Account, Transaction, Split, Commodity
from piecash.core.factories import create_currency_from_ISO

FILE_1 = os.path.join(tempfile.gettempdir(), "example.gnucash")

with create_book(FILE_1, overwrite=True) as book:
    root_acct = book.root_account
    cad = create_currency_from_ISO("CAD")
    expenses_acct = Account(parent=root_acct,
                            name="Expenses",
                            type="EXPENSE",
                            commodity=cad)
    savings_acct = Account(parent=root_acct,
                           name="Savings",
                           type="BANK",
                           commodity=cad)
    opening_acct = Account(parent=root_acct,
                           name="Opening Balance",
                           type="EQUITY",
                           commodity=cad)
    num1 = Decimal("4")
    num2 = Decimal("100")
    num3 = Decimal("15")
def create_simple_book(currency, file_path):
    book = piecash.create_book(currency=currency,
                               sqlite_file=file_path,
                               overwrite=True)

    curr = book.default_currency
    assets = piecash.Account("Assets",
                             "ASSET",
                             curr,
                             parent=book.root_account,
                             placeholder=True)
    acc1 = piecash.Account("Asset #1", "ASSET", curr, parent=assets)
    acc2 = piecash.Account("Asset #2", "ASSET", curr, parent=assets)

    expenses = piecash.Account("Expenses",
                               "EXPENSE",
                               curr,
                               parent=book.root_account,
                               placeholder=True)
    type1 = piecash.Account("Main Type #1",
                            "EXPENSE",
                            curr,
                            parent=expenses,
                            placeholder=True)
    type2 = piecash.Account("Main Type #2",
                            "EXPENSE",
                            curr,
                            parent=expenses,
                            placeholder=True)
    fruits = piecash.Account("Fruits",
                             "EXPENSE",
                             curr,
                             parent=type1,
                             placeholder=True)
    dairy = piecash.Account("Dairy",
                            "EXPENSE",
                            curr,
                            parent=type2,
                            placeholder=True)
    apples = piecash.Account("Apples", "EXPENSE", curr, parent=fruits)
    eggs = piecash.Account("Eggs", "EXPENSE", curr, parent=dairy)

    incomes = piecash.Account("Income",
                              "INCOME",
                              curr,
                              parent=book.root_account,
                              placeholder=True)
    inc1 = piecash.Account("Income #1", "INCOME", curr, parent=incomes)
    inc2 = piecash.Account("Income #2", "INCOME", curr, parent=incomes)

    book.save()

    simple_transactions = [
        (date(year=2019, month=1,
              day=1), acc1, apples, "Apples #1", Decimal("5")),
        (date(year=2019, month=1,
              day=2), acc1, eggs, "Eggs #1", Decimal("10")),
        (date(year=2019, month=1,
              day=3), acc2, apples, "Other Apples", Decimal("4.5"))
    ]

    shop_transactions = [("Shop #1", date(year=2019, month=1, day=10),
                          ((acc1, apples, "Apples #1", Decimal("3")),
                           (acc1, eggs, "Eggs #1", Decimal("7")))),
                         ("Shop #2", date(year=2019, month=1, day=11),
                          ((acc2, apples, "Other Apples", Decimal("3")),
                           (acc1, apples, "Apples #1", Decimal("5"))))]

    income_transactions = [
        (date(year=2019, month=1,
              day=1), inc1, acc1, "Salary", Decimal("1000")),
        (date(year=2019, month=1,
              day=1), inc2, acc2, "Salary", Decimal("1500"))
    ]

    # add 2 income transactions
    for income_tr in income_transactions:
        tr = piecash.Transaction(currency=curr,
                                 description=income_tr[3],
                                 post_date=income_tr[0],
                                 splits=[
                                     piecash.Split(account=income_tr[1],
                                                   value=-income_tr[4]),
                                     piecash.Split(account=income_tr[2],
                                                   value=income_tr[4])
                                 ])
        book.flush()

    # add 3 simple transactions
    for simple_tr in simple_transactions:
        tr = piecash.Transaction(currency=curr,
                                 description=simple_tr[3],
                                 post_date=simple_tr[0],
                                 splits=[
                                     piecash.Split(account=simple_tr[1],
                                                   value=-simple_tr[4]),
                                     piecash.Split(account=simple_tr[2],
                                                   value=simple_tr[4])
                                 ])
        book.flush()

    # add 2 shop transactions
    for shop_tr in shop_transactions:
        shop_name = shop_tr[0]
        day = shop_tr[1]
        list_of_splits = []
        for simple_tr in shop_tr[2]:
            list_of_splits.append(
                piecash.Split(account=simple_tr[0], value=-simple_tr[3]))
            list_of_splits.append(
                piecash.Split(account=simple_tr[1],
                              value=simple_tr[3],
                              memo=simple_tr[2]))
        tr = piecash.Transaction(currency=curr,
                                 description=shop_name,
                                 post_date=day,
                                 splits=list_of_splits)
        book.flush()

    book.save()
Example #37
0
from piecash import open_book, create_book, GnucashException


FILE_1 = os.path.join(tempfile.gettempdir(), "not_there.gnucash")
FILE_2 = os.path.join(tempfile.gettempdir(), "example_file.gnucash")

if os.path.exists(FILE_2):
    os.remove(FILE_2)

# open a file that isn't there, detect the error
try:
    book = open_book(FILE_1)
except GnucashException as backend_exception:
    print("OK", backend_exception)

# create a new file, this requires a file type specification
with create_book(FILE_2) as book:
    pass

# open the new file, try to open it a second time, detect the lock
# using the session as context manager automatically release the lock and close the session
with open_book(FILE_2) as book:
    try:
        with open_book(FILE_2) as book_2:
            pass
    except GnucashException as backend_exception:
        print("OK", backend_exception)

os.remove(FILE_2)
Example #38
0
from __future__ import print_function
from piecash import create_book

# create by default an in memory sqlite version
with create_book(echo=False) as book:

    print("Book is saved:", book.is_saved, end=' ')
    print(" ==> book description:", book.root_account.description)

    print("changing description...")
    book.root_account.description = "hello, book"
    print("Book is saved:", book.is_saved, end=' ')
    print(" ==> book description:", book.root_account.description)

    print("saving...")
    book.save()

    print("Book is saved:", book.is_saved, end=' ')
    print(" ==> book description:", book.root_account.description)

    print("changing description...")
    book.root_account.description = "nevermind, book"
    print("Book is saved:", book.is_saved, end=' ')
    print(" ==> book description:", book.root_account.description)

    print("cancel...")
    book.cancel()

    print("Book is saved:", book.is_saved, end=' ')
    print(" ==> book description:", book.root_account.description)
Example #39
0
def session(request):
    s = create_book()
    return s.session
Example #40
0
from __future__ import print_function
from piecash import create_book

# create by default an in memory sqlite version
book = create_book(echo=False)

print("Book is saved:", book.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("changing description...")
book.root_account.description = "hello, book"
print("Book is saved:", book.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("saving...")
book.save()

print("Book is saved:", book.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("changing description...")
book.root_account.description = "nevermind, book"
print("Book is saved:", book.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)

print("cancel...")
book.cancel()

print("Book is saved:", book.is_saved, end=' ')
print(" ==> book description:", book.root_account.description)
Example #41
0
# coding=utf-8
from __future__ import unicode_literals
import sys
from piecash import open_book, Transaction, Split
from piecash.kvp import Slot
# from gnucash import Session, Account, Transaction, Split, GncNumeric
# import gnucash
from piecash import create_book, Account, Split, Transaction, Commodity, Price
from datetime import datetime

bookname = "/home/sdementen/Projects/piecash/tests/foozbar.sqlite"
bookname = "/home/sdementen/Projects/piecash/gnucash_books/complex_example_piecash.gnucash"

with create_book(bookname, currency="EUR", keep_foreign_keys=False, overwrite=True) as b:
    # create some accounts
    curr = b.default_currency
    other_curr = b.currencies(mnemonic="USD")
    cdty = Commodity(namespace=u"BEL20", mnemonic=u"GnuCash Inc.", fullname=u"GnuCash Inc. stock")
    asset = Account(name="asset", type="ASSET", commodity=curr, parent=b.root_account)
    foreign_asset = Account(name="foreign asset", type="ASSET", commodity=other_curr, parent=b.root_account)
    stock = Account(name="broker", type="STOCK", commodity=cdty, parent=asset)
    expense = Account(name="exp", type="EXPENSE", commodity=curr, parent=b.root_account)
    income = Account(name="inc", type="INCOME", commodity=curr, parent=b.root_account)

    tr1 = Transaction(post_date=datetime(2015, 10, 21),
                      description="my revenue",
                      currency=curr,
                      splits=[
                          Split(account=asset, value=(1000, 1)),
                          Split(account=income, value=(-1000, 1)),
                      ]
#!/usr/bin/env python
##  @file
#   @brief Example Script simple sqlite create
#   @ingroup python_bindings_examples

from __future__ import print_function
import os

from piecash import create_book, Account, Commodity, open_book
from piecash.core.factories import create_currency_from_ISO

filename = os.path.abspath('test.blob')
if os.path.exists(filename):
    os.remove(filename)

with create_book(filename) as book:
    a = Account(parent=book.root_account,
                name="wow",
                type="ASSET",
                commodity=create_currency_from_ISO("CAD"))

    book.save()

with open_book(filename) as book:
    print(book.root_account.children)
    print(book.commodities.get(mnemonic="CAD"))

os.remove(filename)
Example #43
0
def book(request):
    b = create_book()
    return b
Example #44
0
import random
import pytest

from piecash import create_book, Account, Transaction, Split, GncValidationError

# create new book
with create_book() as book:
    ra = book.root_account
    eur = book.default_currency

    # number of accounts
    N = 5
    # number of transactions
    T = 100

    # create accounts
    accounts = [Account("account {}".format(i), "ASSET", eur, parent=ra) for i in range(N)]

    # create transactions
    for i, v in enumerate(random.randrange(10) for j in range(T)):
        tx = Transaction(eur, "transaction {}".format(i))
        Split(accounts[random.randrange(N)], value=v, transaction=tx)
        Split(accounts[random.randrange(N)], value=-v, transaction=tx)
    book.save()

    # select two accounts
    acc = accounts[0]
    tacc = accounts[1]
    # move all splits from account acc to account tacc
    for spl in list(acc.splits):
        spl.account = tacc
Example #45
0
 def create_book(self):
     """Creates a new in-memory book"""
     # piecash.create_book(filename)
     return piecash.create_book()
Example #46
0
def session(request):
    s = create_book()
    return s.session
Example #47
0
def book(request):
    b = create_book()
    return b
Example #48
-1
    def test_open_RW_backup(self, book_uri):
        # create book
        with create_book(uri_conn=book_uri) as b:
            engine_type = b.session.bind.name

        # open book with readonly = False (ie RW)
        if engine_type != "sqlite":
            # raise an exception as try to do a backup on postgres which is not supported yet
            with pytest.raises(GnucashException):
                b = open_book(uri_conn=book_uri, readonly=False)

        elif engine_type == "sqlite":
            # delete all potential existing backup files
            url = book_uri[len("sqlite:///") :]
            for fn in glob.glob("{}.[0-9]*.gnucash".format(url)):
                os.remove(fn)

            # open file in RW without a backup creation
            with open_book(uri_conn=book_uri, readonly=False, do_backup=False) as b:
                pass

            # check no backup file creation
            assert len(glob.glob("{}.[0-9]*.gnucash".format(url))) == 0

            # open file in RW without a backup creation
            with open_book(uri_conn=book_uri, readonly=False) as b:
                pass

            # check backup file creation
            assert len(glob.glob("{}.[0-9]*.gnucash".format(url))) == 1