#!/usr/bin/perl

#
#    pb2ofx.pl
#    Version 0.1
#    Copyright 2008, 2009 Peter Vermaas
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

sub printheader
{
	($se,$mi,$ho,$d,$m,$y)=gmtime(time()); # can't assume strftime
	$nowdate=sprintf("%04d%02d%02d%02d%02d%02d",$y+1900,$m+1,$d,$ho,$mi,$se);
	print OUT <<EOT;
<OFX>
<SIGNONMSGSRSV1>
       <SONRS>                          <!-- Begin signon -->
          <STATUS>                      <!-- Begin status aggregate -->
            <CODE>0</CODE>              <!-- OK -->
            <SEVERITY>INFO</SEVERITY>
          </STATUS>
          <DTSERVER>$nowdate</DTSERVER><!-- Oct. 29, 1999, 10:10:03 am -->
          <LANGUAGE>ENG</LANGUAGE>                <!-- Language used in response -->
          <DTPROFUP>$nowdate</DTPROFUP><!-- Last update to profile-->
          <DTACCTUP>$nowdate</DTACCTUP><!-- Last account update -->
          <FI>                          <!-- ID of receiving institution -->
            <ORG>NCH</ORG>              <!-- Name of ID owner -->
            <FID>1001</FID>             <!-- Actual ID -->
          </FI>
       </SONRS>                         <!-- End of signon -->
     </SIGNONMSGSRSV1>
     <BANKMSGSRSV1>
       <STMTTRNRS>                      <!-- Begin response -->
          <TRNUID>1001</TRNUID>         <!-- Client ID sent in request -->
          <STATUS>                      <!-- Start status aggregate -->
            <CODE>0</CODE>              <!-- OK -->
            <SEVERITY>INFO</SEVERITY>
          </STATUS>
EOT
}

sub printfooter
{
	print OUT <<EOT;
             </STMTTRNRS>                           <!-- End of transaction -->
             </BANKMSGSRSV1>
       </OFX>
EOT
}

#
# main
#

#$OUT = $ARGV[0];
if ( $ARGV[0] =~ /^(.*)\.csv$/)
{
	$outfile = "ofx/$1.ofx";
	$OUT = open(OUT, "> $outfile") || die "can't open $outfile: $!";
}

print "IN = $ARGV[0]\n";
print "OUT = $outfile\n";


&printheader();
$mindate=99999999;
$maxdate=0;
$tnr=0;
while (<>)
{
	s/^\"//;	# remove starting "
	s/\"\s*$//;	# remove trailing "
	($t_datum, $t_name, $t_myaccount, $t_otheraccount, $t_code, $t_credit, $t_amount, $t_mu, $t_memo) = split(/\",\"/);
	# print "$t_myaccount, $t_name\n";
	
	if ($t_myaccount =~ /(\d+)/)
	{
		if ($t_datum < $mindate)
		{
			$mindate = $t_datum;
		}
		if ($t_datum > $maxdate)
		{
			$maxdate = $t_datum;
		}
		$accounts{$1}=1;
		if ($t_code eq "IC")
		{
			$trntype = "DIRECTDEBIT";
		} elsif ($t_code eq "GT")	# girotel
		{
			$trntype = "PAYMENT";
		} elsif ($t_code eq "BA")	# betaalautomaat
		{
			$trntype = "POS";
		} elsif ($t_code eq "GM")	# giromaat
		{
			$trntype = "ATM";
		} elsif ($t_code eq "OV")	# overschrijving
		{
			if ($t_credit eq "Bij")
			{
				$trntype = "CREDIT";
			} else {
				$trntype = "DEBIT";
			}
		} elsif ($t_code eq "VZ")	# verzamelgiro
		{
			if ($t_credit eq "Bij")
			{
				$trntype = "CREDIT";
			} else {
				$trntype = "DEBIT";
			}
		} elsif ($t_code eq "DV")	# diversen
		{
			if ($t_credit eq "Bij")
			{
				$trntype = "CREDIT";
			} else {
				$trntype = "DEBIT";
			}
		} else
		{
			$trntype = "OTHER";
		}
		if ($t_credit eq "Bij")
		{
			$amount = $t_amount;
		} else {
			$amount = "-".$t_amount;
		} 
		# verwijder dubbele spaties
		$t_name =~ s/\s{2,}/ /g;
		$t_memo =~ s/\s{2,}/ /g;
		# verwijder spaties aan het einde
		$t_name =~ s/\s+$//;
		$t_memo =~ s/\s+$//;
		#
		$transaction[$tnr]{'account'} = $t_myaccount;
		$transaction[$tnr]{'trntype'} =	$trntype;
		$transaction[$tnr]{'dtposted'} = $t_datum;
		$transaction[$tnr]{'trnamt'} = $amount;
		$transaction[$tnr]{'fitid'} = $t_datum . $t_amount;
		$transaction[$tnr]{'payee'} = $t_name;
		$transaction[$tnr]{'bankacctto'} = $t_otheraccount;
		$transaction[$tnr]{'memo'} = $t_memo;
		#print "$transaction[$#transaction]{'account'}\n";
		$tnr++;
	}
}

foreach my $rekening (keys %accounts)
{
	#print "rekening: $rekening\n";
	print OUT <<EOT;
	<STMTRS>                      <!-- Begin statement response -->
            <CURDEF>EUR</CURDEF>
	<BANKACCTFROM>              <!-- Identify the account -->
                  <BANKID>121099999</BANKID><!-- Routing transit or other FI ID -->
                  <ACCTID>$rekening</ACCTID><!-- Account number -->
                  <ACCTTYPE>CHECKING</ACCTTYPE><!-- Account type -->
        </BANKACCTFROM>             <!-- End of account ID -->
	<BANKTRANLIST>              <!-- Begin list of statement
                                        trans. -->
                  <DTSTART>$mindate</DTSTART>
                  <DTEND>$maxdate</DTEND>
EOT
	for ($tnr=0; $tnr <= $#transaction ; $tnr++)
	{
		#print "$transaction[$tnr]{'account'}, $transaction[$tnr]{'payee'}\n";
		if ($rekening == $transaction[$tnr]{'account'})
		{
			#print "$t_myaccount, $t_name\n";
			print OUT "<STMTTRN>\n";
			print OUT "\t<TRNTYPE>$transaction[$tnr]{'trntype'}</TRNTYPE>\n";
			print OUT "\t<DTPOSTED>$transaction[$tnr]{'dtposted'}</DTPOSTED>\n";
			print OUT "\t<TRNAMT>$transaction[$tnr]{'trnamt'}</TRNAMT>\n";
			print OUT "\t<FITID>$transaction[$tnr]{'fitid'}</FITID>\n";
			print OUT "\t<NAME>$transaction[$tnr]{'payee'}</NAME>\n";
			print OUT "\t<BANKACCTTO>$transaction[$tnr]{'bankacctto'}</BANKACCTTO>\n";
			print OUT "\t<MEMO>$transaction[$tnr]{'memo'}</MEMO>\n";
			print OUT "</STMTTRN>\n";

		}
	}
	print OUT <<EOT;
		    </BANKTRANLIST>                   <!-- End list of statement trans. -->
                    <LEDGERBAL>                       <!-- Ledger balance aggregate -->
                       <BALAMT>0</BALAMT>
                       <DTASOF>199910291120</DTASOF><!-- Bal date: 10/29/99, 11:20 am -->
                    </LEDGERBAL>                      <!-- End ledger balance -->
                 </STMTRS>  
EOT


}
&printfooter();


