def from_account_two(book):
    """Test piecash Account #2 (Asset)"""
    from_account = piecash.Account("Test Asset Account 2",
                                   "ASSET",
                                   book.default_currency,
                                   parent=book.root_account)
    book.save()
    return from_account
def to_account_two(book):
    """Test piecash Account #2 (Expense)"""
    to_account = piecash.Account("Test Expense Account 2",
                                 "EXPENSE",
                                 book.default_currency,
                                 parent=book.root_account)
    book.save()
    return to_account
def add_account(book, new_acct_name, parent, currency='USD'):
    """Add a GnuCash account with name `new_acct_name` and a parent account of `parent`.

    Optionally set USD
    """
    parent_account = book.accounts.get(fullname=parent)
    if parent_account:
        # Ensure no account already exists with the requested name
        child_accts = [child.name.lower() for child in parent_account.children]
        if new_acct_name.lower() in child_accts:
            logger.warning(
                f'The {new_acct_name} account already exists as a child of your {parent} account. Skipping'
            )
            return False
        # Grab the account type of the parent account
        # To keep things simple, the child inherits the parent's account type
        parent_account_type = parent_account.type
    else:
        logger.error(f'There was no parent account named "{parent}"')
        return False

    commodity = book.commodities.get(mnemonic=currency)
    if parent_account and commodity and parent_account_type:
        new_account = piecash.Account(name=new_acct_name,
                                      type=parent_account_type,
                                      parent=parent_account,
                                      commodity=commodity)
        try:
            book.save()
        except GnucashException as gce:
            logger.critical('Encounted GnuCash Error while saving book:')
            logger.critical(gce)
            sys.exit(1)
        else:
            logger.info(
                f'Successfully saved book with new account "{new_acct_name}", child of parent account "{parent}"'
            )
            return True

    else:
        logger.error(
            f'There was no parent account named "{parent}", no parent account type, or no commodity named "{currency}"'
        )
        return False
Beispiel #4
0
def import2cash(transactions_compiled, path_to_Book):
    """Write compiled transactions to GNUCash Book"""

    logger.info(f'Function start')
    logger.info(f'Length of transactions_compiled: {len(transactions_compiled.index)}')

    book = piecash.open_book(path_to_Book.as_posix(), readonly=False)

    # if the GNUCash Book has one currency, use that currency
    if len(book.commodities) == 1:
        currency = book.commodities[0]
    else:
        raise RuntimeError(
            'GNUCash Book must have 1 commodity. Please make GitHub issue if this is an issue for you.'
        )

    # create "Uncategorized" account if none exists
    try:
        book.accounts(name='Uncategorized')
    except:
        _ = piecash.Account(
            "Uncategorized", "EXPENSE", currency, parent=book.root_account)
        book.save()

    for index, transaction in transactions_compiled.iterrows():
        logger.debug(
            f'COMPILEDINDEX={index}, writing transaction to GNUCashBook')
        _ = piecash.Transaction(
            currency=currency,
            description=transaction['description'],
            post_date=transaction['post_date'].date(),
            splits=[
                piecash.Split(
                    account=book.accounts(
                        name=transaction['split1']['account']),
                    value=transaction['split1']['value']),
                piecash.Split(
                    account=book.accounts(
                        name=transaction['split2']['account']),
                    value=transaction['split2']['value'])
            ])

    book.save()
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()
Beispiel #6
0
import piecash

book = piecash.create_book(
    keep_foreign_keys=True,
    uri_conn="mysql+pymysql://cohirer:Letsgo!@localhost/pieledger?charset=utf8&use_unicode=0",
    overwrite=True
)

acc = piecash.Account(
    name="My account",
    type="ASSET",
    parent=book.root_account,
    commodity=book.commodities.get(mnemonic="EUR"),
    placeholder=True)

book.save()