Example #1
0
    def setUp(self):
        BookSession.setUp(self)

        self.today = datetime.today()

        self.bank = Account(self.book)
        self.bank.SetType(ACCT_TYPE_BANK)
        self.bank.SetCommodity(self.currency)
        self.income = Account(self.book)
        self.income.SetType(ACCT_TYPE_INCOME)
        self.income.SetCommodity(self.currency)
        self.receivable = Account(self.book)
        self.receivable.SetType(ACCT_TYPE_RECEIVABLE)
        self.receivable.SetCommodity(self.currency)

        self.customer = Customer(self.book,'CustomerID',self.currency)
        self.vendor = Vendor(self.book,'VendorID',self.currency)
        self.employee = Employee(self.book,'EmployeeID',self.currency)
        self.job = Job(self.book,'JobID',self.customer)

        self.invoice = Invoice(self.book,'InvoiceID',self.currency,self.customer)
        self.invoice.SetDateOpened(self.today)
        entry = Entry(self.book)
        entry.SetDate(self.today)
        entry.SetDescription("Some income")
        entry.SetQuantity(GncNumeric(1))
        entry.SetInvAccount(self.income)
        entry.SetInvPrice(GncNumeric(100))
        self.invoice.AddEntry(entry)

        self.invoice.PostToAccount(self.receivable,
            self.today, self.today, "", True, False)
Example #2
0
def __invoice__str__(self):
    """__str__ method for Invoice"""

    from gnucash.gnucash_business import Invoice
    self = Invoice(instance=self)

    # This dict and the return statement can be changed according to individual needs
    fmt_dict = {
        "id_name": "ID:",
        "id_value": self.GetID(),
        "notes_name": "Notes:",
        "notes_value": self.GetNotes(),
        "active_name": "Active:",
        "active_value": str(self.GetActive()),
        "owner_name": "Owner Name:",
        "owner_value": self.GetOwner().GetName(),
        "total_name": "Total:",
        "total_value": str(self.GetTotal()),
        "currency_mnemonic": self.GetCurrency().get_mnemonic()
    }

    ret_invoice= ("{id_name:4}{id_value:10} {notes_name:7}{notes_value:20} {active_name:8}{active_value:7} {owner_name:12}{owner_value:20}"+
                  "{total_name:8}{total_value:10}{currency_mnemonic:3}").\
                    format(**all_as_classwithcutting__format__keys(**fmt_dict))

    ret_entries = ""
    entry_list = self.GetEntries()
    for entry in entry_list:  # Type of entry has to be checked
        if not (type(entry) == Entry):
            entry = Entry(instance=entry)
        ret_entries += "  " + str(entry) + "\n"

    return ret_invoice + "\n" + ret_entries
Example #3
0
def __invoice__str__(self):
    """__str__ method for invoice class"""
    
    from gnucash.gnucash_business import Invoice
    self=Invoice(instance=self)

    return unicode(self).encode('utf-8')
Example #4
0
def get_invoices(book, customer=None, days=None):
    invoices = []
    query = Query()
    query.set_book(book)
    query.search_for("gncInvoice")
    if customer:
        query.add_guid_match(["owner", "guid"], customer.GetGUID(),
                             QOF_QUERY_AND)
    if days:
        date_posted = date.today() - timedelta(days=days)
        pred_data = QueryDatePredicate(QOF_COMPARE_GTE, 2, date_posted)
        query.add_term(["date_posted"], pred_data, QOF_QUERY_AND)
    for result in query.run():
        invoices.append(Invoice(instance=result))
    return invoices
Example #5
0
def get_all_invoices_from_lots(account):
  """Return all invoices in account and descendants

  This is based on lots. So invoices without lots will be missed."""

  lot_list=get_all_lots(account)
  invoice_list=[]
  for lot in lot_list:
    if type(lot).__name__ == 'SwigPyObject':
        lot = gnucash.GncLot(instance=lot)

    invoice=gnucash.gnucash_core_c.gncInvoiceGetInvoiceFromLot(lot.instance)
    if invoice:
      invoice_list.append(Invoice(instance=invoice))
  return invoice_list
