#! /usr/bin/perl -w
# Filename:     acctcnvt
# Description:  Perl script to convert the accounting data from CSV file into PostgreSQL
# Author:       imacat <imacat@mail.imacat.idv.tw>
# Date:         2007-09-24
# Copyright:    (c) 2007 imacat

use 5.006;
use strict;
use warnings;
use DBI qw();
use Encode qw(encode decode FB_CROAK);
use Fcntl qw(:flock :seek);
use File::Basename qw(basename);
use Getopt::Long qw(GetOptions);
use Term::ReadKey qw(ReadMode);
# Prototype declaration
sub main();
sub parse_args();
sub try_login($);
sub newsn();
sub table_cols($$);
sub usersn($$);
sub xfread($);
sub xfupdate($$);
sub get_accounting_data($);
sub acct_recs_to_trxs(@);
sub r2t_fundin($\@);
sub r2t_transfer($\@);
sub r2t_interest($\@);
sub r2t_phone($\@);
sub r2t_temp($\@);
sub r2t_miscin($\@);
sub r2t_expense($\@);
sub trxs_to_sqls($$@);
sub map_acct_subjs($);

use vars qw($THIS_FILE $VERSION $VERBOSE);
$THIS_FILE = basename($0);
$VERSION = "1.14";
$VERBOSE = 1;

use vars qw($DEFUSER $USER $PGDATABASE $FILE $OUTFILE);
$DEFUSER = exists $ENV{"PGUSER"}? $ENV{"PGUSER"}:
    (getpwuid($>)   or die "$THIS_FILE: getpwuid: $!");
$PGDATABASE = "wov";
use constant IMPORTER => "importer";

use vars qw($VERMSG $SHORTHELP $HELPMSG);
$VERMSG = "$THIS_FILE v$VERSION by imacat <imacat\@mail.imacat.idv.tw>";
$SHORTHELP = "Try `$THIS_FILE --help' for more information.";
$HELPMSG = << "EOT";
Usage: $THIS_FILE [options] source output
Convert the accounting data from CSV file into PostgreSQL

  -U,--username=NAME  Database user name (default: $DEFUSER)
  -d,--debug          Display debug messages.  Multiple --debug to debug more.
  -q,--quiet          Disable debug messages.  An opposite that cancels the
                      effect of --debug.
  -h,--help           Display this help.
  -v,--version        Display version number.
  source              The source CSV file.
  output              File to output the result SQL script.

EOT

main;
exit 0;

# main: Main program
sub main() {
    local ($_, %_);
    my ($dbh, $sql, $sth, $usersn, @recs, @trxs, @sqls);
    
    # Parse the arguments
    parse_args;
    
    # Try to log in
    $dbh = try_login "dbi:Pg:dbname=$PGDATABASE;";
    $sql = "SET NAMES 'utf8';\n";
    $dbh->do($sql)                      or die "$THIS_FILE: $sql: " . $dbh->errstr;
    $sql = "LOCK TABLE acctsubj, users IN SHARE MODE;\n";
    $dbh->do($sql)                      or die "$THIS_FILE: $sql: " . $dbh->errstr;
    $usersn = usersn $dbh, IMPORTER;
    
    # Read the CSV accounting data file
    @recs = get_accounting_data $FILE;
    # Convert the accounting records to accounting transactions
    @trxs = acct_recs_to_trxs @recs;
    # Convert the accounting transactions to SQL statements
    @sqls = trxs_to_sqls $dbh, $usersn, @trxs;
    # Output the SQL statements
    $_ = join "", @sqls;
    $_ = encode("UTF-8", $_, FB_CROAK);
    xfupdate $OUTFILE, $_;
    
    $dbh->disconnect                    or die "$THIS_FILE: " . $dbh->errstr;
    undef $dbh;
    
    print STDERR "Done.  " . (time - $^T) . " seconds elapsed.\n"
        if $VERBOSE > 0;
    return;
}

