Ejemplo n.º 1
0
    def test_create_person_taxtabme(self, book_basic, Person):
        if Person is Employee:
            return

        EUR = book_basic.commodities(namespace="CURRENCY")

        # create person detached from book with a specific id
        taxtable = Taxtable(
            name="Local tax",
            entries=[
                TaxtableEntry(type="percentage",
                              amount=Decimal("6.5"),
                              account=Account(name="MyAcc",
                                              parent=book_basic.root_account,
                                              commodity=EUR,
                                              type="ASSET"))
            ])
        te = TaxtableEntry(type="percentage",
                           amount=Decimal("6.5"),
                           account=Account(name="MyOtherAcc",
                                           parent=book_basic.root_account,
                                           commodity=EUR,
                                           type="ASSET"),
                           taxtable=taxtable)

        c = Person(name="John Föo",
                   currency=EUR,
                   taxtable=taxtable,
                   book=book_basic)
        assert len(taxtable.entries) == 2
        assert taxtable.entries[0].account.parent == book_basic.root_account

        book_basic.flush()

        assert book_basic.taxtables == [taxtable]
Ejemplo n.º 2
0
    def test_create_parentless_account(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create an account without parent that is not ROOT
        acc = Account(name="test account", type="ASSET", commodity=EUR)
        new_book.add(acc)
        with pytest.raises(ValueError):
            new_book.validate()
        new_book.cancel()

        # create an account without parent that is ROOT but with wrong name
        acc = Account(name="test account", type="ROOT", commodity=EUR)
        new_book.add(acc)
        with pytest.raises(ValueError):
            new_book.validate()
        new_book.cancel()

        # create an account without parent that is ROOT with correct name
        acc = Account(name="Root Account", type="ROOT", commodity=EUR)
        new_book.add(acc)
        new_book.flush()

        assert len(new_book.accounts) == 0
        root_accs = new_book.query(Account).all()
        assert len(root_accs) == 3
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
    def test_add_account_incompatible(self, book):
        # test compatibility between child account and parent account
        for acc_type1 in ACCOUNT_TYPES - root_types:
            acc1 = Account(name=acc_type1,
                           type=acc_type1,
                           parent=book.root_account,
                           commodity=None)
        book.save()

        assert len(book.accounts) == 13
        for acc_type1 in ACCOUNT_TYPES - root_types:
            acc1 = book.accounts(name=acc_type1)
            for acc_type2 in ACCOUNT_TYPES:
                if not _is_parent_child_types_consistent(
                        acc_type1, acc_type2, []):
                    acc2 = Account(name=acc_type2,
                                   type=acc_type2,
                                   parent=acc1,
                                   commodity=None)
                    with pytest.raises(ValueError):
                        book.validate()
                    book.cancel()
        book.save()

        assert len(book.accounts) == 13
Ejemplo n.º 5
0
    def test_add_account_compatibility(self, session):
        # test compatibility between child account and parent account
        for acc_type1 in ACCOUNT_TYPES - root_types:
            acc1 = Account(name=acc_type1,
                           type=acc_type1,
                           parent=session.book.root_account,
                           commodity=None)

            for acc_type2 in ACCOUNT_TYPES:

                if not _is_parent_child_types_consistent(acc_type1, acc_type2):
                    with pytest.raises(ValueError):
                        acc2 = Account(name=acc_type2,
                                       type=acc_type2,
                                       parent=acc1,
                                       commodity=None)
                else:
                    acc2 = Account(name=acc_type2,
                                   type=acc_type2,
                                   parent=acc1,
                                   commodity=None)

        session.save()

        assert len(session.accounts) == 100
Ejemplo n.º 6
0
 def test_scu(self, new_book):
     EUR = new_book.commodities[0]
     acc = Account(name="test", type="ASSET", commodity=EUR)
     assert acc.commodity_scu == EUR.fraction
     assert not acc.non_std_scu
     acc.commodity_scu = 100
     assert acc.non_std_scu
     acc.commodity_scu = None
     assert acc.commodity_scu == EUR.fraction
     assert not acc.non_std_scu
Ejemplo n.º 7
0
 def test_scu(self, new_book):
     EUR = new_book.commodities[0]
     acc = Account(name="test", type="ASSET", commodity=EUR)
     assert acc.commodity_scu == EUR.fraction
     assert not acc.non_std_scu
     acc.commodity_scu = 100
     assert acc.non_std_scu
     acc.commodity_scu = None
     assert acc.commodity_scu == EUR.fraction
     assert not acc.non_std_scu
Ejemplo n.º 8
0
    def test_add_account_compatibility(self, book):
        # test compatibility between child account and parent account
        for acc_type1 in ACCOUNT_TYPES - root_types:
            acc1 = Account(name=acc_type1, type=acc_type1, parent=book.root_account, commodity=None)
            for acc_type2 in ACCOUNT_TYPES:
                if _is_parent_child_types_consistent(acc_type1, acc_type2, []):
                    acc2 = Account(name=acc_type2, type=acc_type2, parent=acc1, commodity=None)

        book.save()

        assert len(book.accounts) == 100
Ejemplo n.º 9
0
 def test_create_samenameandparent_accounts(self, new_book):
     EUR = new_book.commodities[0]
     racc = new_book.root_account
     acc1 = Account(name="test account",
                    type="ASSET",
                    commodity=EUR,
                    parent=racc)
     acc2 = Account(name="test account",
                    type="ASSET",
                    commodity=EUR,
                    parent=racc)
     with pytest.raises(ValueError):
         new_book.validate()
Ejemplo n.º 10
0
    def test_create_standardliability_account(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create normal account
        acc = Account(name="test account", type="LIABILITY", commodity=EUR, parent=racc)
        new_book.flush()
        assert len(new_book.accounts) == 1
        assert acc.non_std_scu == 0
        assert acc.commodity_scu == EUR.fraction
        assert acc.get_balance() == 0
        assert acc.sign == -1
        assert not acc.is_template
Ejemplo n.º 11
0
 def test_add_account_names(self, book):
     # raise ValueError as acc1 and acc2 shares same parents with same name
     acc1 = Account(name="Foo", type="MUTUAL", parent=book.root_account, commodity=None)
     acc2 = Account(name="Foo", type="BANK", parent=book.root_account, commodity=None)
     with pytest.raises(ValueError):
         book.save()
     book.cancel()
     # ok as same name but different parents
     acc3 = Account(name="Fooz", type="BANK", parent=book.root_account, commodity=None)
     acc4 = Account(name="Fooz", type="BANK", parent=acc3, commodity=None)
     book.save()
     # raise ValueError as now acc4 and acc3 shares same parents with same name
     acc4.parent = acc3.parent
     with pytest.raises(ValueError):
         book.save()
Ejemplo n.º 12
0
    def test_create_standardliability_account(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create normal account
        acc = Account(name="test account",
                      type="LIABILITY",
                      commodity=EUR,
                      parent=racc)
        new_book.flush()
        assert len(new_book.accounts) == 1
        assert acc.non_std_scu == 0
        assert acc.commodity_scu == EUR.fraction
        assert acc.get_balance() == 0
        assert acc.sign == -1
        assert not acc.is_template
Ejemplo n.º 13
0
    def test_create_samenameanddifferentparent_accounts(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create 2 accounts with same name but different parent
        acc1 = Account(name="test account",
                       type="ASSET",
                       commodity=EUR,
                       parent=racc)
        acc2 = Account(name="test account",
                       type="ASSET",
                       commodity=EUR,
                       parent=acc1)
        new_book.flush()
        assert acc1.fullname == "test account"
        assert acc2.fullname == "test account:test account"
Ejemplo n.º 14
0
    def test_create_children_accounts(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create account with unknown type
        acc = Account(name="test account",
                      type="ASSET",
                      commodity=EUR,
                      parent=racc,
                      children=[
                          Account(name="test sub-account",
                                  type="ASSET",
                                  commodity=EUR)
                      ])
        new_book.flush()
        assert len(acc.children) == 1
Ejemplo n.º 15
0
    def test_create_nobook_account(self, new_book):
        USD = Commodity(namespace="FOO", mnemonic="BAZ", fullname="cuz")

        # create account with no book attachable to it
        with pytest.raises(ValueError):
            acc = Account(name="test account", type="ASSET", commodity=USD)
            new_book.flush()
Ejemplo n.º 16
0
    def test_example(self, realbook_session):
        book = realbook_session

        # example 1, print all stock prices in the Book
        # display all prices
        for price in book.query(Price).all():
            print(
                "{}/{} on {} = {} {}".format(
                    price.commodity.namespace,
                    price.commodity.mnemonic,
                    price.date,
                    float(price.value_num) / price.value_denom,
                    price.currency.mnemonic,
                )
            )

        for account in book.accounts:
            print(account)

        # build map between account fullname (e.g. "Assets:Current Assets" and account)
        map_fullname_account = {account.fullname: account for account in book.query(Account).all()}

        # use it to retrieve the current assets account
        print(map_fullname_account)
        acc_cur = map_fullname_account["Assets:Current Assets"]

        # retrieve EUR currency
        EUR = book.commodities.get(mnemonic="EUR")

        # add a new subaccount to this account of type ASSET with currency EUR
        Account(name="new savings account", type="ASSET", parent=acc_cur, commodity=EUR)

        # save changes
        with pytest.raises(GnucashException) as excinfo:
            book.save()
Ejemplo n.º 17
0
 def test_sign_accounts(self, new_book):
     EUR = new_book.commodities[0]
     neg = "EQUITY,PAYABLE,LIABILITY,CREDIT,INCOME".split(",")
     pos = "STOCK,MUTUAL,EXPENSE,BANK,TRADING,CASH,ASSET,RECEIVABLE".split(
         ",")
     all = neg + pos
     for acc in all:
         assert Account(name=acc, type=acc,
                        commodity=EUR).sign == (1 if acc in pos else -1)
Ejemplo n.º 18
0
    def test_create_unknowntype_account(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create account with unknown type
        with pytest.raises(ValueError):
            acc = Account(name="test account",
                          type="FOO",
                          commodity=EUR,
                          parent=racc)
            new_book.validate()
Ejemplo n.º 19
0
    def test_create_unicodename_account(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create normal account
        acc = Account(name=u"inouï étrange",
                      type="ASSET",
                      commodity=EUR,
                      parent=racc)
        new_book.flush()
        assert len(new_book.accounts) == 1
        assert len(repr(acc)) >= 2
Ejemplo n.º 20
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")
Ejemplo n.º 21
0
    def test_create_root_subaccount(self, new_book):
        EUR = new_book.commodities[0]
        racc = new_book.root_account

        # create root account should raise an exception
        acc = Account(name="subroot accout",
                      type="ROOT",
                      commodity=EUR,
                      parent=racc)
        with pytest.raises(ValueError):
            new_book.validate()

        # except if we add the control_mode 'allow-root-subaccounts' to the book
        new_book.control_mode.append("allow-root-subaccounts")
        new_book.validate()

        assert len(new_book.accounts) == 1
Ejemplo n.º 22
0
 def test_add_account_names(self, book):
     # raise ValueError as acc1 and acc2 shares same parents with same name
     acc1 = Account(name="Foo", type="MUTUAL", parent=book.root_account, commodity=None)
     acc2 = Account(name="Foo", type="BANK", parent=book.root_account, commodity=None)
     with pytest.raises(ValueError):
         book.save()
     book.cancel()
     # ok as same name but different parents
     acc3 = Account(name="Fooz", type="BANK", parent=book.root_account, commodity=None)
     acc4 = Account(name="Fooz", type="BANK", parent=acc3, commodity=None)
     book.save()
     # raise ValueError as now acc4 and acc3 shares same parents with same name
     acc4.parent = acc3.parent
     with pytest.raises(ValueError):
         book.save()
Ejemplo n.º 23
0
from piecash import open_book, Budget
from piecash._common import Recurrence
from piecash import create_book, Account, Transaction, Split





# create a book (in memory)
s = create_book(currency="EUR")
# get the EUR and create the USD currencies
c1 = s.book.default_currency
c2 = s.book.create_currency_from_ISO("USD")
# create two accounts
a1 = Account("Acc 1", "ASSET", c1, parent=s.book.root_account)
a2 = Account("Acc 2", "ASSET", c2, parent=s.book.root_account)
# create a transaction from a1 to a2
tr = Transaction(currency=c1,
                 description="transfer",
                 splits=[
                     Split(account=a1, value=-100),
                     Split(account=a2, value=100, quantity=30)
                 ])
s.flush()

# ledger_str() returns a representation of the transaction in the ledger-cli format
tr.ledger_str()

# change the book to use the "trading accounts" options
s.book.use_trading_accounts = True
Ejemplo n.º 24
0
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()

    # select two accounts
    acc = accounts[0]
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
# @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")

    # create transaction with core objects in one step
    trans1 = Transaction(currency=cad,
Ejemplo n.º 27
0
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)),
                      ]
                      )
    tr2 = Transaction(post_date=datetime(2015, 10, 25),
                      description="my expense",
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
Ejemplo n.º 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()
Ejemplo n.º 30
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)
def add_transaction(t):

    settings_file = os.environ['HOME'] + "/gnucash/settings.yaml"

    with open(settings_file) as ymlfile:
        settings = yaml.load(ymlfile)

    book_path = settings['location'] + settings['gnucash']
    log_file = settings['location'] + settings['log']

    # check for existance of to_account and from_account
    book = piecash.open_book(book_path)
    to_account_found = False
    from_account_found = False

    for a in book.accounts:
        if a.fullname == t.account:
            from_account_found = True
        elif a.fullname == t.expense:
            to_account_found = True

    success = True

    expense_account_created = False

    try:
        # income - allow for not found accounts to instead go to Imbalance account
        if t.income:
            if not to_account_found:
                t.account = 'Imbalance'
            if not from_account_found:
                t.expense = 'Imbalance'
        # expense - allow creation of expense accounts ONLY
        #         - allow not found "from" accounts to instead go to Imbalance account
        else:
            # add missing expense account
            if not to_account_found:
                with open_book(book_path, open_if_lock=True,
                               readonly=False) as book:

                    acc = book.root_account
                    for subacc in book.root_account.children:
                        if subacc.name == 'Expenses':
                            acc = subacc
                            break

                    # could change this and loop to support mutli-level expense account creation
                    #t.expense = 'Expense:' + t.expense.split(':')[-1]

                    a = Account(
                        parent=acc,
                        name=t.expense.split(':')[-1],
                        type="EXPENSE",
                        description='Automatically Added from SMS transaction.',
                        commodity=book.commodities.get(mnemonic="USD"))

                    book.save()
                to_account_found = True
                expense_account_created = True
            if not from_account_found:
                t.account = "Imbalance"

        # reopen the book and add a transaction
        # this must be a sqlite3 file
        with open_book(book_path, open_if_lock=True, readonly=False) as mybook:

            today = datetime.now()
            today = today.replace(microsecond=0)

            # retrieve the currency from the book
            USD = mybook.currencies(mnemonic='USD')

            # define the amount as Decimal
            amount = t.amount

            # retrieve accounts
            to_account = mybook.accounts(fullname=t.expense)
            from_account = mybook.accounts(fullname=t.account)

            # if income, flip the accounts so 'income' is used instead of 'charge'
            if t.income:
                to_account = mybook.accounts(fullname=t.account)
                from_account = mybook.accounts(fullname=t.expense)

            # create the transaction with its two splits
            Transaction(post_date=today,
                        enter_date=today,
                        currency=USD,
                        description=t.description,
                        splits=[
                            Split(account=to_account,
                                  value=amount,
                                  memo='Automated from script'),
                            Split(account=from_account,
                                  value=-amount,
                                  memo='Automated from script'),
                        ])

            # save the book
            mybook.save()
    except:
        success = False

    log(success, t, to_account_found, from_account_found,
        expense_account_created, log_file)