File indexing completed on 2024-07-21 04:36:26

0001 #!/usr/bin/perl
0002 #
0003 # SPDX-FileCopyrightText: 2019 Thomas Baumgart <tbaumgart@kde.org>
0004 # SPDX-License-Identifier: GPL-2.0-or-later
0005 #
0006 # ----------------------------------------------------------------------
0007 #
0008 # Extract split field values for a specific account and field into a CSV file
0009 #
0010 # The script reads a plain text KMyMoney XML data file on stdin and writes
0011 # the following columns as CSV format on stdout:
0012 #
0013 # transactionId;splitId;<selected-field>[;numeric amount]
0014 #
0015 # in case the selected field is either 'shares' or 'value' the column 'amount'
0016 # will be added to the output which contains the value in a form that can be
0017 # processed by spreadsheet programs
0018 #
0019 #
0020 # usage: zcat data.kmy | getsplitpart.pl --acc=A000002 --field=shares > output.csv
0021 #
0022 
0023 
0024 my @args = @ARGV;
0025 my $accountid;
0026 my $field;
0027 my $fields = ";shares;value;payee;";
0028 my @files = ();
0029 
0030 while ($#args >= 0) {
0031     my $a = shift @args;
0032     $accountid = $1 if ($a =~ /--acc=(.*)/);
0033     $field = $1 if ($a =~ /--field=(.*)/);
0034 }
0035 
0036 die ("Missing account id. Use --acc= to specify.") if ($accountid eq "");
0037 die ("Missing field name. Use --field= to specify.") if ($field eq "");
0038 die ("Field '$field' not supported.") if ($fields !~ /\;$field\;/);
0039 
0040 my $transactionid;
0041 my $splitid;
0042 
0043 # print header line
0044 print "transactionId;splitId;$field";
0045 print ";amount" if ($field =~ /^(shares|value)$/);
0046 print "\n";
0047 
0048 while(<STDIN>) {
0049     if ($_ =~ /<SCHEDULED_TX .+=/) {
0050         $_ =~ /id="([^"]*)"/;
0051         $scheduleid = $1;
0052         next;
0053     }
0054     if ($_ =~ /<TRANSACTION [a-z]+=/) {
0055         $_ =~ /id="([^"]*)"/;
0056         $transactionid = $1;
0057         $transactionid = $scheduleid if($transactionid eq "");
0058         $_ =~ /postdate="([^"]*)"/;
0059         $postdate = $1;
0060         next;
0061     }
0062     if ($_ =~ /<SPLIT [a-z]+=/) {
0063         $_ =~ /id="([^"]*)"/;
0064         $splitid = $1;
0065         if ($_ =~ /account="$accountid"/) {
0066             if ($_ =~ /$field="([^"]*)"/) {
0067                 my $value = $1;
0068                 if ($value =~ /-?[0-9]+\/[0-9]+/) {
0069                     $result = eval $value;
0070                     if ($@) {
0071                         print "Invalid string: '$value'\n";
0072                     } else {
0073                         print "$postdate;$transactionid;$splitid;$value;$result\n";
0074                     }
0075                 } else {
0076                     print "$postdate;$transactionid;$splitid;$value\n";
0077                 }
0078             }
0079         }
0080     }
0081 }