# parse_args: Parse the arguments
sub parse_args() {
    local ($_, %_);
    
    # Get the arguments
    eval {
        local $SIG{"__WARN__"} = sub { die $_[0]; };
        Getopt::Long::Configure(qw(no_auto_abbrev bundling));
        GetOptions( "username|U=s"=>\$USER,
                    "debug|d+"=>\$VERBOSE,
                    "quiet|q"=>sub { $VERBOSE-- if $VERBOSE > 0; },
                    "help|h"=>sub { print $HELPMSG; exit 0; },
                    "version|v"=>sub { print "$VERMSG\n"; exit 0; });
    };
    die "$THIS_FILE: $@$SHORTHELP\n" if $@ ne "";
    
    $| = 1 if $VERBOSE > 0;
    
    # Check the arguments
    # The source CSV file
    die "$THIS_FILE: Please specify the source CSV file\n$SHORTHELP\n"
        if @ARGV == 0;
    $FILE = shift @ARGV;
    # The output file
    die "$THIS_FILE: Please specify the output file\n$SHORTHELP\n"
        if @ARGV == 0;
    $OUTFILE = shift @ARGV;
    
    die "$THIS_FILE: Too many arguments: $ARGV[0]\n$SHORTHELP\n"
        if @ARGV > 0;
    
    # The database user
    $USER = $DEFUSER if !defined $USER;
    
    #binmode STDOUT, "encoding(big5)";
    
    return;
}

# try_login: Try to log in, and request the password when required.
sub try_login($) {
    local ($_, %_);
    my ($dsn, $dbh, $subseq, $passwd);
    $dsn = $_[0];
    $subseq = 0;
    # Try to log in
    while (!defined($dbh = DBI->connect($dsn, $USER, $passwd, { PrintError => 0 }))) {
        $_ = DBI->errstr;
        if ($subseq) {
            print STDERR $_;
            sleep 5;
        }
        $subseq = 1;
        # Obtain the current login user
        $USER = $1 if !defined $USER && / failed for user "(.+?)"/;
        # Disable console echo
        ReadMode 2;
        print STDERR defined $USER? "PostgreSQL password for $USER: ":
            "PostgreSQL password: ";
        $passwd = <STDIN>;
        print STDERR "\n";
        die "$THIS_FILE: Failed connecting to the PostgreSQL server\n"
            if !defined $passwd;
        chomp $passwd;
        # Restore console echo status
        ReadMode 0;
    }
    # Return the database handle
    return $dbh;
}

{
my %SN;
# newsn: Generate a new random S/N
sub newsn() {
    local ($_, %_);
    do {
        $_ = 100000000 + int rand 900000000;
    } until !exists $SN{$_};
    return $_;
}
}

{
my %cols;
# table_cols: Obtain the columns of a specific SQL table
sub table_cols($$) {
    local ($_, %_);
    my ($dbh, $table, $sth);
    ($dbh, $table) = @_;
    
    return @{$cols{$table}} if exists $cols{$table};
    
    $sth = $dbh->column_info(undef, undef, $table, "%")
                                        or die "$THIS_FILE: $table: " . $dbh->errstr;
    @_ = qw();
    push @_, $_ while defined($_ = $sth->fetchrow_hashref);
    undef $sth;
    $cols{$table} = [ map $$_{"COLUMN_NAME"},
        sort { ${$a}{"ORDINAL_POSITION"} <=> ${$b}{"ORDINAL_POSITION"} } @_ ];
    s/"(.+)"/$1/ foreach @{$cols{$table}};
    
    return @{$cols{$table}};
}
}

{
my %USERSN;
# usersn: Find the S/N of the user
sub usersn($$) {
    local ($_, %_);
    my ($dbh, $id, $sql, $sth);
    ($dbh, $id) = @_;
    
    return $USERSN{$id} if exists $USERSN{$id};
    
    $sql = "SELECT sn FROM users"
        . " WHERE id=" . $dbh->quote($id) . ";\n";
    $sth = $dbh->prepare($sql)          or die "$THIS_FILE: $sql: " . $dbh->errstr;
    $sth->execute                       or die "$THIS_FILE: $sql: " . $sth->errstr;
    die "$THIS_FILE: $id: no such user in table \"users\"\n"
        if $sth->rows != 1;
    
    return ($USERSN{$id} = ${$sth->fetch}[0]);
}
}

# xfread: Read from a file
sub xfread($) {
    local ($_, %_);
    my ($FH, $file);
    $file = $_[0];
    
    # Return as lines
    if (wantarray) {
        open $FH, $file                 or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_SH              or die "$THIS_FILE: $file: $!";
        @_ = <$FH>;
        flock $FH, LOCK_UN              or die "$THIS_FILE: $file: $!";
        close $FH                       or die "$THIS_FILE: $file: $!";
        return @_;
    
    # A scalar file content
    } else {
        # Regular files
        if (-f $file) {
            my $size;
            @_ = stat $file             or die "$THIS_FILE: $file: $!";
            $size = $_[7];
            return "" if $size == 0;
            open $FH, $file             or die "$THIS_FILE: $file: $!";
            flock $FH, LOCK_SH          or die "$THIS_FILE: $file: $!";
            read $FH, $_, $size         or die "$THIS_FILE: $file: $!";
            flock $FH, LOCK_UN          or die "$THIS_FILE: $file: $!";
            close $FH                   or die "$THIS_FILE: $file: $!";
            return $_;
        
        # Special files
        } else {
            open $FH, $file             or die "$THIS_FILE: $file: $!";
            flock $FH, LOCK_SH          or die "$THIS_FILE: $file: $!";
            $_ = join "", <$FH>;
            flock $FH, LOCK_UN          or die "$THIS_FILE: $file: $!";
            close $FH                   or die "$THIS_FILE: $file: $!";
            return $_;
        }
    }
}

