MT940-Import: Implementation eines eigenen Parsers anstelle von AQBanking
[kivitendo-erp.git] / SL / Helper / MT940.pm
1 package SL::Helper::MT940;
2
3 use strict;
4 use File::Path qw(mkpath);
5 use File::Copy qw(copy);
6
7 sub convert_mt940_data {
8   my ($mt940_data) = @_;
9
10   # takes the data from an uploaded mt940 file, converts it to csv via aqbanking and returns the converted data
11   # The uploaded file data is stored as a session file, just like the aqbanking settings file.
12
13   my $import_filename = 'bank_transfer.940';
14   my $sfile = SL::SessionFile->new($import_filename, mode => '>');
15   $sfile->fh->print($mt940_data);
16   $sfile->fh->close;
17
18   # create needed dir structure for aqbanking 5.x and 6.x
19   my $todir = $sfile->get_path . '/imexporters/csv/profiles';
20   mkpath $todir;
21   die "Cannot create $todir" unless -d $todir;
22
23   File::Copy::copy('users/aqbanking.conf', $todir.'/kivi.conf');
24   die "Cannot create local aqbanking conf " unless -f $todir.'/kivi.conf';
25
26   mkpath $sfile->get_path . '/settings6/aqbanking';
27
28   my $aqbin = $::lx_office_conf{applications}->{aqbanking};
29   die "Can't find aqbanking-cli, please check your configuration file.\n" unless -f $aqbin;
30   my $cmd = "$aqbin --cfgdir=\"" . $sfile->get_path . "\" import --importer=\"swift\" --profile=\"SWIFT-MT940\" -f " .
31           $sfile->get_path . "/$import_filename | $aqbin --cfgdir=\"" . $sfile->get_path . "\" export --profile=kivi 2> /dev/null ";
32
33   my $converted_data = '"empty";"local_bank_code";"local_account_number";"remote_bank_code";"remote_account_number";"transdate";"valutadate";"amount";'.
34     '"currency";"remote_name";"remote_name_1";"purpose";"purpose1";"purpose2";"purpose3";"purpose4";"purpose5";"purpose6";"purpose7";"purpose8";"purpose9";'.
35     '"purpose10";"purpose11";"transaction_key";"customer_reference";"bank_reference";"transaction_code";"transaction_text"'."\n";
36
37   open my $mt, "-|", "$cmd" || die "Problem with executing aqbanking\n";
38   my $headerline = <$mt>;  # discard original aqbanking header line
39   while (<$mt>) {
40     $converted_data .= $_;
41   };
42   close $mt;
43   return $converted_data;
44 };
45
46 1;