
#!/bin/sh
# File	: proc_autoinvoice.sh
# By	: MaartenDeBoper.nl, 190110
# Subject	: Script to process (automatic) invoicing
PGM=`basename $0|cut -d\. -f1`
VER="0.1"
TMP="/tmp/${PGM}.$$"
BASEDIR="${HOME}/autoinvoice"
YRMON="`date +%Y-%m`"
LOG="${BASEDIR}/log/${PGM}-${YRMON}.log"

#MAILTO="maarten@agrarix.nl"
MAILTO="agrarix@xs4all.nl"

DATADIR="${BASEDIR}/data/"
CUSTOMER="bakkerij-vanbreemen"
CSV="${DATADIR}/${CUSTOMER}.csv"

PERIOD="2018-1[012]"

touch ${TMP}

# Init invoice
echo "<HTML>" >> ${TMP}

HEADER=`grep ^# ${CSV}|grep 'HEADER='|cut -d\= -f2`
echo "  <H1> ${HEADER} </H1>" >> ${TMP}
echo "  <H2> Factuur </H2>" >> ${TMP}
NAME=`grep ^# ${CSV}|grep 'NAME='|cut -d\= -f2`
ADDR1=`grep ^# ${CSV}|grep 'ADDRESS1='|cut -d\= -f2`
ADDR2=`grep ^# ${CSV}|grep 'ADDRESS2='|cut -d\= -f2`
echo "  ${NAME} <BR>" >> ${TMP}
echo "  ${ADDR1} <BR>" >> ${TMP}
echo "  ${ADDR2} <BR>" >> ${TMP}

DATE=`grep ^# ${CSV}|grep 'DATE='|cut -d\= -f2`
if [ "${DATE}" = "" ]; then
  DATE=`date +%d-%m-%Y`
fi
echo "  <DIV align=right> " >> ${TMP}
echo "  Factuurdatum: ${DATE} <BR>" >> ${TMP}
echo "  </DIV> " >> ${TMP}

NUMBER=`grep ^# ${CSV}|grep 'NUMBER='|cut -d\= -f2`

echo "  <DIV align=right> " >> ${TMP}
echo "  Factuurperiode: ${PERIOD} <BR>" >> ${TMP}
echo "  </DIV> " >> ${TMP}

# 2nd part; the invoice lines
echo "  <P>" >> ${TMP}

echo "  <TABLE border=1 width=100%> " >> ${TMP}
echo "  <TR> " >> ${TMP}
echo "    <TD><B>Product</TD> <TD><B>Omschrijving</TD> <TD><B>Periode</TD> <TD><B>Bedrag</TD> " |tee -a ${TMP}
echo "  </TR> " >> ${TMP}

TOTAL=0
cat ${CSV}|grep -v ^#| while read LINE
do
  
  echo "LINE=${LINE}"

# #Product;Omschrijving;Periode;Bedrag;
  PROD=`echo ${LINE}|grep -v ^#|awk -F\; '{print $1}'`
  OMSCHR=`echo ${LINE}|grep -v ^#|awk -F\; '{print $2}'`
  PERIODE=`echo ${LINE}|grep -v ^#|awk -F\; '{print $3}'|grep "${PERIOD}"`
  BEDRAG=`echo ${LINE}|grep -v ^#|awk -F\; '{print $4}'`

  if [ "${PERIODE}" != "" ]; then
    echo "    <TR>" >> ${TMP}
    echo "      <TD>${PROD}</TD> <TD>${OMSCHR}</TD> <TD>${PERIODE}</TD> <TD>${BEDRAG} euro</TD> " |tee -a ${TMP}
    TOTAL=`expr ${TOTAL} + ${BEDRAG}`
    echo ${TOTAL} > ${TMP}.ttl
    echo "    </TR>" >> ${TMP}
  fi

done  # cat LINE
echo "    <TR>" >> ${TMP}
TOTAL=`cat ${TMP}.ttl`
rm ${TMP}.ttl
echo "    <TD><B>Totaal</TD> <TD> </TD> <TD> </TD> <TD>${TOTAL} euro</TD> " |tee -a ${TMP}
echo "    </TR>" >> ${TMP}
echo "  </TABLE> " >> ${TMP}

if [ "${FOOTER}" = "" ]; then
  FOOTER=`grep ^# ${CSV}|grep 'FOOTER='|cut -d\= -f2`
  echo "  <H6> <CENTER> ${FOOTER} </CENTER> </H6>" >> ${TMP}
fi
echo "</HTML>" >> ${TMP}

if [ -s ${TMP} ]; then
  cat ${TMP}| mailx --append="Content-type: text/html" -s "(auto) invoice" ${MAILTO}
  echo "  Mailed to ${MAILTO}" |tee -a ${LOG}
fi


rm ${TMP}
exit 0

