% This is an example document accompanying "LaTeX for Administrative Work"
% See www.dickimaw-books.com/latex/admin/ for the book details,
% including licence.
%
% arara: pdflatex
\documentclass{isodoc}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{datatool}

\DTLloaddb{orders}{orders.csv}
\DTLloaddb{ordergroups}{ordergroups.csv}
\DTLloaddb{books}{booklist.csv}
\DTLloaddb{countries}{country-codes.csv}
\DTLloaddb{people}{people.csv}

\DTLassignfirstmatch{ordergroups}{id}{2}{%
  \CustomerId=customerid,%
  \OrderDiscount=discount,%
  \Postage=postage%
}
\xDTLassignfirstmatch{people}{id}{\CustomerId}{%
  \Title=title,%
  \Forenames=forenames,%
  \Surname=surname,%
  \AddressI=address1,%
  \AddressII=address2,%
  \Town=town,%
  \County=county,%
  \Postcode=postcode,%
  \CountryCode=country%
}
\xDTLassignfirstmatch{countries}{code}{\CountryCode}{\CountryName=name}

\begin{document}
\newcommand*{\CurrentTotal}{0}% initialise running total
\newcommand*{\mytablecontents}{}% initialise hook

\DTLforeach*[\equal{\OrderGroupId}{2}]{orders}%
{%
  \OrderGroupId=groupid,%
  \BookId=bookid,%
  \OrderQuantity=quantity%
}%
{%
  \xDTLassignfirstmatch{books}{id}{\BookId}%
  {%
    \BookTitle=title,%
    \BookAuthor=author,%
    \BookFormat=format,%
    \BookPrice=price%
  }%
% Compute quantity x price:
  \dtlmul{\subtotal}{\OrderQuantity}{\BookPrice}%
% Add to the running total:
  \dtladd{\CurrentTotal}{\CurrentTotal}{\subtotal}%
% Round to 2 d.p.
  \dtlround{\subtotal}{\subtotal}{2}%
% Append to hook:
  \eappto\mytablecontents{\noexpand\iitem{\OrderQuantity\ $\times$ ``\BookTitle''
  @ \BookPrice\ each}{\subtotal}}
}%
% Round the subtotal to 2 d.p.
\dtlround{\subtotal}{\CurrentTotal}{2}%
% Add postage to running total:
\dtladd{\CurrentTotal}{\CurrentTotal}{\Postage}%
% Subtract discount from running total:
\dtlsub{\CurrentTotal}{\CurrentTotal}{\OrderDiscount}%
% Round to 2 d.p.:
\dtlround{\CurrentTotal}{\CurrentTotal}{2}%

\invoice
[
  to={\DTLifnullorempty{\Title}{}{\Title\ }%
  \Forenames\ \Surname\\%
  \AddressI\\%
  \DTLifnullorempty{\AddressII}{}{\AddressII\\}%
  \Town\\%
  \DTLifnullorempty{\County}{}{\County\\}%
  \Postcode\\%
  \CountryName},
  currency={\pounds}
]
{
  \itable
  {
    \mytablecontents
    \itotal[Subtotal]{\subtotal}
    \iitem{Postage and Packaging}{\Postage}
    \iitem{Promotional Discount}{$-\OrderDiscount$}
    \itotal{\CurrentTotal}
  }
}

\end{document}