Example #6
0
def get_all_invoices(book, is_paid=None, is_active=None):
    """Returns a list of all invoices in the book.

    posts a query to search for all invoices.

    arguments:
        book                the gnucash book to work with
    keyword-arguments:
        is_paid     int     1 to search for invoices having been paid, 0 for not, None to ignore.
        is_active   int     1 to search for active invoices
    """

    query = gnucash.Query()
    query.search_for('gncInvoice')
    query.set_book(book)

    if is_paid == 0:
        query.add_boolean_match([gnucash.INVOICE_IS_PAID], False,
                                gnucash.QOF_QUERY_AND)
    elif is_paid == 1:
        query.add_boolean_match([gnucash.INVOICE_IS_PAID], True,
                                gnucash.QOF_QUERY_AND)
    elif is_paid == None:
        pass

    # active = JOB_IS_ACTIVE
    if is_active == 0:
        query.add_boolean_match(['active'], False, gnucash.QOF_QUERY_AND)
    elif is_active == 1:
        query.add_boolean_match(['active'], True, gnucash.QOF_QUERY_AND)
    elif is_active == None:
        pass

    # return only invoices (1 = invoices)
    pred_data = gnucash.gnucash_core.QueryInt32Predicate(
        gnucash.QOF_COMPARE_EQUAL, 1)
    query.add_term([gnucash.INVOICE_TYPE], pred_data, gnucash.QOF_QUERY_AND)

    invoice_list = []

    result = query.run()
    for result in query.run():
        invoice_list.append(Invoice(instance=result))

    query.destroy()

    return invoice_list
Example #7
0
s = Session(argv[1], is_new=False)

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

my_customer = book.CustomerLookupByID(argv[2])
assert (my_customer != None)
assert (isinstance(my_customer, Customer))

assets = root.lookup_by_name("Assets")
receivables = assets.lookup_by_name("Receivables")
income = root.lookup_by_name("Income")

invoice = Invoice(book, argv[3], CAD, my_customer)
description = argv[4]
invoice_value = gnc_numeric_from_decimal(Decimal(argv[5]))
tax_table = book.TaxTableLookupByName('good tax')
invoice_entry = Entry(book, invoice)
invoice_entry.SetInvTaxTable(tax_table)
invoice_entry.SetInvTaxIncluded(False)
invoice_entry.SetDescription(description)
invoice_entry.SetQuantity(GncNumeric(1))
invoice_entry.SetInvAccount(income)
invoice_entry.SetInvPrice(invoice_value)

invoice.PostToAccount(receivables, datetime.date.today(),
                      datetime.date.today(), "", True, False)

s.save()
    # not required, but a good idea because the GUI insists on basic address info
    address = new_customer.GetAddr()
    address.SetName("Bill & Bob")
    address.SetAddr1("201 Nowhere street")

    new_employee = Employee(book, "2", CAD, "Reliable employee")

    new_vendor = Vendor(book, "3", CAD, "Dependable vendor")

    new_job = Job(book, "4", new_vendor, "Good clean, fun")

    # 7% tax
    tax_table = TaxTable(book, "good tax",
                         TaxTableEntry(a5, True, GncNumeric(700000, 100000)))

    invoice_customer = Invoice(book, "5", CAD, new_customer)
    customer_extract = invoice_customer.GetOwner()
    assert (isinstance(customer_extract, Customer))
    assert (customer_extract.GetName() == new_customer.GetName())

    invoice_employee = Invoice(book, "6", CAD, new_employee)
    employee_extract = invoice_employee.GetOwner()
    assert (isinstance(employee_extract, Employee))
    assert (employee_extract.GetName() == new_employee.GetName())

    invoice_vendor = Invoice(book, "7", CAD, new_vendor)
    vendor_extract = invoice_vendor.GetOwner()
    assert (isinstance(vendor_extract, Vendor))
    assert (vendor_extract.GetName() == new_vendor.GetName())

    invoice_job = Invoice(book, "8", CAD, new_job)
