1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 #  Contributors: Benjamin Lee <benjaminlee@consultant.com>
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # backend code for reports
 
  33 #======================================================================
 
  39 use List::Util qw(sum);
 
  44 # new implementation of balance sheet
 
  47 # stuff missing from the original implementation:
 
  50 # - proper testing for heading charts
 
  51 # - transmission from $form to TMPL realm is not as clear as i'd like
 
  53   $main::lxdebug->enter_sub();
 
  55   my $myconfig = \%main::myconfig;
 
  56   my $form     = $main::form;
 
  57   my $dbh      = $form->get_standard_dbh($myconfig);
 
  60   my @categories  = qw(A C L Q);
 
  62   # if there are any dates construct a where
 
  63   if ($form->{asofdate}) {
 
  64     $form->{period} = $form->{this_period} = conv_dateq($form->{asofdate});
 
  67   get_accounts($dbh, $last_period, "", $form->{asofdate}, $form, \@categories);
 
  69   # if there are any compare dates
 
  70   if ($form->{compareasofdate}) {
 
  72     get_accounts($dbh, $last_period, "", $form->{compareasofdate}, $form, \@categories);
 
  73     $form->{last_period} = conv_dateq($form->{compareasofdate});
 
  76   # now we got $form->{A}{accno}{ }    assets
 
  77   # and $form->{L}{accno}{ }           liabilities
 
  78   # and $form->{Q}{accno}{ }           equity
 
  79   # build asset accounts
 
  81   my %account = ('A' => { 'ml'     => -1 },
 
  83                  'Q' => { 'ml'     =>  1 });
 
  87   foreach my $category (grep { !/C/ } @categories) {
 
  89     $TMPL_DATA->{$category} = [];
 
  90     my $ml  = $account{$category}{ml};
 
  92     foreach my $key (sort keys %{ $form->{$category} }) {
 
  94       my $row = { %{ $form->{$category}{$key} } };
 
  96       # if charttype "heading" - calculate this entry, start a new batch of charts belonging to this heading and skip the rest bo the loop
 
  97       # header charts are not real charts. start a sub aggregation with them, but don't calculate anything with them
 
  98       if ($row->{charttype} eq "H") {
 
  99         if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 100           $row->{subdescription} = $account{$category}{subdescription};
 
 101           $row->{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 102           $row->{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 105         $row->{subheader} = 1;
 
 106         $account{$category}{subthis}        = $row->{this};
 
 107         $account{$category}{sublast}        = $row->{last};
 
 108         $account{$category}{subdescription} = $row->{description};
 
 109         $account{$category}{subtotal} = 1;
 
 114         next unless $form->{l_heading};
 
 117       for my $period (qw(this last)) {
 
 118         next if ($period eq 'last' && !$last_period);
 
 120         $row->{$period}                    *= $ml;
 
 121         $form->{total}{$category}{$period} += $row->{$period};      #      if ($row->{charttype} eq 'A') {   # why??
 
 124       push @{ $TMPL_DATA->{$category} }, $row;
 
 127     # resolve heading/subtotal
 
 128     if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 129       $TMPL_DATA->{$category}[-1]{subdescription} = $account{$category}{subdescription};
 
 130       $TMPL_DATA->{$category}[-1]{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 131       $TMPL_DATA->{$category}[-1]{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 134     $TMPL_DATA->{total}{$category}{this} = sum map { $_->{this} } @{ $TMPL_DATA->{$category} };
 
 135     $TMPL_DATA->{total}{$category}{last} = sum map { $_->{last} } @{ $TMPL_DATA->{$category} };
 
 138   for my $period (qw(this last)) {
 
 139     next if ($period eq 'last' && !$last_period);
 
 141     $form->{E}{$period}             = $form->{total}{A}{$period} - $form->{total}{L}{$period} - $form->{total}{Q}{$period};
 
 142     $form->{total}{Q}{$period}     += $form->{E}{$period};
 
 143     $TMPL_DATA->{total}{Q}{$period} = $form->{total}{Q}{$period};
 
 144     $TMPL_DATA->{total}{$period}    = $form->{total}{L}{$period} + $form->{total}{Q}{$period};
 
 147   push @{ $TMPL_DATA->{Q} }, $form->{E};
 
 149   $main::lxdebug->leave_sub();
 
 155   $main::lxdebug->enter_sub();
 
 157   my ($dbh, $last_period, $fromdate, $todate, $form, $categories) = @_;
 
 159   my ($null, $department_id) = split /--/, $form->{department};
 
 170   my $dec = $form->{decimalplaces};
 
 172   my $category = qq| AND (| . join(" OR ", map({ "(c.category = " . $dbh->quote($_) . ")" } @{$categories})) . qq|) |;
 
 176     qq|SELECT c.accno, c.description, c.category
 
 178        WHERE (c.charttype = 'H')
 
 182   $sth = prepare_execute_query($form, $dbh, $query);
 
 184   my @headingaccounts = ();
 
 185   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 186     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
 
 187       "$ref->{description}";
 
 188     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
 
 189     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
 
 191     push @headingaccounts, $ref->{accno};
 
 197     $fromdate = conv_dateq($fromdate);
 
 198     if ($form->{method} eq 'cash') {
 
 199       $subwhere .= " AND (transdate >= $fromdate)";
 
 200       $glwhere = " AND (ac.transdate >= $fromdate)";
 
 202       $where .= " AND (ac.transdate >= $fromdate)";
 
 207     $todate = conv_dateq($todate);
 
 208     $where    .= " AND (ac.transdate <= $todate)";
 
 209     $subwhere .= " AND (transdate <= $todate)";
 
 212   if ($department_id) {
 
 213     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
 
 214     $dpt_where = qq| AND (t.id = | . conv_i($department_id, 'NULL') . qq|)|;
 
 217   if ($form->{project_id}) {
 
 218     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 221   if ($form->{method} eq 'cash') {
 
 223       qq|SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 225          JOIN chart c ON (c.id = ac.chart_id)
 
 226          JOIN ar a ON (a.id = ac.trans_id)
 
 235                JOIN chart ON (chart_id = id)
 
 236                WHERE (link LIKE '%AR_paid%')
 
 240          GROUP BY c.accno, c.description, c.category
 
 244          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 246          JOIN chart c ON (c.id = ac.chart_id)
 
 247          JOIN ap a ON (a.id = ac.trans_id)
 
 256                JOIN chart ON (chart_id = id)
 
 257                WHERE (link LIKE '%AP_paid%')
 
 261          GROUP BY c.accno, c.description, c.category
 
 265          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 267          JOIN chart c ON (c.id = ac.chart_id)
 
 268          JOIN gl a ON (a.id = ac.trans_id)
 
 274              AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
 
 276          GROUP BY c.accno, c.description, c.category |;
 
 278     if ($form->{project_id}) {
 
 283          SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 285          JOIN ar a ON (a.id = ac.trans_id)
 
 286          JOIN parts p ON (ac.parts_id = p.id)
 
 287          JOIN chart c on (p.income_accno_id = c.id)
 
 289          -- use transdate from subwhere
 
 290          WHERE (c.category = 'I')
 
 297                JOIN chart ON (chart_id = id)
 
 298                WHERE (link LIKE '%AR_paid%')
 
 302          GROUP BY c.accno, c.description, c.category
 
 306          SELECT c.accno AS accno, SUM(ac.sellprice) AS amount, c.description AS description, c.category
 
 308          JOIN ap a ON (a.id = ac.trans_id)
 
 309          JOIN parts p ON (ac.parts_id = p.id)
 
 310          JOIN chart c on (p.expense_accno_id = c.id)
 
 312          WHERE (c.category = 'E')
 
 319                JOIN chart ON (chart_id = id)
 
 320                WHERE link LIKE '%AP_paid%'
 
 324          GROUP BY c.accno, c.description, c.category |;
 
 327   } else {                      # if ($form->{method} eq 'cash')
 
 328     if ($department_id) {
 
 329       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
 330       $dpt_where = qq| AND t.department_id = $department_id |;
 
 334       SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 336       JOIN chart c ON (c.id = ac.chart_id)
 
 342       GROUP BY c.accno, c.description, c.category |;
 
 344     if ($form->{project_id}) {
 
 348       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 350       JOIN ar a ON (a.id = ac.trans_id)
 
 351       JOIN parts p ON (ac.parts_id = p.id)
 
 352       JOIN chart c on (p.income_accno_id = c.id)
 
 354       -- use transdate from subwhere
 
 355       WHERE (c.category = 'I')
 
 359       GROUP BY c.accno, c.description, c.category
 
 363       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount, c.description AS description, c.category
 
 365       JOIN ap a ON (a.id = ac.trans_id)
 
 366       JOIN parts p ON (ac.parts_id = p.id)
 
 367       JOIN chart c on (p.expense_accno_id = c.id)
 
 369       WHERE (c.category = 'E')
 
 373       GROUP BY c.accno, c.description, c.category |;
 
 381   $sth = prepare_execute_query($form, $dbh, $query);
 
 383   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 385     if ($ref->{category} eq 'C') {
 
 386       $ref->{category} = 'A';
 
 389     # get last heading account
 
 390     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
 394         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
 
 396         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
 
 400     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
 
 401     $form->{ $ref->{category} }{ $ref->{accno} }{description} = $ref->{description};
 
 402     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
 
 405       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
 
 407       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
 
 412   # remove accounts with zero balance
 
 413   foreach $category (@{$categories}) {
 
 414     foreach $accno (keys %{ $form->{$category} }) {
 
 415       $form->{$category}{$accno}{last} = $form->round_amount($form->{$category}{$accno}{last}, $dec);
 
 416       $form->{$category}{$accno}{this} = $form->round_amount($form->{$category}{$accno}{this}, $dec);
 
 418       delete $form->{$category}{$accno}
 
 419         if (   $form->{$category}{$accno}{this} == 0
 
 420             && $form->{$category}{$accno}{last} == 0);
 
 424   $main::lxdebug->leave_sub();
 
 428   $main::lxdebug->enter_sub();
 
 430   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
 
 432   my ($null, $department_id) = split /--/, $form->{department};
 
 445     $fromdate = conv_dateq($fromdate);
 
 446     if ($form->{method} eq 'cash') {
 
 447       $subwhere .= " AND (transdate    >= $fromdate)";
 
 448       $glwhere   = " AND (ac.transdate >= $fromdate)";
 
 449       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 451       $where    .= " AND (ac.transdate >= $fromdate)";
 
 456     $todate = conv_dateq($todate);
 
 457     $subwhere   .= " AND (transdate    <= $todate)";
 
 458     $where      .= " AND (ac.transdate <= $todate)";
 
 459     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 462   if ($department_id) {
 
 463     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
 
 464     $dpt_where = qq| AND (t.id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 467   if ($form->{project_id}) {
 
 468     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
 
 471   if ($form->{method} eq 'cash') {
 
 474        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 476          JOIN chart c ON (c.id = ac.chart_id)
 
 477          JOIN ar a ON (a.id = ac.trans_id)
 
 479          WHERE $where $dpt_where
 
 480            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AR_paid%') $subwhere)
 
 486          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 488          JOIN chart c ON (c.id = ac.chart_id)
 
 489          JOIN ap a ON (a.id = ac.trans_id)
 
 491          WHERE $where $dpt_where
 
 492            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AP_paid%') $subwhere)
 
 498          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 500          JOIN chart c ON (c.id = ac.chart_id)
 
 501          JOIN gl a ON (a.id = ac.trans_id)
 
 503          WHERE $where $dpt_where $glwhere
 
 504            AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
 
 509     if ($form->{project_id}) {
 
 513          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 515          JOIN ar a ON (a.id = ac.trans_id)
 
 516          JOIN parts p ON (ac.parts_id = p.id)
 
 517          JOIN chart c on (p.income_accno_id = c.id)
 
 519          WHERE (c.category = 'I') $prwhere $dpt_where
 
 520            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AR_paid%') $subwhere)
 
 526          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 528          JOIN ap a ON (a.id = ac.trans_id)
 
 529          JOIN parts p ON (ac.parts_id = p.id)
 
 530          JOIN chart c on (p.expense_accno_id = c.id)
 
 532          WHERE (c.category = 'E') $prwhere $dpt_where
 
 533            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AP_paid%') $subwhere)
 
 539   } else {                      # if ($form->{method} eq 'cash')
 
 540     if ($department_id) {
 
 541       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
 542       $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 546         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 548         JOIN chart c ON (c.id = ac.chart_id)
 
 553         GROUP BY c.$category |;
 
 555     if ($form->{project_id}) {
 
 559         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 561         JOIN ar a ON (a.id = ac.trans_id)
 
 562         JOIN parts p ON (ac.parts_id = p.id)
 
 563         JOIN chart c on (p.income_accno_id = c.id)
 
 565         WHERE (c.category = 'I')
 
 573         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 575         JOIN ap a ON (a.id = ac.trans_id)
 
 576         JOIN parts p ON (ac.parts_id = p.id)
 
 577         JOIN chart c on (p.expense_accno_id = c.id)
 
 579         WHERE (c.category = 'E')
 
 583         GROUP BY c.$category |;
 
 591   my $sth = prepare_execute_query($form, $dbh, $query);
 
 593   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 594     if ($category eq "pos_bwa") {
 
 596         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 598         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 601       $form->{ $ref->{$category} } += $ref->{amount};
 
 606   $main::lxdebug->leave_sub();
 
 610   $main::lxdebug->enter_sub();
 
 612   my ($self, $myconfig, $form, %options) = @_;
 
 614   my $dbh = $form->dbconnect($myconfig);
 
 616   my ($query, $sth, $ref);
 
 619   my ($null, $department_id) = split /--/, $form->{department};
 
 620   my @headingaccounts = ();
 
 626   my $invwhere = $where;
 
 628   if ($department_id) {
 
 629     $dpt_join = qq| JOIN dpt_trans t ON (ac.trans_id = t.trans_id) |;
 
 630     $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 633   # project_id only applies to getting transactions
 
 634   # it has nothing to do with a trial balance
 
 635   # but we use the same function to collect information
 
 637   if ($form->{project_id}) {
 
 638     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 641   my $acc_cash_where = "";
 
 642 #  my $ar_cash_where = "";
 
 643 #  my $ap_cash_where = "";
 
 646   if ($form->{method} eq "cash") {
 
 648       qq| AND (ac.trans_id IN (
 
 651             WHERE datepaid >= '$form->{fromdate}'
 
 652               AND datepaid <= '$form->{todate}'
 
 658             WHERE datepaid >= '$form->{fromdate}'
 
 659               AND datepaid <= '$form->{todate}'
 
 665             WHERE transdate >= '$form->{fromdate}'
 
 666               AND transdate <= '$form->{todate}'
 
 668 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 671   if ($options{beginning_balances}) {
 
 672     foreach my $prefix (qw(from to)) {
 
 673       next if ($form->{"${prefix}date"});
 
 675       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 676       $query      = qq|SELECT ${min_max}(transdate)
 
 682       ($form->{"${prefix}date"}) = selectfirst_array_query($form, $dbh, $query);
 
 685     # get beginning balances
 
 687       qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
 
 689           LEFT JOIN chart c ON (ac.chart_id = c.id)
 
 691           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 694           GROUP BY c.accno, c.category, c.description |;
 
 696     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 698     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 700       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 701         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 702         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 703         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 705         if ($ref->{amount} > 0) {
 
 706           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 708           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 710         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 719     qq|SELECT c.accno, c.description, c.category
 
 721        WHERE c.charttype = 'H'
 
 724   $sth = prepare_execute_query($form, $dbh, $query);
 
 726   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 727     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 728     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 729     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 731     push @headingaccounts, $ref->{accno};
 
 737   my $saldowhere    = " 1 = 1 ";
 
 738   my $sumwhere      = " 1 = 1 ";
 
 740   my $sumsubwhere   = '';
 
 741   my $saldosubwhere = '';
 
 742   my $glsaldowhere  = '';
 
 748   if ($form->{fromdate} || $form->{todate}) {
 
 749     if ($form->{fromdate}) {
 
 750       $fromdate = conv_dateq($form->{fromdate});
 
 751       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 752       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 753       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 754       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 755       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 756       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 757       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 758       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 760     if ($form->{todate}) {
 
 761       $todate = conv_dateq($form->{todate});
 
 762       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 763       $invwhere      .= " AND (a.transdate <= $todate)";
 
 764       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 765       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 766       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 767       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 768       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 769       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 773   if ($form->{method} eq "cash") {
 
 775       qq| AND(ac.trans_id IN (SELECT id FROM ar WHERE datepaid>= $fromdate AND datepaid<= $todate UNION SELECT id FROM ap WHERE datepaid>= $fromdate AND datepaid<= $todate UNION SELECT id FROM gl WHERE transdate>= $fromdate AND transdate<= $todate)) AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL) |;
 
 776     $saldowhere .= qq| AND(ac.trans_id IN (SELECT id FROM ar WHERE datepaid>= $fromdate AND datepaid<= $todate UNION SELECT id FROM ap WHERE datepaid>= $fromdate AND datepaid<= $todate UNION SELECT id FROM gl WHERE transdate>= $fromdate AND transdate<= $todate))  AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL) |;
 
 778     $sumwhere .= qq| AND(ac.trans_id IN (SELECT id FROM ar WHERE datepaid>= $fromdate AND datepaid<= $todate UNION SELECT id FROM ap WHERE datepaid>= $fromdate AND datepaid<= $todate UNION SELECT id FROM gl WHERE transdate>= $fromdate AND transdate<= $todate)) AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL) |;
 
 780     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 781     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 782     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 786        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 788        JOIN chart c ON (c.id = ac.chart_id)
 
 793        GROUP BY c.accno, c.description, c.category |;
 
 795   if ($form->{project_id}) {
 
 797       -- add project transactions from invoice
 
 801       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 803       JOIN ar a ON (ac.trans_id = a.id)
 
 804       JOIN parts p ON (ac.parts_id = p.id)
 
 805       JOIN chart c ON (p.income_accno_id = c.id)
 
 810       GROUP BY c.accno, c.description, c.category
 
 814       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 816       JOIN ap a ON (ac.trans_id = a.id)
 
 817       JOIN parts p ON (ac.parts_id = p.id)
 
 818       JOIN chart c ON (p.expense_accno_id = c.id)
 
 823       GROUP BY c.accno, c.description, c.category
 
 827   $query .= qq| ORDER BY accno|;
 
 829   $sth = prepare_execute_query($form, $dbh, $query);
 
 831   # calculate the debit and credit in the period
 
 832   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 833     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 834     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 835     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 836     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 840   # prepare query for each account
 
 841   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 845          (SELECT SUM(ac.amount) * -1
 
 847           JOIN chart c ON (c.id = ac.chart_id)
 
 853           AND (c.accno = ?)) AS debit,
 
 855          (SELECT SUM(ac.amount)
 
 857           JOIN chart c ON (c.id = ac.chart_id)
 
 863           AND c.accno = ?) AS credit,
 
 864         (SELECT SUM(ac.amount)
 
 866          JOIN chart c ON (ac.chart_id = c.id)
 
 871          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 873         (SELECT SUM(ac.amount)
 
 875          JOIN chart c ON (ac.chart_id = c.id)
 
 881          AND c.accno = ?) AS sum_credit,
 
 883         (SELECT SUM(ac.amount)
 
 885          JOIN chart c ON (ac.chart_id = c.id)
 
 891          AND c.accno = ?) AS sum_debit,
 
 893         (SELECT max(ac.transdate) FROM acc_trans ac
 
 894         JOIN chart c ON (ac.chart_id = c.id)
 
 899         AND c.accno = ?) AS last_transaction
 
 904   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 906   if ($form->{project_id}) {
 
 907     # prepare query for each account
 
 910           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
 912            JOIN parts p ON (ac.parts_id = p.id)
 
 913            JOIN ap a ON (ac.trans_id = a.id)
 
 914            JOIN chart c ON (p.expense_accno_id = c.id)
 
 919            AND c.accno = ?) AS debit,
 
 921           (SELECT SUM(ac.sellprice * ac.qty)
 
 923            JOIN parts p ON (ac.parts_id = p.id)
 
 924            JOIN ar a ON (ac.trans_id = a.id)
 
 925            JOIN chart c ON (p.income_accno_id = c.id)
 
 930            AND c.accno = ?) AS credit,
 
 932         (SELECT SUM(ac.amount)
 
 934          JOIN chart c ON (ac.chart_id = c.id)
 
 939          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 941         (SELECT SUM(ac.amount)
 
 943          JOIN chart c ON (ac.chart_id = c.id)
 
 949          AND c.accno = ?) AS sum_credit,
 
 951         (SELECT SUM(ac.amount)
 
 953          JOIN chart c ON (ac.chart_id = c.id)
 
 959          AND c.accno = ?) AS sum_debit,
 
 962         (SELECT max(ac.transdate) FROM acc_trans ac
 
 963         JOIN chart c ON (ac.chart_id = c.id)
 
 968         AND c.accno = ?) AS last_transaction
 
 971     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
 975   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
 977   foreach my $accno (sort keys %trb) {
 
 980     $ref->{accno} = $accno;
 
 981     map { $ref->{$_} = $trb{$accno}{$_} }
 
 982       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
 984     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
 986     if ($trb{$accno}{charttype} eq 'A') {
 
 989       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
 991       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
 992       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
 993       $last_transaction = "";
 
 994       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
 995         $ref->{debit}  += $debit;
 
 996         $ref->{credit} += $credit;
 
 998           $ref->{haben_saldo} += $saldo;
 
1000           $ref->{soll_saldo} += $saldo * -1;
 
1002         $ref->{last_transaction} = $last_transaction;
 
1003         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1004         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1008       if ($form->{project_id}) {
 
1011         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1013         ($debit, $credit) = (0, 0);
 
1014         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1015           $ref->{debit}  += $debit;
 
1016           $ref->{credit} += $credit;
 
1018             $ref->{haben_saldo} += $saldo;
 
1020             $ref->{soll_saldo} += $saldo * -1;
 
1022           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1023           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1025         $project_drcr->finish;
 
1028       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1029       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1031       if ($ref->{haben_saldo} != 0) {
 
1032         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1033         if ($ref->{haben_saldo} < 0) {
 
1034           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1035           $ref->{haben_saldo} = 0;
 
1038         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1039         if ($ref->{soll_saldo} < 0) {
 
1040           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1041           $ref->{soll_saldo} = 0;
 
1044       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1045       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1046       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1047       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1052     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1053     $accno = pop @accno;
 
1055       $trb{$accno}{debit}  += $ref->{debit};
 
1056       $trb{$accno}{credit} += $ref->{credit};
 
1057       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1058       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1059       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1060       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1063     push @{ $form->{TB} }, $ref;
 
1069   # debits and credits for headings
 
1070   foreach my $accno (@headingaccounts) {
 
1071     foreach $ref (@{ $form->{TB} }) {
 
1072       if ($accno eq $ref->{accno}) {
 
1073         $ref->{debit}           = $trb{$accno}{debit};
 
1074         $ref->{credit}          = $trb{$accno}{credit};
 
1075         $ref->{soll_saldo}      = $trb{$accno}{soll_saldo};
 
1076         $ref->{haben_saldo}     = $trb{$accno}{haben_saldo};
 
1077         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
 
1078         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};
 
1083   $main::lxdebug->leave_sub();
 
1087   $main::lxdebug->enter_sub();
 
1088   my ($self, $dbh, $form) = @_;
 
1089   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
 
1090   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
 
1091   my $sth =  $dbh->prepare($query);
 
1092   while(my $ref = $sth->fetchrow_hashref()) {
 
1093     $ref->{invnumer} =~ s/Storno zu //g;
 
1094     $form->{storno}{$ref->{invnumber}} = 1;
 
1096   $main::lxdebug->leave_sub();
 
1100   $main::lxdebug->enter_sub();
 
1102   my ($self, $myconfig, $form) = @_;
 
1104   # connect to database
 
1105   my $dbh     = $form->dbconnect($myconfig);
 
1107   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
 
1109   if ($form->{ct} eq "customer") {
 
1122   $ct_id = "${ct}_id";
 
1124   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
 
1125   my $todate = conv_dateq($form->{todate});
 
1126   my $fromdate = conv_dateq($form->{fromdate});
 
1128   my $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
 
1130   my $where = " 1 = 1 ";
 
1133   if ($form->{$ct_id}) {
 
1134     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
 
1135   } elsif ($form->{ $form->{ct} }) {
 
1136     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
 
1140   if ($form->{department}) {
 
1141     my ($null, $department_id) = split /--/, $form->{department};
 
1142     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
 
1143     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1147     -- between 0-30 days
 
1149     SELECT ${ct}.id AS ctid, ${ct}.name,
 
1150       street, zipcode, city, country, contact, email,
 
1151       phone as customerphone, fax as customerfax, ${ct}number,
 
1152       "invnumber", "transdate",
 
1153       (amount - COALESCE((SELECT sum(amount)*$ml FROM acc_trans LEFT JOIN chart ON (acc_trans.chart_id=chart.id) WHERE link ilike '%paid%' AND acc_trans.trans_id=${arap}.id AND acc_trans.transdate <= (date $todate)),0)) as "open", "amount",
 
1154       "duedate", invoice, ${arap}.id,
 
1157        WHERE (${arap}.curr = exchangerate.curr)
 
1158          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
 
1160     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
 
1161       AND (${arap}.storno IS FALSE)
 
1162       AND (${arap}.${ct}_id = ${ct}.id)
 
1164       AND (transdate <= (date $todate) $fromwhere )
 
1166     ORDER BY ctid, transdate, invnumber |;
 
1168   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1170   # select outstanding vendors or customers, depends on $ct
 
1172     qq|SELECT DISTINCT ct.id, ct.name
 
1173        FROM $ct ct, $arap a
 
1176          AND (a.${ct_id} = ct.id)
 
1177          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
 
1178          AND (a.transdate <= $todate $fromwhere)
 
1181   my $sth = prepare_execute_query($form, $dbh, $query);
 
1184   # for each company that has some stuff outstanding
 
1185   while (my ($id) = $sth->fetchrow_array) {
 
1186     do_statement($form, $sth_details, $q_details, $id);
 
1188     while (my $ref = $sth_details->fetchrow_hashref("NAME_lc")) {
 
1189       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
 
1190       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
 
1191       push @{ $form->{AG} }, $ref;
 
1194     $sth_details->finish;
 
1203   $main::lxdebug->leave_sub();
 
1207   $main::lxdebug->enter_sub();
 
1209   my ($self, $myconfig, $form) = @_;
 
1211   # connect to database
 
1212   my $dbh = $form->dbconnect($myconfig);
 
1214   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1217     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1220   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1221     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1224   $main::lxdebug->leave_sub();
 
1227 sub get_taxaccounts {
 
1228   $main::lxdebug->enter_sub();
 
1230   my ($self, $myconfig, $form) = @_;
 
1232   # connect to database
 
1233   my $dbh = $form->dbconnect($myconfig);
 
1237     qq|SELECT c.accno, c.description, t.rate
 
1239        WHERE (c.link LIKE '%CT_tax%') AND (c.id = t.chart_id)
 
1241   $form->{taxaccounts} = selectall_hashref_quert($form, $dbh, $query);
 
1245   $main::lxdebug->leave_sub();
 
1249   $main::lxdebug->enter_sub();
 
1251   my ($self, $myconfig, $form) = @_;
 
1253   # connect to database
 
1254   my $dbh = $form->dbconnect($myconfig);
 
1256   my ($null, $department_id) = split /--/, $form->{department};
 
1259   my $where = "1 = 1";
 
1261   if ($department_id) {
 
1262     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1267   if ($form->{accno}) {
 
1268     $accno = $form->{accno};
 
1269     $rate  = $form->{"$form->{accno}_rate"};
 
1270     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1276   if ($form->{db} eq 'ar') {
 
1277     $table = "customer";
 
1284   my $arap = lc($ARAP);
 
1286   my $transdate = "a.transdate";
 
1288   if ($form->{method} eq 'cash') {
 
1289     $transdate = "a.datepaid";
 
1291     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1298           JOIN chart ON (chart_id = id)
 
1299           WHERE (link LIKE '%${ARAP}_paid%')
 
1300           AND (transdate <= $todate)
 
1305   # if there are any dates construct a where
 
1306   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1307   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1309   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1311   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1312   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1315   if ($form->{report} !~ /nontaxable/) {
 
1317       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1318           ac.amount * $ml AS tax
 
1320          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1321          JOIN chart ch ON (ch.id = ac.chart_id)
 
1322          JOIN $table n ON (n.id = a.${table}_id)
 
1326            AND (a.invoice = '0')
 
1330          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1331            i.sellprice * i.qty * $rate * $ml AS tax
 
1333          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1334          JOIN chart ch ON (ch.id = ac.chart_id)
 
1335          JOIN $table n ON (n.id = a.${table}_id)
 
1336          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1337          JOIN invoice i ON (i.trans_id = a.id)
 
1338          JOIN partstax p ON (p.parts_id = i.parts_id)
 
1342            AND (a.invoice = '1')
 
1343          ORDER BY $sortorder|;
 
1345     # only gather up non-taxable transactions
 
1347       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount
 
1349          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1350          JOIN $table n ON (n.id = a.${table}_id)
 
1353            AND (a.invoice = '0')
 
1354            AND (a.netamount = a.amount)
 
1358          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount
 
1360          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1361          JOIN $table n ON (n.id = a.${table}_id)
 
1362          JOIN invoice i ON (i.trans_id = a.id)
 
1365            AND (a.invoice = '1')
 
1367              a.${table}_id NOT IN (SELECT ${table}_id FROM ${table}tax t (${table}_id))
 
1369              i.parts_id NOT IN (SELECT parts_id FROM partstax p (parts_id))
 
1371          GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
 
1372          ORDER by $sortorder|;
 
1375   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1379   $main::lxdebug->leave_sub();
 
1382 sub paymentaccounts {
 
1383   $main::lxdebug->enter_sub();
 
1385   my ($self, $myconfig, $form) = @_;
 
1387   # connect to database, turn AutoCommit off
 
1388   my $dbh = $form->dbconnect_noauto($myconfig);
 
1390   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1392   # get A(R|P)_paid accounts
 
1394     qq|SELECT accno, description
 
1396        WHERE link LIKE '%${ARAP}_paid%'|;
 
1397   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1401   $main::lxdebug->leave_sub();
 
1405   $main::lxdebug->enter_sub();
 
1407   my ($self, $myconfig, $form) = @_;
 
1409   # connect to database, turn AutoCommit off
 
1410   my $dbh = $form->dbconnect_noauto($myconfig);
 
1415   if ($form->{db} eq 'ar') {
 
1416     $table = 'customer';
 
1428   if ($form->{department_id}) {
 
1429     $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
1430     $where = qq| AND (t.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1433   if ($form->{fromdate}) {
 
1434     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1436   if ($form->{todate}) {
 
1437     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1439   if (!$form->{fx_transaction}) {
 
1440     $where .= " AND ac.fx_transaction = '0'";
 
1445   if ($form->{reference}) {
 
1446     $reference = $dbh->quote('%' . $form->{reference} . '%');
 
1447     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1448     $reference = " AND (g.reference LIKE $reference)";
 
1450   if ($form->{source}) {
 
1451     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
 
1453   if ($form->{memo}) {
 
1454     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
 
1457   my %sort_columns =  (
 
1458     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1459     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1460     'name'         => [ qw(lower_name transdate)                 ],
 
1461     'source'       => [ qw(lower_source)                         ],
 
1462     'memo'         => [ qw(lower_memo)                           ],
 
1464   my %lowered_columns =  (
 
1465     'invnumber'       => { 'gl' => 'g.reference',   'arap' => 'a.invnumber', },
 
1466     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1467     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1468     'name'            => { 'gl' => 'g.description', 'arap' => 'c.name',      },
 
1471   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1472   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1473   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1476   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1477   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1478     next if ($spec !~ m/^lower_(.*)$/);
 
1481     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1484   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1485   $sth = prepare_query($form, $dbh, $query);
 
1488       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1489            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1490            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1491            $columns_for_sorting{arap}
 
1493          JOIN $arap a ON (ac.trans_id = a.id)
 
1494          JOIN $table c ON (c.id = a.${table}_id)
 
1496          WHERE (ac.chart_id = ?)
 
1502          SELECT g.description, g.reference, NULL AS ordnumber,
 
1503            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1504            '0' as invoice, g.id, ac.memo, 'gl' AS module
 
1505            $columns_for_sorting{gl}
 
1507          JOIN gl g ON (g.id = ac.trans_id)
 
1509          WHERE (ac.chart_id = ?)
 
1512            AND (ac.amount * $ml) > 0
 
1514          ORDER BY $sortorder|;
 
1515   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1519   # cycle through each id
 
1520   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1521     do_statement($form, $sth, $query, $accno);
 
1522     my $ref = $sth->fetchrow_hashref();
 
1523     push(@{ $form->{PR} }, $ref);
 
1526     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1528     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1529     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1530       push(@{ $form->{ $ref->{id} } }, $pr);
 
1532     $sth_details->finish();
 
1537   $main::lxdebug->leave_sub();
 
1541   $main::lxdebug->enter_sub();
 
1543   my ($self, $myconfig, $form) = @_;
 
1545   # connect to database
 
1546   my $dbh = $form->dbconnect($myconfig);
 
1548   my $last_period = 0;
 
1551     qw(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40);
 
1553   $form->{decimalplaces} *= 1;
 
1555   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1557   # if there are any compare dates
 
1559   if ($form->{fromdate} || $form->{todate}) {
 
1561     if ($form->{fromdate}) {
 
1562       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1565       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1568     my $kummfromdate = $form->{comparefromdate};
 
1569     my $kummtodate   = $form->{comparetodate};
 
1570     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1573   my @periods        = qw(jetzt kumm);
 
1574   my @gesamtleistung = qw(1 3);
 
1575   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
 
1577     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1579   foreach my $key (@periods) {
 
1580     $form->{ "$key" . "gesamtleistung" } = 0;
 
1581     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1583     foreach $category (@categories) {
 
1585       if (defined($form->{$category}{$key})) {
 
1586         $form->{"$key$category"} =
 
1587           $form->format_amount($myconfig,
 
1588                                $form->round_amount($form->{$category}{$key}, 2
 
1590                                $form->{decimalplaces},
 
1594     foreach my $item (@gesamtleistung) {
 
1595       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1597     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1599     foreach my $item (@gesamtkosten) {
 
1600       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1602     $form->{ "$key" . "rohertrag" } =
 
1603       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1604     $form->{ "$key" . "betriebrohertrag" } =
 
1605       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1606     $form->{ "$key" . "betriebsergebnis" } =
 
1607       $form->{ "$key" . "betriebrohertrag" } -
 
1608       $form->{ "$key" . "gesamtkosten" };
 
1609     $form->{ "$key" . "neutraleraufwand" } =
 
1610       $form->{30}{$key} + $form->{31}{$key};
 
1611     $form->{ "$key" . "neutralertrag" } =
 
1612       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1613     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1614       $form->{ "$key" . "betriebsergebnis" } -
 
1615       $form->{ "$key" . "neutraleraufwand" } +
 
1616       $form->{ "$key" . "neutralertrag" };
 
1617     $form->{ "$key" . "ergebnis" } =
 
1618       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1620     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1621       foreach $category (@categories) {
 
1622         if (defined($form->{$category}{$key})) {
 
1623           $form->{ "$key" . "gl" . "$category" } =
 
1624             $form->format_amount(
 
1626                                $form->round_amount(
 
1627                                  ($form->{$category}{$key} /
 
1628                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1630                                  $form->{decimalplaces}
 
1632                                $form->{decimalplaces},
 
1636       foreach my $item (@ergebnisse) {
 
1637         $form->{ "$key" . "gl" . "$item" } =
 
1638           $form->format_amount($myconfig,
 
1639                                $form->round_amount(
 
1640                                  ( $form->{ "$key" . "$item" } /
 
1641                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1643                                  $form->{decimalplaces}
 
1645                                $form->{decimalplaces},
 
1650     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1651       foreach $category (@categories) {
 
1652         if (defined($form->{$category}{$key})) {
 
1653           $form->{ "$key" . "gk" . "$category" } =
 
1654             $form->format_amount($myconfig,
 
1655                                  $form->round_amount(
 
1656                                    ($form->{$category}{$key} /
 
1657                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1659                                    $form->{decimalplaces}
 
1661                                  $form->{decimalplaces},
 
1665       foreach my $item (@ergebnisse) {
 
1666         $form->{ "$key" . "gk" . "$item" } =
 
1667           $form->format_amount($myconfig,
 
1668                                $form->round_amount(
 
1669                                    ($form->{ "$key" . "$item" } /
 
1670                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1672                                    $form->{decimalplaces}
 
1674                                $form->{decimalplaces},
 
1679     if ($form->{10}{$key} > 0) {
 
1680       foreach $category (@categories) {
 
1681         if (defined($form->{$category}{$key})) {
 
1682           $form->{ "$key" . "pk" . "$category" } =
 
1683             $form->format_amount(
 
1685                         $form->round_amount(
 
1686                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1687                           $form->{decimalplaces}
 
1689                         $form->{decimalplaces},
 
1693       foreach my $item (@ergebnisse) {
 
1694         $form->{ "$key" . "pk" . "$item" } =
 
1695           $form->format_amount($myconfig,
 
1696                                $form->round_amount(
 
1697                                                 ($form->{ "$key" . "$item" } /
 
1698                                                    $form->{10}{$key} * 100
 
1700                                                 $form->{decimalplaces}
 
1702                                $form->{decimalplaces},
 
1707     if ($form->{4}{$key} > 0) {
 
1708       foreach $category (@categories) {
 
1709         if (defined($form->{$category}{$key})) {
 
1710           $form->{ "$key" . "auf" . "$category" } =
 
1711             $form->format_amount(
 
1713                          $form->round_amount(
 
1714                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1715                            $form->{decimalplaces}
 
1717                          $form->{decimalplaces},
 
1721       foreach my $item (@ergebnisse) {
 
1722         $form->{ "$key" . "auf" . "$item" } =
 
1723           $form->format_amount($myconfig,
 
1724                                $form->round_amount(
 
1725                                                 ($form->{ "$key" . "$item" } /
 
1726                                                    $form->{4}{$key} * 100
 
1728                                                 $form->{decimalplaces}
 
1730                                $form->{decimalplaces},
 
1735     foreach my $item (@ergebnisse) {
 
1736       $form->{ "$key" . "$item" } =
 
1737         $form->format_amount($myconfig,
 
1738                              $form->round_amount($form->{ "$key" . "$item" },
 
1739                                                  $form->{decimalplaces}
 
1741                              $form->{decimalplaces},
 
1748   $main::lxdebug->leave_sub();
 
1752   $main::lxdebug->enter_sub();
 
1754   my ($self, $myconfig, $form) = @_;
 
1756   # connect to database
 
1757   my $dbh = $form->dbconnect($myconfig);
 
1759   my $last_period     = 0;
 
1760   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
 
1761     96 66 43 45 53 62 65 67);
 
1762   my @categories_euro = qw(48 51 86 91 97 93 94);
 
1763   $form->{decimalplaces} *= 1;
 
1765   foreach my $item (@categories_cent) {
 
1766     $form->{"$item"} = 0;
 
1768   foreach my $item (@categories_euro) {
 
1769     $form->{"$item"} = 0;
 
1772   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_ustva");
 
1774   #   foreach $item (@categories_cent) {
 
1775   #     if ($form->{$item}{"jetzt"} > 0) {
 
1776   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1777   #             delete $form->{$item}{"jetzt"};
 
1780   #   foreach $item (@categories_euro) {
 
1781   #     if ($form->{$item}{"jetzt"} > 0) {
 
1782   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1783   #             delete $form->{$item}{"jetzt"};
 
1784   #     }  foreach $item (@categories_cent) {
 
1785   #     if ($form->{$item}{"jetzt"} > 0) {
 
1786   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1787   #             delete $form->{$item}{"jetzt"};
 
1790   #   foreach $item (@categories_euro) {
 
1791   #     if ($form->{$item}{"jetzt"} > 0) {
 
1792   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1793   #             delete $form->{$item}{"jetzt"};
 
1800   # Berechnung der USTVA Formularfelder
 
1802   $form->{"51r"} = $form->{"511"};
 
1803   $form->{"86r"} = $form->{"861"};
 
1804   $form->{"97r"} = $form->{"971"};
 
1805   $form->{"93r"} = $form->{"931"};
 
1807   #$form->{"96"}  = $form->{"94"} * 0.16;
 
1809     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
 
1811   $form->{"45"} = $form->{"43"};
 
1812   $form->{"53"} = $form->{"43"};
 
1813   $form->{"62"} = $form->{"43"} - $form->{"66"};
 
1814   $form->{"65"} = $form->{"43"} - $form->{"66"};
 
1815   $form->{"67"} = $form->{"43"} - $form->{"66"};
 
1817   foreach my $item (@categories_cent) {
 
1819       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
 
1823   foreach my $item (@categories_euro) {
 
1825       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
 
1831   $main::lxdebug->leave_sub();
 
1834 sub income_statement {
 
1835   $main::lxdebug->enter_sub();
 
1837   my ($self, $myconfig, $form) = @_;
 
1839   # connect to database
 
1840   my $dbh = $form->dbconnect($myconfig);
 
1842   my $last_period          = 0;
 
1843   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1844   my @categories_ausgaben  =
 
1845     qw(8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31);
 
1847   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1849   $form->{decimalplaces} *= 1;
 
1853   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1857   foreach my $item (@categories_einnahmen) {
 
1858     $form->{"eur${item}"} =
 
1859       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1860     $form->{"sumeura"} += $form->{$item};
 
1862   foreach my $item (@categories_ausgaben) {
 
1863     $form->{"eur${item}"} =
 
1864       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1865     $form->{"sumeurb"} += $form->{$item};
 
1868   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1870   foreach my $item (@ergebnisse) {
 
1872       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1874   $main::lxdebug->leave_sub();