gcinvoice
=========

About
-----

**gcinvoice** generates invoices from Gnucash XML files using templates.

gcinvoice (http://www.smoerz.org/gcinvoice) is a tool to parse Gnucash XML data
files, and create invoices from this data using templates. It is similar to
g2latex (http://stefans.datenbruch.de/gnucash/gc2latex.shtml) by Stefan
Tomanek, but the latter was not powerful enough for my needs, and did somehow
not work for me.

Features of gcinvoice:

* works with data files from Gnucash starting with version 2.0, tested up
  to Gnucash 3.1.

* does *not* need the gnucash python bindings, but reads the Gnucash
  XML-file directly from python.

* powerful templating; not only latex, but arbitrary templates can be used.

* full support for discount and taxes, but **warning**:

  In my opinion, POSTTAX discounts in Gnucash are not very useful, see
  bug https://bugs.gnucash.org/show_bug.cgi?id=520547  in the Gnucash bug
  database. As long there is not an option in gnucash to calculate
  tax included discounts a better way, gcinvoice abuses POSTTAX to calculate
  the taxes the way I think it should be, and thus gives a different result
  for invoices with such discounts. If such discounts occure in a invoice
  generated by gcinvoice, a warning is generated.

* needs only a working Python version 2.7 or 3.x installation (tested with 2.7
  and 3.4). There are no external requirements, apart from the future module if
  running with python 2.7.

* can be run standalone, or easily integrated into python applications.

* gcinvoice is free software.

License and Credits
-------------------

gcinvoice was written by Roman Bertle <bertle@smoerz.org> 2007-2008. It
contains an adapted version of YAPTU, a templating utility written by Alex
Martelli (ActiveState python Cookbook recipe 52305). gcinvoice has been
refactored and ported to python3 by Fabian Köster 2017, and rewritten by
Roman Bertle in 2018.

gcinvoice is published under the MIT Licence.

Installation
------------

The only prerequisite of gcinvoice is a working installation of Python.
For python 2.7, package 'future' has to be installed. For python 3.x, no
additional packages are needed.

Installation using pip
~~~~~~~~~~~~~~~~~~~~~~

gcinvoice can be installed using pip from https://pypi.org/::

  python -m pip install gcinvoice

See the python installation documentation for options
(https://packaging.python.org/tutorials/installing-packages). For exampe, to
install into the user install directory::

  python -m pip install --user gcinvoice

Building from source
~~~~~~~~~~~~~~~~~~~~

For building from source, download the sdist using pip from https://pypi.org/::

  python -m pip download --no-binary gcinvoice

Install the build dependencies, if not already installed::

  python -m pip install setuptools wheel

Untar the file and enter the directory::

  tar xvfz gcinvoice-X.Y.Z.tar.gz
  cd gcinvoice-X.Y.Z

Build a wheel::

  python setup.py bdist_wheel

Install the wheel using pip::

  python -m pip install dist/gcinvoice-*.whl


Testing
-------

From the unpacked source directory, various tests can be run after
gcinvoice have been installed. To this end change into the 'tests'
directory and run e.g.::

  python test.py

There might be a warning about a missing locale 'de_DE.UTF'; this special
locale is used to test formatting of currency and quantity values. If it is
not available, these tests are not performed, but this does not indicate any
further problems. One test (testScriptrun) might also fail if you have
already installed a global /etc/gcinvoicerc or a $HOME/.gcinvoicerc, or have
a changed gcinvoicerc in the directory you run the test from, because it
assumes the default settings of gcinvoice.

If package 'pytest' is installed, the tests are nicer run by::

  python -m pytest test.py

Usage
-----

There are two ways to use gcinvoice. First, it can be run as a
stand-alone script by simply executing it. Installing gcinvoice provides
a script 'create_gcinvoice'. The help message can be got typing::

  create_gcinvoice --help

An example for running gcinvoice as a script::

  create_gcinvoice -t mytemplate.tex  -o out.tex 13

This uses the invoice with id '13' to fill out the template 'mytemplate.tex'
and put the result into 'out.tex'. The gnucash data file is inferred in this
example from the configuration files, as described in the next section.

Another way is to import gcinvoice from your python session::

  import gcinvoice

See the docstring of gcinvoice.Gcinvoice for further information.

Configuration
-------------

gcinvoice reads configuration files from the following places:

* /etc/gcinvoicerc

* $HOME/.gcinvoicerc

* ./gcinvoicerc

and all files given to gcinvoice as a configuration option. The format of
the configuration files is defined by the python standard library module
'ConfigParser'; the file 'gcinvoicerc' in folder 'tests' of the source
distribution of gcinvoice is a well documented sample configuration file
which can be adapted for your needs.

Templates
---------

gcinvoice uses a template file to generate invoices from the parsed
Gnucash data. The templating engine 'YAPTU' is built into gcinvoice, for
detailed information see
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305.
In short, the template file can contain python statements, and python
expressions identified by (configurable) regular expressions. There is
no restriction on the used python code, hence be careful, a malicious
template could execute any code.

The source distribution of gcinvoice contains an example template file
'tests/invoice_template.tex'.

By default, python expressions are written as @{}, where the expression
is inside the curly brackets. Below are the defined variables extracted
from the Gnucash data file, with there type indicated. These variables
can also be None if not found in the Gnucash data file. The type
'formatted' is special: For each of such a variable 'x', there is a
variable `x_`, which is a decimal.Decimal instance. The variable 'x' is
the value formatted as a string according to the configurated settings.

::

  guid        -- The guid of the invoice (string).
  id          -- The id of the invoice (int if possible, else string).
  billing_id  -- The billing_id of the invoice (string).
  owner       -- The owner (customer or vendor) of the invoice (dict).
  job         -- The job of the invoice (dict).
  date_opened -- The open date of the invoice (Date).
  date_posted -- The post date of the invoice (Date).
  terms       -- The terms of the invoice (dict).
  notes       -- The notes of the invoice (string).
  currency    -- The currency of the invoice (string).
  entries     -- The entries of the invoice (list).
  amount_net  -- The total net amount of the invoice (formatted).
  amount_gross -- The total gross amount of the invoice (formatted).
  amount_taxes -- The total amount of taxes of the invoice (formatted).

In addition these useful functions and classes are provided::

  _currencyformatting -- A function to format monetary values.
  _quantityformatting -- A function to format other quantities.
  cformat -- The function to format monetary values as used by gcinvoice.
  qformat -- The function to format other quantities as used by gcinvoice.
  Decimal -- The decimal.Decimal class.

The dict 'owner' contains data of the customer or vendor::

  guid        -- The guid of the owner (string).
  id          -- The id of the owner (int if possible, else string).
  name        -- The name of the owner (string).
  address     -- The address of the owner (list of strings).
  email       -- The email of the (string).
  full_name   -- The full name of the (string).

The dict 'job' containes::

  guid        -- The guid of the job (string).
  id          -- The id of the job (int if possible, else string).
  name        -- The name of the job (string).
  reference   -- The reference of the job (string).
  owner       -- The owner (customer or vendor) of the job (dict).
                 The owner of the invoice is also accessible directly
                 in variable 'owner', see above.

The dict 'terms' contains::

  guid        -- The guid of the terms (string).
  name        -- The name of the terms (string).
  desc        -- The description of the terms (string).
  due-days    -- The due days of the terms (string).
  disc-days   -- The discount days of the terms (string).
  discount    -- The discount of the terms (Decimal number).

'entries' is a list of dicts, where amount_net, amount_gross and
amount_taxes are amounts after applying the discount::

  guid        -- The guid of the entry (string).
  date        -- The date of the entry (Date).
  entered     -- The datetime of entering of the entry (DateTime).
  description -- The description of the entry (string).
  action      -- The action of the entry (action).
  qty         -- The quantity of the entry (formatted).
  price       -- The price of the entry (formatted).
  amount_raw  -- The amount of the entry as entered into Gnucash,
        i.e. qty x price (formatted).
  amount_net  -- The amount of the entry without taxes (formatted).
  amount_gross -- The amount of the entry including taxes (formatted).
  amount_taxes -- The amount of the taxes for the entry (formatted).
  amount_discount -- The amount of the discount for the entry (formatted).
        for POSTTAX, this is the gross discount, else its the net discount.
  discount    -- The discount of the entry (Decimal number).
  discount_type -- The type of the discount (DISCOUNT/VALUE) (string).
  discount_how -- Taxing of the discount (PRETAX/SAMETIME/POSTTAX) (string).
  taxable     -- Flag if the entry is taxable (int).
  taxincluded -- Flag if the tax is included in amount_raw (int).
  taxtable    -- Tax table for the entry (dict).

The dict 'taxtable' contains::

  guid        -- The guid of the taxtable (string).
  name        -- The name of the taxtable (string).
  percent_sum -- Sum of percent entries of the taxtable (Decimal number).
  value_sum   -- Sum of value entries of the taxtable (Decimal number).

Python statements are identified by default by lines in the template
starting either with '%+', '%-' or '%='. The first one is for start
statements like 'for e in entries' or 'if ...', the second one marks
usually empty lines ending a python 'if' or 'for' construct, and the last
one is for continuations like e.g. 'else'.

Be aware that a template file must be encoded either as ascii or UTF-8.

Issues
------

* Because templates can contain arbitrary python expression, malicious
  templates could execute code with the permissions of the user.

* I think that the calculation on POSTAX discounts is not useful in Gnucash
  (see bug report https://bugs.gnucash.org/show_bug.cgi?id=520547). gcinvoice
  calculates such discounts in invoices in a way which is more useful, but
  unfortunately still missing in Gnucash. Hence the result differs for
  invoices with such discounts from the Gnucash result.

Possible Improvements
---------------------

* After porting to python3, one test does not work any more and is skipped
  for now.

* rewrite gcinvoice using a functional instead of an object oriented style.

* Implement accessing not only XML-files, but also the database backends of
  Gnucash.

* After python2.7 is obsolete, remove python 2 compatibility.

* Testing on windows

* Alternative templating engines like jinja2.