Example #9
0
File: tax.py Project: jfishe/qb2gnc
def new_transaction(root, book, out, USD):
    # global existing_customers, existing_vendors
    # Assemble the invoice dictionary
    isinvoice = False
    isbill = False
    isinvpayment = False
    isbillpayment = False
    isentry = False

    for row in out:
        if 'type' in row.keys():
            rtype = row['type']
        else:
            rtype = ''

        if rtype:
            new_rtype, date_opened = get_rtype(row)
            new_rtype['entries'] = []

            if rtype == 'Invoice':
                isinvoice = True
            elif rtype == 'Payment':
                isinvpayment = True
            elif rtype == 'Sales Tax Payment':
                isentry = True
            elif rtype == 'Paycheck':
                continue
            elif rtype == 'Bill':
                isbill = True
            elif rtype == 'Credit':
                isbill = True
            elif rtype == 'Bill Pmt -CCard':
                isbillpayment = True
            else:
                isentry = True

        elif 'account' in row.keys():
            if row['account']:
                test, new_entry = get_entries(row, date_opened)
                if test == 'tax_table':
                    new_rtype['tax_table'] = new_entry['tax_table']
                    new_rtype['tax_rate'] = new_entry['price']
                elif test == 'entry':
                    new_rtype['entries'].append(new_entry)

                    # No account in total row, so process entries
        elif isentry:
            trans1 = Transaction(book)
            trans1.BeginEdit()
            trans1.SetCurrency(USD)
            if 'owner' in new_rtype.keys():
                trans1.SetDescription(new_rtype['owner'])
            trans1.SetDateEnteredTS(
                new_rtype['date_opened'] + datetime.timedelta(microseconds=1))
            trans1.SetDatePostedTS(
                new_rtype['date_opened'] + datetime.timedelta(microseconds=1))
            if 'num' in new_rtype.keys():
                trans1.SetNum(new_rtype['num'])
            if 'notes' in new_rtype.keys():
                trans1.SetNotes = new_rtype['notes']

            if new_rtype['account'] != '-SPLIT-':
                split1 = Split(book)
                split1.SetParent(trans1)
                # if new_rtype['type'] == 'Deposit':
                # new_rtype['amount'] = new_rtype['amount'].neg()
                split1.SetAccount(root.lookup_by_name(new_rtype['account']))
                # if split1.GetAccount() == ACCT_TYPE_EQUITY:
                # isequity = True
                # new_rtype['amount'] = new_rtype['amount'].neg()
                # else:
                # isequity = False
                split1.SetValue(new_rtype['amount'])
                if 'owner' in new_rtype.keys():
                    split1.SetMemo(new_rtype['owner'])
                    # split1.SetAction(get_action(new_rtype['type']))

            for entry in new_rtype['entries']:
                if 'amount' in entry.keys():
                    split1 = Split(book)
                    split1.SetParent(trans1)
                    # if isequity:
                    # entry['amount'] = entry['amount'].neg()
                    split1.SetValue(entry['amount'])
                    split1.SetAccount(root.lookup_by_name(entry['account']))
                    if 'description' in entry.keys():
                        split1.SetMemo(entry['description'])
            # split1.SetAction(get_action(new_rtype['type']))
            trans1.CommitEdit()

            isentry = False

        elif isinvpayment:
            try:
                owner = GetCustomers.iscustomer(new_rtype['owner'])
                assert (isinstance(owner, Customer))
            except AssertionError:
                print 'Customer %s does not exist; skipping' % \
                      new_rtype['owner']
                continue

            xfer_acc = root.lookup_by_name(new_rtype['account'])
            date_opened = new_rtype['date_opened']
            if 'notes' in new_rtype.keys():
                notes = new_rtype['notes']
            else:
                notes = ''
            if 'num' in new_rtype.keys():
                num = new_rtype['num']
            else:
                num = ''
            for entry in new_rtype['entries']:
                posted_acc = root.lookup_by_name(entry['account'])

                owner.ApplyPayment(None, None, posted_acc, xfer_acc,
                                   new_rtype['amount'], entry['amount'],
                                   date_opened, notes, num, False)
            isinvpayment = False

        elif isbillpayment:
            try:
                owner = GetVendors.isvendor(new_rtype['owner'])
                assert (isinstance(owner, Vendor))
            except AssertionError:
                print 'Vendor %s does not exist; skipping' % \
                      new_rtype['owner']
                continue

            xfer_acc = root.lookup_by_name(new_rtype['account'])
            date_opened = new_rtype['date_opened']
            if 'notes' in new_rtype.keys():
                notes = new_rtype['notes']
            else:
                notes = ''
            if 'num' in new_rtype.keys():
                num = new_rtype['num']
            else:
                num = ''
            for entry in new_rtype['entries']:
                posted_acc = root.lookup_by_name(entry['account'])

                owner.ApplyPayment(None, None, posted_acc, xfer_acc,
                                   new_rtype['amount'], entry['amount'],
                                   date_opened, notes, num, False)
            isbillpayment = False

        # new_customer.ApplyPayment(self, invoice, posted_acc, xfer_acc, amount,
        # exch, date, memo, num)
        # new_customer.ApplyPayment(None, None, a2, a6, GncNumeric(100,100),
        # GncNumeric(1), datetime.date.today(), "", "", False)

        # invoice_customer.ApplyPayment(None, a6, GncNumeric(7,100),
        # GncNumeric(1), datetime.date.today(), "", "")

        elif isbill:
            # put item on entries!!!
            # Accumulate splits
            # QuickBooks Journal has a total row after splits,
            # which is used to detect the end of splits.
            try:
                owner = GetVendors.isvendor(new_rtype['owner'])
                assert (isinstance(owner, Vendor))
            except AssertionError:
                print 'Vendor %s does not exist; skipping' % \
                      new_rtype['owner']
                continue

            try:
                cid = book.BillNextID(owner)
            # save Bill ID and tax rate for xml overlay.
            # ReplaceTax.bill(cid, new_rtype['tax_rate'])
            except:
                raise

            bill_vendor = Bill(book, cid, USD, owner)
            vendor_extract = bill_vendor.GetOwner()
            assert (isinstance(vendor_extract, Vendor))
            assert (vendor_extract.GetName() == owner.GetName())

            if new_rtype['type'] == 'Credit':
                bill_vendor.SetIsCreditNote(True)

            bill_vendor.SetDateOpened(new_rtype['date_opened'])

            if 'notes' in new_rtype.keys():
                bill_vendor.SetNotes(new_rtype['notes'])

            if 'num' in new_rtype.keys():
                bill_vendor.SetBillingID(new_rtype['num'])

            if 'tax_table' in new_rtype.keys():
                tax_table = book.TaxTableLookupByName(new_rtype['tax_table'])
                assert (isinstance(tax_table, TaxTable))

            # Add the entries
            for entry in new_rtype['entries']:
                # skip entries that link COGS and Billentory
                if 'quantity' not in entry.keys():
                    continue
                bill_entry = Entry(book, bill_vendor)

                account = root.lookup_by_name(entry['account'])
                assert (isinstance(account, Account))
                bill_entry.SetBillAccount(account)

                if 'tax_table' in new_rtype.keys():
                    bill_entry.SetBillTaxTable(tax_table)
                    bill_entry.SetBillTaxIncluded(False)
                else:
                    bill_entry.SetBillTaxable(False)

                if 'description' in entry.keys():
                    bill_entry.SetDescription(entry['description'])
                bill_entry.SetQuantity(entry['quantity'])
                bill_entry.SetBillPrice(entry['price'])
                bill_entry.SetDateEntered(entry['date'])
                bill_entry.SetDate(entry['date'])
                if 'notes' in entry.keys():
                    bill_entry.SetNotes(entry['notes'])

            isbill = False

            # Post bill
            account = root.lookup_by_name(new_rtype['account'])
            assert (isinstance(account, Account))
            bill_vendor.PostToAccount(account, new_rtype['date_opened'], new_rtype['date_opened'],
                                      str(new_rtype['owner']), True, False)

        elif isinvoice:
            # put item on entries!!!
            # Accumulate splits
            # QuickBooks Journal has a total row after splits,
            # which is used to detect the end of splits.
            try:
                owner = GetCustomers.iscustomer(new_rtype['owner'])
                assert (isinstance(owner, Customer))
            except AssertionError:
                print 'Customer %s does not exist; skipping' % \
                      new_rtype['owner']
                continue

            try:
                cid = book.InvoiceNextID(owner)
            # save Invoice ID and tax rate for xml overlay.
            # ReplaceTax.invoice(cid, new_rtype['tax_rate'])
            except:
                raise

            invoice_customer = Invoice(book, cid, USD, owner)
            customer_extract = invoice_customer.GetOwner()
            assert (isinstance(customer_extract, Customer))
            assert (customer_extract.GetName() == owner.GetName())

            invoice_customer.SetDateOpened(new_rtype['date_opened'])

            if 'notes' in new_rtype.keys():
                invoice_customer.SetNotes(new_rtype['notes'])

            if 'num' in new_rtype.keys():
                invoice_customer.SetBillingID(new_rtype['num'])

            if 'tax_table' in new_rtype.keys():
                tax_table = book.TaxTableLookupByName(new_rtype['tax_table'])
                assert (isinstance(tax_table, TaxTable))

            # assert( not isinstance( \
            # book.InvoiceLookupByID(new_rtype['id']), Invoice))

            # Add the entries
            for entry in new_rtype['entries']:
                invoice_entry = Entry(book, invoice_customer)

                account = root.lookup_by_name(entry['account'])
                assert (isinstance(account, Account))
                invoice_entry.SetInvAccount(account)

                if 'tax_table' in new_rtype.keys():
                    invoice_entry.SetInvTaxTable(tax_table)
                    invoice_entry.SetInvTaxIncluded(False)
                else:
                    invoice_entry.SetInvTaxable(False)

                invoice_entry.SetDescription(entry['description'])
                invoice_entry.SetQuantity(entry['quantity'])
                invoice_entry.SetInvPrice(entry['price'])
                invoice_entry.SetDateEntered(entry['date'])
                invoice_entry.SetDate(entry['date'])
                if 'notes' in entry.keys():
                    invoice_entry.SetNotes(entry['notes'])

            isinvoice = False

            # Post invoice
            account = root.lookup_by_name(new_rtype['account'])
            assert (isinstance(account, Account))
            invoice_customer.PostToAccount(account, new_rtype['date_opened'], new_rtype['date_opened'],
                                           str(new_rtype['owner']), True, False)
            # ReplaceTax.replace(gnc_file.path)

    return 0