# xfupdate: Update a file
sub xfupdate($$) {
    local ($_, %_);
    my ($FH, $file, $content);
    ($file, $content) = @_;
    
    if (-e $file) {
        open $FH, "+<$file"             or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_SH              or die "$THIS_FILE: $file: $!";
        $_ = join "", <$FH>;
        if ($_ ne $content) {
            seek $FH, 0, SEEK_SET       or die "$THIS_FILE: $file: $!";
            truncate $FH, 0             or die "$THIS_FILE: $file: $!";
            print $FH $content          or die "$THIS_FILE: $file: $!";
        }
        flock $FH, LOCK_UN              or die "$THIS_FILE: $file: $!";
        close $FH                       or die "$THIS_FILE: $file: $!";
    
    } else {
        open $FH, ">$file"              or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_EX              or die "$THIS_FILE: $file: $!";
        print $FH $content              or die "$THIS_FILE: $file: $!";
        flock $FH, LOCK_UN              or die "$THIS_FILE: $file: $!";
        close $FH                       or die "$THIS_FILE: $file: $!";
    }
    return;
}

# get_accounting_data: Parse the CSV file and obtain the accounting data
sub get_accounting_data($) {
    local ($_, %_);
    my ($file, @recs, @lines);
    $file = $_[0];
    
    # Obtain the record lines
    $_ = xfread $file;
    $_ = decode("Big5", $_, FB_CROAK);
    s/\r\n/\n/g;
    @lines = split /\n/, $_;
    
    # Check each line
    # First line is title.  We should omit it.
    for (my $i = 1, @recs = qw(); $i < @lines; $i++) {
        die "$THIS_FILE: Malformed line found:\n$lines[$i]\n"
            if $lines[$i] !~ /^(\d{8}),(\d{4}-\d{2}-\d{2}),(\d{4}),((?:"[^"]+")?),(\d+),(\d+),(\d+),(\d+),((?:\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})?)$/; # "
        %_ = (
            "no"        => $1,
            "date"      => $2,
            "subj"      => $3,
            "summary"   => $4,
            "cashin"    => $5,
            "cashout"   => $6,
            "bankin"    => $7,
            "bankout"   => $8,
            "lastmod"   => $9,
        );
        # The order
        $_{"date"} =~ /^(\d{4})-(\d{2})-(\d{2})$/;
        $_ = sprintf "%02d%02d%02d", $1 - 1911, $2, $3;
        $_{"no"} =~ /^$_(\d{2})$/;
        $_{"ord"} = $1 + 0;
        $_{"no"} += 0;
        # The subject
        $_{"subj"} = map_acct_subjs $_{"subj"};
        die "$THIS_FILE: Unidentifiable subject:\n$lines[$i]\n"
            if !defined $_{"subj"};
        # The summary
        $_{"summary"} =~ s/^"([^"]+)"$/$1/;     # "
        $_{"summary"} = undef if $_{"summary"} eq "";
        # The amount
        $_{$_} += 0 foreach qw(cashin cashout bankin bankout);
        # The last-modified date
        $_{"lastmod"} = undef if $_{"lastmod"} eq "";
        push @recs, {%_};
    }
    # Sort them
    @recs = sort { $$a{"no"} <=> $$b{"no"} } @recs;
    
    return @recs;
}

# acct_recs_to_trxs: Convert the accounting records to accounting transactions
sub acct_recs_to_trxs(@) {
    local ($_, %_);
    my (@recs, @trxs, @dates);
    @recs = @_;
    # Obtain all the dates
    %_ = map { $$_{"date"} => 1 } @recs;
    @dates = sort keys %_;
    @trxs = qw();
    foreach my $date (@dates) {
        my (@remains, @toproc);
        @remains = grep $$_{"date"} eq $date, @recs;
        # The 74811/74812 incomes
        push @trxs, r2t_fundin $date, @remains;
        # The 11131 bank/cash transfer
        push @trxs, r2t_transfer $date, @remains;
        # The 7111 interest
        push @trxs, r2t_interest $date, @remains;
        # The 6256 phone fee
        push @trxs, r2t_phone $date, @remains;
        # The 1283/2283 temporarily payment/receipts
        push @trxs, r2t_temp $date, @remains;
        # There should not be any more bank record
        @_ = grep $$_{"bankin"} > 0 || $$_{"bankout"} > 0, @remains;
        die "$THIS_FILE: " . ${$_[0]}{"no"} . ": missing bank record"
            if @_ > 0;
        # The 1283/2283 other incomes
        push @trxs, r2t_miscin $date, @remains;
        # There should not be any more income record
        @_ = grep $$_{"cashin"} > 0, @remains;
        die "$THIS_FILE: " . ${$_[0]}{"no"} . ": missing cash income record"
            if @_ > 0;
        # All the expenses
        push @trxs, r2t_expense $date, @remains;
        # There should not be any more record
        die "$THIS_FILE: " . ${$remains[0]}{"no"} . ": missing cash income record"
            if @remains > 0;
    }
    
    # Set the transaction order
    %_ = map { $$_{"date"} => 1 } @trxs;
    @dates = sort keys %_;
    foreach my $date (@dates) {
        @_ = grep $$_{"date"} eq $date, @trxs;
        @_ = sort { ${${$$a{"recs"}}[0]}{"ord"} <=> ${${$$b{"recs"}}[0]}{"ord"} } @_;
        for ($_ = 0; $_ < @_; $_++) {
            ${$_[$_]}{"ord"} = $_ + 1;
        }
    }
    # Sort the transaction
    @trxs = sort { $$a{"date"} cmp $$b{"date"} || $$a{"ord"} <=> $$b{"ord"} } @trxs;
    
    # Set the record order
    foreach my $trx (@trxs) {
        my ($ob, $ol);
        ($ob, $ol) = (1, 1);
        foreach my $rec (@{$$trx{"recs"}}) {
            if ($$rec{"type"} eq "credit") {
                $$rec{"ord"} = $ob++;
            } elsif ($$rec{"type"} eq "debit") {
                $$rec{"ord"} = $ol++;
            }
        }
    }
    
    return @trxs;
}

# r2t_fundin: Convert 74811/74812 income records to transactions
sub r2t_fundin($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, @trxs, @cash, @bank, @mandy, @imacat);
    my ($sum, $summary, $subj);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} =~ /^7481[12]$/, @$recs;
    return if @toproc == 0;
    @$recs = grep $$_{"subj"} !~ /^7481[12]$/, @$recs;
    
    # Only to a single deposit
    @cash = grep $$_{"cashin"} > 0, @toproc;
    @bank = grep $$_{"bankin"} > 0, @toproc;
    # Only cash income
    if (@bank == 0) {
        @_ = @cash;
        $sum = 0;
        foreach (@_) {
            $$_{"type"} = "credit";
            $$_{"credit"} = 1;
            $$_{"amount"} = $$_{"cashin"};
            $sum += $$_{"amount"};
        }
        push @_, {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "debit",
                "credit"    => 0,
                "ord"       => 1,
                "subj"      => 1111,
                "summary"   => undef,
                "amount"    => $sum,
                "lastmod"   => undef,
            };
        return {"date"  => $date, "recs" => [@_]};
    
    # Only bank income
    } elsif (@cash == 0) {
        @_ = @bank;
        $sum = 0;
        foreach (@_) {
            $$_{"type"} = "credit";
            $$_{"credit"} = 1;
            $$_{"amount"} = $$_{"bankin"};
            $sum += $$_{"amount"};
        }
        push @_, {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "debit",
                "credit"    => 0,
                "ord"       => 1,
                "subj"      => 11131,
                "summary"   => undef,
                "amount"    => $sum,
                "lastmod"   => undef,
            };
        return {"date"  => $date, "recs" => [@_]};
    }
    
    # Only from a single person
    @mandy = grep $$_{"subj"} == 74811, @toproc;
    @imacat = grep $$_{"subj"} == 74812, @toproc;
    # Only from mandy
    if (@imacat == 0) {
        @_ = @mandy;
        $sum = 0;
        $summary = ${$_[0]}{"summary"};
        foreach (@_) {
            $$_{"type"} = "debit";
            $$_{"credit"} = 0;
            if ($$_{"cashin"} > 0) {
                $$_{"subj"} = 1111;
                $$_{"amount"} = $$_{"cashin"};
            } elsif ($$_{"bankin"} > 0) {
                $$_{"subj"} = 11131;
                $$_{"amount"} = $$_{"bankin"};
            }
            $$_{"summary"} = undef;
            $sum += $$_{"amount"};
        }
        push @_, {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "credit",
                "credit"    => 1,
                "ord"       => 1,
                "subj"      => 74811,
                "summary"   => $summary,
                "amount"    => $sum,
                "lastmod"   => undef,
            };
        return {"date"  => $date, "recs" => [@_]};
    
    # Only from imacat
    } elsif (@mandy == 0) {
        @_ = @imacat;
        $sum = 0;
        $summary = ${$_[0]}{"summary"};
        foreach (@_) {
            $$_{"type"} = "debit";
            $$_{"credit"} = 0;
            if ($$_{"cashin"} > 0) {
                $$_{"subj"} = 1111;
                $$_{"amount"} = $$_{"cashin"};
            } elsif ($$_{"bankin"} > 0) {
                $$_{"subj"} = 11131;
                $$_{"amount"} = $$_{"bankin"};
            }
            $$_{"summary"} = undef;
            $sum += $$_{"amount"};
        }
        push @_, {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "credit",
                "credit"    => 1,
                "ord"       => 1,
                "subj"      => 74812,
                "summary"   => $summary,
                "amount"    => $sum,
                "lastmod"   => undef,
            };
        return {"date"  => $date, "recs" => [@_]};
    }
    
    # Others
    # In fact only on 2000-06-18 with 2 cross records
    @trxs = qw();
    foreach (@toproc) {
        $$_{"type"} = "credit";
        $$_{"credit"} = 1;
        if ($$_{"cashin"} > 0) {
            $subj = 1111;
            $$_{"amount"} = $$_{"cashin"};
        } elsif ($$_{"bankin"} > 0) {
            $subj = 11131;
            $$_{"amount"} = $$_{"bankin"};
        }
        @_ = ($_);
        push @_, {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "debit",
                "credit"    => 0,
                "ord"       => 1,
                "subj"      => $subj,
                "summary"   => undef,
                "amount"    => $$_{"amount"},
                "lastmod"   => $$_{"lastmod"},
            };
        push @trxs, {"date"  => $date, "recs" => [@_]};
    }
    return @trxs;
}