Example #10
0
# not required, but a good idea because the GUI insists on basic address info
address = new_customer.GetAddr()
address.SetName("Bill & Bob")
address.SetAddr1("201 Nowhere street")

new_employee = Employee(book, "2", CAD, "Reliable employee")

new_vendor = Vendor(book, "3", CAD, "Dependable vendor")

new_job = Job(book, "4", new_vendor, "Good clean, fun")

# 7% tax
tax_table = TaxTable(book, "good tax",
                     TaxTableEntry(a5, True, GncNumeric(700000, 100000)))

invoice_customer = Invoice(book, "5", CAD, new_customer)
customer_extract = invoice_customer.GetOwner()
assert (isinstance(customer_extract, Customer))
assert (customer_extract.GetName() == new_customer.GetName())

invoice_employee = Invoice(book, "6", CAD, new_employee)
employee_extract = invoice_employee.GetOwner()
assert (isinstance(employee_extract, Employee))
assert (employee_extract.GetName() == new_employee.GetName())

invoice_vendor = Invoice(book, "7", CAD, new_vendor)
vendor_extract = invoice_vendor.GetOwner()
assert (isinstance(vendor_extract, Vendor))
assert (vendor_extract.GetName() == new_vendor.GetName())

invoice_job = Invoice(book, "8", CAD, new_job)
Example #11
0
    session.end()
    session.destroy()
    quit()