# r2t_transfer: Convert 74811/74812 transfer records to transactions
sub r2t_transfer($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, @trxs, $trans, $cash, $fee);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} == 11131 || ($$_{"subj"} == 6288 && $$_{"bankout"} > 0), @$recs;
    return if @toproc == 0;
    @$recs = grep(!($$_{"subj"} == 11131 || ($$_{"subj"} == 6288 && $$_{"bankout"} > 0)), @$recs);
    
    @_ = grep $$_{"subj"} == 6288, @toproc;
    # Fortunately, all transfers with fee happen on days with only one transfer
    if (@_ > 0) {
        die "$THIS_FILE: more than one transfer fee on $date" if @_ > 1;
        $fee = $_[0];
        $$fee{"type"} = "debit";
        $$fee{"credit"} = 0;
        $$fee{"amount"} = $$fee{"bankout"};
        @_ = grep $$_{"subj"} == 11131, @toproc;
        die "$THIS_FILE: more than one transfer with transfer fee on $date" if @_ > 1;
        die "$THIS_FILE: no transfer found with transfer fee on $date" if @_ < 1;
        $trans = $_[0];
        $$trans{"type"} = "credit";
        $$trans{"credit"} = 1;
        $$trans{"amount"} = $$trans{"bankout"} + $$fee{"bankout"};
        $cash = {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "debit",
                "credit"    => 0,
                "ord"       => 1,
                "subj"      => 1111,
                "summary"   => undef,
                "amount"    => $$trans{"bankout"},
                "lastmod"   => undef,
            };
        return {"date"  => $date, "recs" => [$trans, $cash, $fee]};
    }
    
    @trxs = qw();
    foreach $trans (@toproc) {
        if ($$trans{"bankout"} > 0) {
            $$trans{"type"} = "credit";
            $$trans{"credit"} = 1;
            $$trans{"amount"} = $$trans{"bankout"};
            $cash = {
                    "no"        => 99999999,
                    "date"      => $date,
                    "type"      => "debit",
                    "credit"    => 0,
                    "ord"       => 1,
                    "subj"      => 1111,
                    "summary"   => undef,
                    "amount"    => $$trans{"bankout"},
                    "lastmod"   => undef,
                };
        } elsif ($$trans{"bankin"} > 0) {
            $$trans{"type"} = "debit";
            $$trans{"credit"} = 0;
            $$trans{"amount"} = $$trans{"bankin"};
            $cash = {
                    "no"        => 99999999,
                    "date"      => $date,
                    "type"      => "credit",
                    "credit"    => 1,
                    "ord"       => 1,
                    "subj"      => 1111,
                    "summary"   => undef,
                    "amount"    => $$trans{"bankin"},
                    "lastmod"   => undef,
                };
        }
        push @trxs, {"date"  => $date, "recs" => [$trans, $cash]};
    }
    return @trxs;
}