invoice = book.InvoiceLookupByID("0000157")
if invoice:
    print "Found Invoice!"
    if invoice.IsPosted() or invoice.IsPaid():
        print "Cannot modify posted or paid invoices"
        session.end()
        session.destroy()
        quit()  # Or try next invoice
else:  # No currebt invoice found so create a new invoice TODO need to lookup next free Invoice ID perhaps?
    print "Creating a new invoice"
    invoice = Invoice(
        book, 'TEST', gbp, customer
    )  # I know, need to check of this exists too!!  But this is a test script so...
    # NB Gnucash will happily make another invoice/bill with the same ID!  I think this is a bad thing.
    invoice.SetDateOpened(datetime.date.today())

if invoice:  # Test code
    invoice.GetID()

# Create a new entry and populate it.  Normally there would be a loop for each entry required, reading from a csv or similar
entry = gnucash.gnucash_business.Entry(book, invoice)
entry.SetDate(datetime.date.today())
entry.SetDateEntered(datetime.date.today())
entry.SetDescription("Some stuff I sold")
entry.SetAction("Material")
entry.SetInvAccount(income)
entry.SetQuantity(GncNumeric(1))
Example #12
0
if income.GetType() == -1:
    print "Didn't get income account exiting"
    session.end()
    quit()
assets = root.lookup_by_name("Assets")
recievables = assets.lookup_by_name("Accounts Recievable")
comm_table = book.get_table()
gbp = comm_table.lookup("CURRENCY", "GBP")
customer = book.CustomerLookupByID(CUSTOMER_ID)
assert (customer != None)
assert (isinstance(customer, Customer))

from gnucash.gnucash_core_c import gncInvoiceNextID
iID = gncInvoiceNextID(book.get_instance(),
                       customer.GetEndOwner().get_instance()[1])
invoice = Invoice(book, iID, gbp, customer)
assert (invoice != None)
assert (isinstance(invoice, Invoice))
invoice.SetDateOpened(datetime.date.today())

csv_line = "date,task,duration,rate\r\n"
csv_file.write(csv_line)
for line in data:
    date = line[0]
    task = line[2]
    duration = str(line[3])
    (h, m, s) = duration.split(':')
    d_duration = float(int(h) * 3600 + int(m) * 60 +
                       int(s)) / 3600  # Convert to a decimal fraction
    #print d_duration
    csv_line = str(date) + "," + task + "," + str(duration) + "," + str(