# r2t_interest: Convert 7111 interest records to transactions
sub r2t_interest($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, @trxs, $intr, $bank);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} == 7111, @$recs;
    return if @toproc == 0;
    @$recs = grep $$_{"subj"} != 7111, @$recs;
    
    # It is impossible to have more than one record in a single day
    $intr = $toproc[0];
    $$intr{"type"} = "credit";
    $$intr{"credit"} = 1;
    $$intr{"amount"} = $$intr{"bankin"};
    $bank = {
            "no"        => 99999999,
            "date"      => $date,
            "type"      => "debit",
            "credit"    => 0,
            "ord"       => 1,
            "subj"      => 11131,
            "summary"   => undef,
            "amount"    => $$intr{"bankin"},
            "lastmod"   => undef,
        };
    return {"date"  => $date, "recs" => [$intr, $bank]};
}

# r2t_phone: Convert 6256 phone fee records to transactions
sub r2t_phone($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, @trxs, $sum, $credit);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} == 6256, @$recs;
    return if @toproc == 0;
    @$recs = grep $$_{"subj"} != 6256, @$recs;
    
    # 2 records on one day only on 2007-05-22, both paid with cash
    # We shall adjust it later.  Currently this prevents mistakes.
    $sum = 0;
    foreach (@toproc) {
        $$_{"type"} = "debit";
        $$_{"credit"} = 0;
        $$_{"amount"} = $$_{"cashout"} + $$_{"bankout"};
        $sum += $$_{"amount"};
    }
    $credit = {
            "no"        => 99999999,
            "date"      => $date,
            "type"      => "credit",
            "credit"    => 1,
            "ord"       => 1,
            "subj"      => 1111,
            "summary"   => undef,
            "amount"    => $sum,
            "lastmod"   => undef,
        };
    $$credit{"subj"} = 11131 if ${$toproc[0]}{"bankout"} > 0;
    return {"date"  => $date, "recs" => [@toproc, $credit]};
}

# r2t_temp: Convert 1283/2283 temporarily payment/receipts
sub r2t_temp($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, @trxs, $sup);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} =~ /^[12]283$/, @$recs;
    return if @toproc == 0;
    @$recs = grep $$_{"subj"} !~ /^[12]283$/, @$recs;
    
    @trxs = qw();
    foreach (@toproc) {
        if ($$_{"cashin"} > 0) {
            $$_{"type"} = "credit";
            $$_{"credit"} = 1;
            $$_{"amount"} = $$_{"cashin"};
            $sup = {
                    "no"        => 99999999,
                    "date"      => $date,
                    "type"      => "debit",
                    "credit"    => 0,
                    "ord"       => 1,
                    "subj"      => 1111,
                    "summary"   => undef,
                    "amount"    => $$_{"amount"},
                    "lastmod"   => undef,
                };
        } elsif ($$_{"bankin"} > 0) {
            $$_{"type"} = "credit";
            $$_{"credit"} = 1;
            $$_{"amount"} = $$_{"bankin"};
            $sup = {
                    "no"        => 99999999,
                    "date"      => $date,
                    "type"      => "debit",
                    "credit"    => 0,
                    "ord"       => 1,
                    "subj"      => 11131,
                    "summary"   => undef,
                    "amount"    => $$_{"amount"},
                    "lastmod"   => undef,
                };
        } elsif ($$_{"cashout"} > 0) {
            $$_{"type"} = "debit";
            $$_{"credit"} = 0;
            $$_{"amount"} = $$_{"cashout"};
            $sup = {
                    "no"        => 99999999,
                    "date"      => $date,
                    "type"      => "credit",
                    "credit"    => 1,
                    "ord"       => 1,
                    "subj"      => 1111,
                    "summary"   => undef,
                    "amount"    => $$_{"amount"},
                    "lastmod"   => undef,
                };
        } elsif ($$_{"bankout"} > 0) {
            $$_{"type"} = "debit";
            $$_{"credit"} = 0;
            $$_{"amount"} = $$_{"bankout"};
            $sup = {
                    "no"        => 99999999,
                    "date"      => $date,
                    "type"      => "credit",
                    "credit"    => 1,
                    "ord"       => 1,
                    "subj"      => 11131,
                    "summary"   => undef,
                    "amount"    => $$_{"amount"},
                    "lastmod"   => undef,
                };
        }
        push @trxs, {"date"  => $date, "recs" => [$_, $sup]};
    }
    return @trxs;
}

# r2t_miscin: Convert 7488 other incomes
sub r2t_miscin($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, @trxs, $cash);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} == 7488, @$recs;
    return if @toproc == 0;
    @$recs = grep $$_{"subj"} != 7488, @$recs;
    
    # Sanity check
    @_ = grep $$_{"cashout"} > 0 || $$_{"bankin"} > 0 || $$_{"bankout"} > 0, @toproc;
    die "$THIS_FILE: " . ${$_[0]}{"no"} . ": not cash income" if @_ > 0;
    @trxs = qw();
    foreach (@toproc) {
        $$_{"type"} = "credit";
        $$_{"credit"} = 1;
        $$_{"amount"} = $$_{"cashin"};
        $cash = {
                "no"        => 99999999,
                "date"      => $date,
                "type"      => "debit",
                "credit"    => 0,
                "ord"       => 1,
                "subj"      => 1111,
                "summary"   => undef,
                "amount"    => $$_{"amount"},
                "lastmod"   => undef,
            };
        push @trxs, {"date"  => $date, "recs" => [$_, $cash]};
    }
    return @trxs;
}

# r2t_expense: Convert expenses
sub r2t_expense($\@) {
    local ($_, %_);
    my ($date, $recs, @toproc, $sum, $cash);
    ($date, $recs) = @_;
    @toproc = grep $$_{"subj"} =~ /^(?:6\d{3}|1441)/, @$recs;
    return if @toproc == 0;
    @$recs = grep $$_{"subj"} !~ /^(?:6\d{3}|1441)/, @$recs;
    
    # Sanity check
    @_ = grep $$_{"cashin"} > 0 || $$_{"bankin"} > 0 || $$_{"bankout"} > 0, @toproc;
    die "$THIS_FILE: " . ${$_[0]}{"no"} . ": not expense" if @_ > 0;
    # We merge them into one
    $sum = 0;
    foreach (@toproc) {
        $$_{"type"} = "debit";
        $$_{"credit"} = 0;
        $$_{"amount"} = $$_{"cashout"};
        $sum += $$_{"amount"};
    }
    $cash = {
            "no"        => 99999999,
            "date"      => $date,
            "type"      => "credit",
            "credit"    => 1,
            "ord"       => 1,
            "subj"      => 1111,
            "summary"   => undef,
            "amount"    => $sum,
            "lastmod"   => undef,
        };
    return {"date"  => $date, "recs" => [@toproc, $cash]};
}

# trxs_to_sqls: Convert the accounting transactions to SQL statements
sub trxs_to_sqls($$@) {
    local ($_, %_);
    my ($dbh, $usersn, @trxs, @sqls, @colstrx, @colsrec, $trxsn, %subjs);
    my ($sql, $sth, $count, $row);
    ($dbh, $usersn, @trxs) = @_;
    
    @sqls = qw();
    push @sqls, "SET NAMES 'utf8';\n";
    push @sqls, "START TRANSACTION;\n";
    push @sqls, "LOCK TABLE accttrx, acctrecs, mtime IN ACCESS EXCLUSIVE MODE;\n";
    push @sqls, "DELETE FROM acctrecs;\n";
    push @sqls, "DELETE FROM accttrx;\n";
    push @sqls, "\n";
    
    # Obtain all the subjects
    %_ = qw();
    foreach my $trx (@trxs) {
        %_ = (%_, map { $$_{"subj"} => 1 } @{$$trx{"recs"}});
    }
    $sql = "SELECT sn, code FROM acctsubj"
        . " WHERE " . join(" OR ", map "code='$_'", sort keys %_) .  ";\n";
    $sth = $dbh->prepare($sql)          or die "$THIS_FILE: $sql: " . $dbh->errstr;
    $sth->execute                       or die "$THIS_FILE: $sql: " . $sth->errstr;
    $count = $sth->rows;
    for ($_ = 0, %subjs = qw(); $_ < $count; $_++) {
        $row = $sth->fetchrow_hashref;
        $subjs{$$row{"code"}} = $$row{"sn"};
    }
    
    @colstrx = table_cols $dbh, "accttrx";
    @colsrec = table_cols $dbh, "acctrecs";
    foreach my $trx (@trxs) {
        $$trx{"sn"} = newsn;
        $$trx{"created"} = $$trx{"date"} . " 00:00:00";
        $$trx{"updated"} = $$trx{"created"};
        $$trx{"updated"} = (reverse sort map $$_{"lastmod"}, @_)[0]
            if (@_ = grep defined $$_{"lastmod"}, @{$$trx{"recs"}}) > 0;
        @_ = qw();
        foreach (@colstrx) {
            if (/^sn$/) {
                push @_, [$_, $$trx{$_}];
            } elsif (/^(?:created|updated)$/) {
                push @_, [$_, "'" . $$trx{$_} . "'"];
            } elsif (/^(?:createdby|updatedby)$/) {
                push @_, [$_, $usersn];
            } elsif (/^ord$/) {
                push @_, [$_, $$trx{$_}];
            } elsif (/^date$/) {
                push @_, [$_, "'" . $$trx{$_} . "'"];
            } elsif (/^note$/) {
                push @_, [$_, "NULL"];
            }
        }
        push @sqls, "INSERT INTO accttrx"
            . " (" . join(", ", map $$_[0], @_) . ") VALUES"
            . " (" . join(", ", map $$_[1], @_) . ");\n";
        foreach my $rec (@{$$trx{"recs"}}) {
            $$rec{"sn"} = newsn;
            $$rec{"created"} = $$trx{"created"};
            $$rec{"updated"} = defined $$rec{"lastmod"}?
                $$rec{"lastmod"}: $$rec{"created"};
            @_ = qw();
            foreach (@colsrec) {
                if (/^sn$/) {
                    push @_, [$_, $$rec{$_}];
                } elsif (/^(?:created|updated)$/) {
                    push @_, [$_, "'" . $$rec{$_} . "'"];
                } elsif (/^(?:createdby|updatedby)$/) {
                    push @_, [$_, $usersn];
                } elsif (/^trx$/) {
                    push @_, [$_, $$trx{"sn"}];
                } elsif (/^credit$/) {
                    push @_, [$_, $$rec{$_}? "TRUE": "FALSE"];
                } elsif (/^(?:ord|amount)$/) {
                    push @_, [$_, $$rec{$_}];
                } elsif (/^subj$/) {
                    push @_, [$_, $subjs{$$rec{$_}}];
                } elsif (/^summary$/) {
                    push @_, [$_, $dbh->quote($$rec{$_})];
                }
            }
            foreach (@_) {
               $$_[1] = "(undef)" if !defined $$_[1];
            }
            push @sqls, "INSERT INTO acctrecs"
                . " (" . join(", ", map $$_[0], @_) . ") VALUES"
                . " (" . join(", ", map $$_[1], @_) . ");\n";
        }
        push @sqls, "\n";
    }
    
    push @sqls, "UPDATE mtime SET mtime=now() WHERE tabname='accttrx';\n";
    push @sqls, "UPDATE mtime SET mtime=now() WHERE tabname='acctrecs';\n";
    push @sqls, "COMMIT;\n";
    push @sqls, "ANALYZE accttrx;\n";
    push @sqls, "ANALYZE acctrecs;\n";
    
    return @sqls;
}

# map_acct_subjs: Map the accounting subjects
#   Custom subjects:
#    11131: Ȧs-ls
#    74811: @Pͬ-P
#    74812: @Pͬ-hC
sub map_acct_subjs($) {
    local ($_, %_);
    $_ = $_[0];
    # {
    if ($_ eq 1100) {
        return 1111;
    # Ȧs-ls
    } elsif ($_ eq 1103) {
        return 11131;
    # ȥI
    } elsif ($_ eq 1281) {
        return 1283;
    # q]
    } elsif ($_ eq 1541) {
        return 1441;
    # Ȧ
    } elsif ($_ eq 2281) {
        return 2283;
    # @Pͬ-P
    } elsif ($_ eq 4111) {
        return 74811;
    # @Pͬ-hC
    } elsif ($_ eq 4112) {
        return 74812;
    # X
    } elsif ($_ eq 6111) {
        return 6252;
    # lqO
    } elsif ($_ eq 6115) {
        return 6256;
    # µO
    } elsif ($_ eq 6116) {
        return 6257;
    # qO
    } elsif ($_ eq 6118) {
        return 6261;
    # ڶO
    } elsif ($_ eq 6120) {
        return 6264;
    # 뭹O
    } elsif ($_ eq 6127) {
        return 6272;
    # qO
    } elsif ($_ eq 6134) {
        return 6254;
    # TֶO
    } elsif ($_ eq 6141) {
        return 6273;
    # 
    } elsif ($_ eq 6188) {
        return 6288;
    # QJ
    } elsif ($_ eq 7110) {
        return 7111;
    # 䥦J
    } elsif ($_ eq 7480) {
        return 7488;
    # Non-sense
    } else {
        return undef;
    }
}

__END__
