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};
 
 446     $fromdate = conv_dateq($fromdate);
 
 447     if ($form->{method} eq 'cash') {
 
 448       $subwhere .= " AND (transdate    >= $fromdate)";
 
 449       $glwhere   = " AND (ac.transdate >= $fromdate)";
 
 450       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 451       $inwhere   = " AND (acc.transdate >= $fromdate)";
 
 453       $where    .= " AND (ac.transdate >= $fromdate)";
 
 458     $todate = conv_dateq($todate);
 
 459     $subwhere   .= " AND (transdate    <= $todate)";
 
 460     $where      .= " AND (ac.transdate <= $todate)";
 
 461     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 462     $inwhere    .= " AND (acc.transdate <= $todate)";
 
 465   if ($department_id) {
 
 466     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
 
 467     $dpt_where = qq| AND (t.id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 470   if ($form->{project_id}) {
 
 471     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
 
 475 # GUV patch by Ronny Rentner (Bug 1190)
 
 477 # GUV IST-Versteuerung
 
 479 # Alle tatsaechlichen _Zahlungseingaenge_
 
 480 # im Zeitraum erfassen
 
 481 # (Teilzahlungen werden prozentual auf verschiedene Steuern aufgeteilt)
 
 485   if ($form->{method} eq 'cash') {
 
 488        SELECT SUM( ac.amount *
 
 489                     (SELECT SUM(acc.amount) * -1
 
 491                      INNER JOIN chart c ON (acc.chart_id = c.id AND c.link LIKE '%AR_paid%')
 
 492                      WHERE 1=1 $inwhere AND acc.trans_id = ac.trans_id)
 
 493                   / (SELECT amount FROM ar WHERE id = ac.trans_id)
 
 494                 ) AS amount, c.pos_eur
 
 496        LEFT JOIN chart c ON (c.id  = ac.chart_id)
 
 497        LEFT JOIN ar      ON (ar.id = ac.trans_id)
 
 498        LEFT JOIN taxkeys tk ON (tk.id = (
 
 499                                   SELECT id FROM taxkeys
 
 500                                   WHERE chart_id = ac.chart_id
 
 501                                   AND startdate <= COALESCE(ar.deliverydate,ar.transdate)
 
 502                                   ORDER BY startdate DESC LIMIT 1
 
 505       WHERE ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE 1=1 $subwhere)
 
 510        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 512          JOIN chart c ON (c.id = ac.chart_id)
 
 513          JOIN ar a ON (a.id = ac.trans_id)
 
 515          WHERE $where $dpt_where
 
 516            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AR_paid%') $subwhere)
 
 522          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 524          JOIN chart c ON (c.id = ac.chart_id)
 
 525          JOIN ap a ON (a.id = ac.trans_id)
 
 527          WHERE $where $dpt_where
 
 528            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AP_paid%') $subwhere)
 
 534          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 536          JOIN chart c ON (c.id = ac.chart_id)
 
 537          JOIN gl a ON (a.id = ac.trans_id)
 
 539          WHERE $where $dpt_where $glwhere
 
 540            AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
 
 545     if ($form->{project_id}) {
 
 549          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 551          JOIN ar a ON (a.id = ac.trans_id)
 
 552          JOIN parts p ON (ac.parts_id = p.id)
 
 553          JOIN chart c on (p.income_accno_id = c.id)
 
 555          WHERE (c.category = 'I') $prwhere $dpt_where
 
 556            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AR_paid%') $subwhere)
 
 562          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 564          JOIN ap a ON (a.id = ac.trans_id)
 
 565          JOIN parts p ON (ac.parts_id = p.id)
 
 566          JOIN chart c on (p.expense_accno_id = c.id)
 
 568          WHERE (c.category = 'E') $prwhere $dpt_where
 
 569            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AP_paid%') $subwhere)
 
 575   } else {                      # if ($form->{method} eq 'cash')
 
 576     if ($department_id) {
 
 577       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
 578       $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 582         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 584         JOIN chart c ON (c.id = ac.chart_id)
 
 589         GROUP BY c.$category |;
 
 591     if ($form->{project_id}) {
 
 595         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 597         JOIN ar a ON (a.id = ac.trans_id)
 
 598         JOIN parts p ON (ac.parts_id = p.id)
 
 599         JOIN chart c on (p.income_accno_id = c.id)
 
 601         WHERE (c.category = 'I')
 
 609         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 611         JOIN ap a ON (a.id = ac.trans_id)
 
 612         JOIN parts p ON (ac.parts_id = p.id)
 
 613         JOIN chart c on (p.expense_accno_id = c.id)
 
 615         WHERE (c.category = 'E')
 
 619         GROUP BY c.$category |;
 
 627   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
 
 628     if ($category eq "pos_bwa") {
 
 630         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 632         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 635       $form->{ $ref->{$category} } += $ref->{amount};
 
 639   $main::lxdebug->leave_sub();
 
 643   $main::lxdebug->enter_sub();
 
 645   my ($self, $myconfig, $form, %options) = @_;
 
 647   my $dbh = $form->dbconnect($myconfig);
 
 649   my ($query, $sth, $ref);
 
 652   my ($null, $department_id) = split /--/, $form->{department};
 
 653   my @headingaccounts = ();
 
 659   my $invwhere = $where;
 
 661   if ($department_id) {
 
 662     $dpt_join = qq| JOIN dpt_trans t ON (ac.trans_id = t.trans_id) |;
 
 663     $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 666   # project_id only applies to getting transactions
 
 667   # it has nothing to do with a trial balance
 
 668   # but we use the same function to collect information
 
 670   if ($form->{project_id}) {
 
 671     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 674   my $acc_cash_where = "";
 
 675 #  my $ar_cash_where = "";
 
 676 #  my $ap_cash_where = "";
 
 679   if ($form->{method} eq "cash") {
 
 681       qq| AND (ac.trans_id IN (
 
 684             WHERE datepaid >= '$form->{fromdate}'
 
 685               AND datepaid <= '$form->{todate}'
 
 691             WHERE datepaid >= '$form->{fromdate}'
 
 692               AND datepaid <= '$form->{todate}'
 
 698             WHERE transdate >= '$form->{fromdate}'
 
 699               AND transdate <= '$form->{todate}'
 
 701 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 704   if ($options{beginning_balances}) {
 
 705     foreach my $prefix (qw(from to)) {
 
 706       next if ($form->{"${prefix}date"});
 
 708       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 709       $query      = qq|SELECT ${min_max}(transdate)
 
 715       ($form->{"${prefix}date"}) = selectfirst_array_query($form, $dbh, $query);
 
 718     # get beginning balances
 
 720       qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
 
 722           LEFT JOIN chart c ON (ac.chart_id = c.id)
 
 724           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 727           GROUP BY c.accno, c.category, c.description |;
 
 729     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 731     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 733       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 734         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 735         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 736         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 738         if ($ref->{amount} > 0) {
 
 739           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 741           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 743         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 752     qq|SELECT c.accno, c.description, c.category
 
 754        WHERE c.charttype = 'H'
 
 757   $sth = prepare_execute_query($form, $dbh, $query);
 
 759   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 760     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 761     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 762     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 764     push @headingaccounts, $ref->{accno};
 
 770   my $saldowhere    = " 1 = 1 ";
 
 771   my $sumwhere      = " 1 = 1 ";
 
 773   my $sumsubwhere   = '';
 
 774   my $saldosubwhere = '';
 
 775   my $glsaldowhere  = '';
 
 780   my ($fromdate, $todate);
 
 782   if ($form->{fromdate} || $form->{todate}) {
 
 783     if ($form->{fromdate}) {
 
 784       $fromdate = conv_dateq($form->{fromdate});
 
 785       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 786       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 787       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 788       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 789       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 790       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 791       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 792       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 794     if ($form->{todate}) {
 
 795       $todate = conv_dateq($form->{todate});
 
 796       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 797       $invwhere      .= " AND (a.transdate <= $todate)";
 
 798       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 799       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 800       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 801       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 802       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 803       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 807   if ($form->{method} eq "cash") {
 
 809       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) |;
 
 810     $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) |;
 
 812     $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) |;
 
 814     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 815     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 816     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 820        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 822        JOIN chart c ON (c.id = ac.chart_id)
 
 827        GROUP BY c.accno, c.description, c.category |;
 
 829   if ($form->{project_id}) {
 
 831       -- add project transactions from invoice
 
 835       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 837       JOIN ar a ON (ac.trans_id = a.id)
 
 838       JOIN parts p ON (ac.parts_id = p.id)
 
 839       JOIN chart c ON (p.income_accno_id = c.id)
 
 844       GROUP BY c.accno, c.description, c.category
 
 848       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 850       JOIN ap a ON (ac.trans_id = a.id)
 
 851       JOIN parts p ON (ac.parts_id = p.id)
 
 852       JOIN chart c ON (p.expense_accno_id = c.id)
 
 857       GROUP BY c.accno, c.description, c.category
 
 861   $query .= qq| ORDER BY accno|;
 
 863   $sth = prepare_execute_query($form, $dbh, $query);
 
 865   # calculate the debit and credit in the period
 
 866   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 867     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 868     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 869     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 870     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 874   # prepare query for each account
 
 875   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 879          (SELECT SUM(ac.amount) * -1
 
 881           JOIN chart c ON (c.id = ac.chart_id)
 
 887           AND (c.accno = ?)) AS debit,
 
 889          (SELECT SUM(ac.amount)
 
 891           JOIN chart c ON (c.id = ac.chart_id)
 
 897           AND c.accno = ?) AS credit,
 
 898         (SELECT SUM(ac.amount)
 
 900          JOIN chart c ON (ac.chart_id = c.id)
 
 905          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 907         (SELECT SUM(ac.amount)
 
 909          JOIN chart c ON (ac.chart_id = c.id)
 
 915          AND c.accno = ?) AS sum_credit,
 
 917         (SELECT SUM(ac.amount)
 
 919          JOIN chart c ON (ac.chart_id = c.id)
 
 925          AND c.accno = ?) AS sum_debit,
 
 927         (SELECT max(ac.transdate) FROM acc_trans ac
 
 928         JOIN chart c ON (ac.chart_id = c.id)
 
 933         AND c.accno = ?) AS last_transaction
 
 938   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 940   if ($form->{project_id}) {
 
 941     # prepare query for each account
 
 944           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
 946            JOIN parts p ON (ac.parts_id = p.id)
 
 947            JOIN ap a ON (ac.trans_id = a.id)
 
 948            JOIN chart c ON (p.expense_accno_id = c.id)
 
 953            AND c.accno = ?) AS debit,
 
 955           (SELECT SUM(ac.sellprice * ac.qty)
 
 957            JOIN parts p ON (ac.parts_id = p.id)
 
 958            JOIN ar a ON (ac.trans_id = a.id)
 
 959            JOIN chart c ON (p.income_accno_id = c.id)
 
 964            AND c.accno = ?) AS credit,
 
 966         (SELECT SUM(ac.amount)
 
 968          JOIN chart c ON (ac.chart_id = c.id)
 
 973          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 975         (SELECT SUM(ac.amount)
 
 977          JOIN chart c ON (ac.chart_id = c.id)
 
 983          AND c.accno = ?) AS sum_credit,
 
 985         (SELECT SUM(ac.amount)
 
 987          JOIN chart c ON (ac.chart_id = c.id)
 
 993          AND c.accno = ?) AS sum_debit,
 
 996         (SELECT max(ac.transdate) FROM acc_trans ac
 
 997         JOIN chart c ON (ac.chart_id = c.id)
 
1002         AND c.accno = ?) AS last_transaction
 
1005     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
1009   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
1011   foreach my $accno (sort keys %trb) {
 
1014     $ref->{accno} = $accno;
 
1015     map { $ref->{$_} = $trb{$accno}{$_} }
 
1016       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
1018     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
1020     if ($trb{$accno}{charttype} eq 'A') {
 
1023       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1025       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
1026       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
1027       $last_transaction = "";
 
1028       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
1029         $ref->{debit}  += $debit;
 
1030         $ref->{credit} += $credit;
 
1032           $ref->{haben_saldo} += $saldo;
 
1034           $ref->{soll_saldo} += $saldo * -1;
 
1036         $ref->{last_transaction} = $last_transaction;
 
1037         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1038         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1042       if ($form->{project_id}) {
 
1045         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1047         ($debit, $credit) = (0, 0);
 
1048         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1049           $ref->{debit}  += $debit;
 
1050           $ref->{credit} += $credit;
 
1052             $ref->{haben_saldo} += $saldo;
 
1054             $ref->{soll_saldo} += $saldo * -1;
 
1056           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1057           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1059         $project_drcr->finish;
 
1062       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1063       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1065       if ($ref->{haben_saldo} != 0) {
 
1066         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1067         if ($ref->{haben_saldo} < 0) {
 
1068           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1069           $ref->{haben_saldo} = 0;
 
1072         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1073         if ($ref->{soll_saldo} < 0) {
 
1074           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1075           $ref->{soll_saldo} = 0;
 
1078       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1079       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1080       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1081       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1086     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1087     $accno = pop @accno;
 
1089       $trb{$accno}{debit}  += $ref->{debit};
 
1090       $trb{$accno}{credit} += $ref->{credit};
 
1091       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1092       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1093       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1094       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1097     push @{ $form->{TB} }, $ref;
 
1103   # debits and credits for headings
 
1104   foreach my $accno (@headingaccounts) {
 
1105     foreach $ref (@{ $form->{TB} }) {
 
1106       if ($accno eq $ref->{accno}) {
 
1107         $ref->{debit}           = $trb{$accno}{debit};
 
1108         $ref->{credit}          = $trb{$accno}{credit};
 
1109         $ref->{soll_saldo}      = $trb{$accno}{soll_saldo};
 
1110         $ref->{haben_saldo}     = $trb{$accno}{haben_saldo};
 
1111         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
 
1112         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};
 
1117   $main::lxdebug->leave_sub();
 
1121   $main::lxdebug->enter_sub();
 
1122   my ($self, $dbh, $form) = @_;
 
1123   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
 
1124   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
 
1125   my $sth =  $dbh->prepare($query);
 
1126   while(my $ref = $sth->fetchrow_hashref()) {
 
1127     $ref->{invnumer} =~ s/Storno zu //g;
 
1128     $form->{storno}{$ref->{invnumber}} = 1;
 
1130   $main::lxdebug->leave_sub();
 
1134   $main::lxdebug->enter_sub();
 
1136   my ($self, $myconfig, $form) = @_;
 
1138   # connect to database
 
1139   my $dbh     = $form->dbconnect($myconfig);
 
1141   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
 
1143   if ($form->{ct} eq "customer") {
 
1156   $ct_id = "${ct}_id";
 
1158   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
 
1159   my $todate = conv_dateq($form->{todate});
 
1160   my $fromdate = conv_dateq($form->{fromdate});
 
1162   my $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
 
1164   my $where = " 1 = 1 ";
 
1167   if ($form->{$ct_id}) {
 
1168     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
 
1169   } elsif ($form->{ $form->{ct} }) {
 
1170     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
 
1174   if ($form->{department}) {
 
1175     my ($null, $department_id) = split /--/, $form->{department};
 
1176     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
 
1177     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1181     -- between 0-30 days
 
1183     SELECT ${ct}.id AS ctid, ${ct}.name,
 
1184       street, zipcode, city, country, contact, email,
 
1185       phone as customerphone, fax as customerfax, ${ct}number,
 
1186       "invnumber", "transdate",
 
1187       (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",
 
1188       "duedate", invoice, ${arap}.id,
 
1191        WHERE (${arap}.curr = exchangerate.curr)
 
1192          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
 
1194     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
 
1195       AND (${arap}.storno IS FALSE)
 
1196       AND (${arap}.${ct}_id = ${ct}.id)
 
1198       AND (transdate <= (date $todate) $fromwhere )
 
1200     ORDER BY ctid, transdate, invnumber |;
 
1202   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1204   # select outstanding vendors or customers, depends on $ct
 
1206     qq|SELECT DISTINCT ct.id, ct.name
 
1207        FROM $ct ct, $arap a
 
1210          AND (a.${ct_id} = ct.id)
 
1211          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
 
1212          AND (a.transdate <= $todate $fromwhere)
 
1215   my $sth = prepare_execute_query($form, $dbh, $query);
 
1218   # for each company that has some stuff outstanding
 
1219   while (my ($id) = $sth->fetchrow_array) {
 
1220     do_statement($form, $sth_details, $q_details, $id);
 
1222     while (my $ref = $sth_details->fetchrow_hashref("NAME_lc")) {
 
1223       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
 
1224       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
 
1225       push @{ $form->{AG} }, $ref;
 
1228     $sth_details->finish;
 
1237   $main::lxdebug->leave_sub();
 
1241   $main::lxdebug->enter_sub();
 
1243   my ($self, $myconfig, $form) = @_;
 
1245   # connect to database
 
1246   my $dbh = $form->dbconnect($myconfig);
 
1248   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1251     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1254   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1255     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1258   $main::lxdebug->leave_sub();
 
1261 sub get_taxaccounts {
 
1262   $main::lxdebug->enter_sub();
 
1264   my ($self, $myconfig, $form) = @_;
 
1266   # connect to database
 
1267   my $dbh = $form->dbconnect($myconfig);
 
1271     qq|SELECT c.accno, c.description, t.rate
 
1273        WHERE (c.link LIKE '%CT_tax%') AND (c.id = t.chart_id)
 
1275   $form->{taxaccounts} = selectall_hashref_quert($form, $dbh, $query);
 
1279   $main::lxdebug->leave_sub();
 
1283   $main::lxdebug->enter_sub();
 
1285   my ($self, $myconfig, $form) = @_;
 
1287   # connect to database
 
1288   my $dbh = $form->dbconnect($myconfig);
 
1290   my ($null, $department_id) = split /--/, $form->{department};
 
1293   my $where = "1 = 1";
 
1295   if ($department_id) {
 
1296     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1301   if ($form->{accno}) {
 
1302     $accno = $form->{accno};
 
1303     $rate  = $form->{"$form->{accno}_rate"};
 
1304     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1310   if ($form->{db} eq 'ar') {
 
1311     $table = "customer";
 
1318   my $arap = lc($ARAP);
 
1320   my $transdate = "a.transdate";
 
1322   if ($form->{method} eq 'cash') {
 
1323     $transdate = "a.datepaid";
 
1325     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1332           JOIN chart ON (chart_id = id)
 
1333           WHERE (link LIKE '%${ARAP}_paid%')
 
1334           AND (transdate <= $todate)
 
1339   # if there are any dates construct a where
 
1340   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1341   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1343   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1345   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1346   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1349   if ($form->{report} !~ /nontaxable/) {
 
1351       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1352           ac.amount * $ml AS tax
 
1354          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1355          JOIN chart ch ON (ch.id = ac.chart_id)
 
1356          JOIN $table n ON (n.id = a.${table}_id)
 
1360            AND (a.invoice = '0')
 
1364          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1365            i.sellprice * i.qty * $rate * $ml AS tax
 
1367          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1368          JOIN chart ch ON (ch.id = ac.chart_id)
 
1369          JOIN $table n ON (n.id = a.${table}_id)
 
1370          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1371          JOIN invoice i ON (i.trans_id = a.id)
 
1372          JOIN partstax p ON (p.parts_id = i.parts_id)
 
1376            AND (a.invoice = '1')
 
1377          ORDER BY $sortorder|;
 
1379     # only gather up non-taxable transactions
 
1381       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount
 
1383          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1384          JOIN $table n ON (n.id = a.${table}_id)
 
1387            AND (a.invoice = '0')
 
1388            AND (a.netamount = a.amount)
 
1392          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount
 
1394          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1395          JOIN $table n ON (n.id = a.${table}_id)
 
1396          JOIN invoice i ON (i.trans_id = a.id)
 
1399            AND (a.invoice = '1')
 
1401              a.${table}_id NOT IN (SELECT ${table}_id FROM ${table}tax t (${table}_id))
 
1403              i.parts_id NOT IN (SELECT parts_id FROM partstax p (parts_id))
 
1405          GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
 
1406          ORDER by $sortorder|;
 
1409   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1413   $main::lxdebug->leave_sub();
 
1416 sub paymentaccounts {
 
1417   $main::lxdebug->enter_sub();
 
1419   my ($self, $myconfig, $form) = @_;
 
1421   # connect to database, turn AutoCommit off
 
1422   my $dbh = $form->dbconnect_noauto($myconfig);
 
1424   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1426   # get A(R|P)_paid accounts
 
1428     qq|SELECT accno, description
 
1430        WHERE link LIKE '%${ARAP}_paid%'|;
 
1431   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1435   $main::lxdebug->leave_sub();
 
1439   $main::lxdebug->enter_sub();
 
1441   my ($self, $myconfig, $form) = @_;
 
1443   # connect to database, turn AutoCommit off
 
1444   my $dbh = $form->dbconnect_noauto($myconfig);
 
1449   if ($form->{db} eq 'ar') {
 
1450     $table = 'customer';
 
1462   if ($form->{department_id}) {
 
1463     $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
1464     $where = qq| AND (t.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1467   if ($form->{fromdate}) {
 
1468     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1470   if ($form->{todate}) {
 
1471     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1473   if (!$form->{fx_transaction}) {
 
1474     $where .= " AND ac.fx_transaction = '0'";
 
1479   if ($form->{reference}) {
 
1480     $reference = $dbh->quote('%' . $form->{reference} . '%');
 
1481     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1482     $reference = " AND (g.reference LIKE $reference)";
 
1484   if ($form->{source}) {
 
1485     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
 
1487   if ($form->{memo}) {
 
1488     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
 
1491   my %sort_columns =  (
 
1492     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1493     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1494     'name'         => [ qw(lower_name transdate)                 ],
 
1495     'source'       => [ qw(lower_source)                         ],
 
1496     'memo'         => [ qw(lower_memo)                           ],
 
1498   my %lowered_columns =  (
 
1499     'invnumber'       => { 'gl' => 'g.reference',   'arap' => 'a.invnumber', },
 
1500     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1501     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1502     'name'            => { 'gl' => 'g.description', 'arap' => 'c.name',      },
 
1505   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1506   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1507   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1510   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1511   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1512     next if ($spec !~ m/^lower_(.*)$/);
 
1515     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1518   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1519   $sth = prepare_query($form, $dbh, $query);
 
1522       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1523            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1524            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1525            $columns_for_sorting{arap}
 
1527          JOIN $arap a ON (ac.trans_id = a.id)
 
1528          JOIN $table c ON (c.id = a.${table}_id)
 
1530          WHERE (ac.chart_id = ?)
 
1536          SELECT g.description, g.reference, NULL AS ordnumber,
 
1537            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1538            '0' as invoice, g.id, ac.memo, 'gl' AS module
 
1539            $columns_for_sorting{gl}
 
1541          JOIN gl g ON (g.id = ac.trans_id)
 
1543          WHERE (ac.chart_id = ?)
 
1546            AND (ac.amount * $ml) > 0
 
1548          ORDER BY $sortorder|;
 
1549   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1553   # cycle through each id
 
1554   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1555     do_statement($form, $sth, $query, $accno);
 
1556     my $ref = $sth->fetchrow_hashref();
 
1557     push(@{ $form->{PR} }, $ref);
 
1560     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1562     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1563     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1564       push(@{ $form->{ $ref->{id} } }, $pr);
 
1566     $sth_details->finish();
 
1571   $main::lxdebug->leave_sub();
 
1575   $main::lxdebug->enter_sub();
 
1577   my ($self, $myconfig, $form) = @_;
 
1579   # connect to database
 
1580   my $dbh = $form->dbconnect($myconfig);
 
1582   my $last_period = 0;
 
1585     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);
 
1587   $form->{decimalplaces} *= 1;
 
1589   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1591   # if there are any compare dates
 
1593   if ($form->{fromdate} || $form->{todate}) {
 
1595     if ($form->{fromdate}) {
 
1596       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1599       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1602     my $kummfromdate = $form->{comparefromdate};
 
1603     my $kummtodate   = $form->{comparetodate};
 
1604     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1607   my @periods        = qw(jetzt kumm);
 
1608   my @gesamtleistung = qw(1 3);
 
1609   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
 
1611     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1613   foreach my $key (@periods) {
 
1614     $form->{ "$key" . "gesamtleistung" } = 0;
 
1615     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1617     foreach $category (@categories) {
 
1619       if (defined($form->{$category}{$key})) {
 
1620         $form->{"$key$category"} =
 
1621           $form->format_amount($myconfig,
 
1622                                $form->round_amount($form->{$category}{$key}, 2
 
1624                                $form->{decimalplaces},
 
1628     foreach my $item (@gesamtleistung) {
 
1629       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1631     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1633     foreach my $item (@gesamtkosten) {
 
1634       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1636     $form->{ "$key" . "rohertrag" } =
 
1637       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1638     $form->{ "$key" . "betriebrohertrag" } =
 
1639       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1640     $form->{ "$key" . "betriebsergebnis" } =
 
1641       $form->{ "$key" . "betriebrohertrag" } -
 
1642       $form->{ "$key" . "gesamtkosten" };
 
1643     $form->{ "$key" . "neutraleraufwand" } =
 
1644       $form->{30}{$key} + $form->{31}{$key};
 
1645     $form->{ "$key" . "neutralertrag" } =
 
1646       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1647     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1648       $form->{ "$key" . "betriebsergebnis" } -
 
1649       $form->{ "$key" . "neutraleraufwand" } +
 
1650       $form->{ "$key" . "neutralertrag" };
 
1651     $form->{ "$key" . "ergebnis" } =
 
1652       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1654     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1655       foreach $category (@categories) {
 
1656         if (defined($form->{$category}{$key})) {
 
1657           $form->{ "$key" . "gl" . "$category" } =
 
1658             $form->format_amount(
 
1660                                $form->round_amount(
 
1661                                  ($form->{$category}{$key} /
 
1662                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1664                                  $form->{decimalplaces}
 
1666                                $form->{decimalplaces},
 
1670       foreach my $item (@ergebnisse) {
 
1671         $form->{ "$key" . "gl" . "$item" } =
 
1672           $form->format_amount($myconfig,
 
1673                                $form->round_amount(
 
1674                                  ( $form->{ "$key" . "$item" } /
 
1675                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1677                                  $form->{decimalplaces}
 
1679                                $form->{decimalplaces},
 
1684     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1685       foreach $category (@categories) {
 
1686         if (defined($form->{$category}{$key})) {
 
1687           $form->{ "$key" . "gk" . "$category" } =
 
1688             $form->format_amount($myconfig,
 
1689                                  $form->round_amount(
 
1690                                    ($form->{$category}{$key} /
 
1691                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1693                                    $form->{decimalplaces}
 
1695                                  $form->{decimalplaces},
 
1699       foreach my $item (@ergebnisse) {
 
1700         $form->{ "$key" . "gk" . "$item" } =
 
1701           $form->format_amount($myconfig,
 
1702                                $form->round_amount(
 
1703                                    ($form->{ "$key" . "$item" } /
 
1704                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1706                                    $form->{decimalplaces}
 
1708                                $form->{decimalplaces},
 
1713     if ($form->{10}{$key} > 0) {
 
1714       foreach $category (@categories) {
 
1715         if (defined($form->{$category}{$key})) {
 
1716           $form->{ "$key" . "pk" . "$category" } =
 
1717             $form->format_amount(
 
1719                         $form->round_amount(
 
1720                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1721                           $form->{decimalplaces}
 
1723                         $form->{decimalplaces},
 
1727       foreach my $item (@ergebnisse) {
 
1728         $form->{ "$key" . "pk" . "$item" } =
 
1729           $form->format_amount($myconfig,
 
1730                                $form->round_amount(
 
1731                                                 ($form->{ "$key" . "$item" } /
 
1732                                                    $form->{10}{$key} * 100
 
1734                                                 $form->{decimalplaces}
 
1736                                $form->{decimalplaces},
 
1741     if ($form->{4}{$key} > 0) {
 
1742       foreach $category (@categories) {
 
1743         if (defined($form->{$category}{$key})) {
 
1744           $form->{ "$key" . "auf" . "$category" } =
 
1745             $form->format_amount(
 
1747                          $form->round_amount(
 
1748                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1749                            $form->{decimalplaces}
 
1751                          $form->{decimalplaces},
 
1755       foreach my $item (@ergebnisse) {
 
1756         $form->{ "$key" . "auf" . "$item" } =
 
1757           $form->format_amount($myconfig,
 
1758                                $form->round_amount(
 
1759                                                 ($form->{ "$key" . "$item" } /
 
1760                                                    $form->{4}{$key} * 100
 
1762                                                 $form->{decimalplaces}
 
1764                                $form->{decimalplaces},
 
1769     foreach my $item (@ergebnisse) {
 
1770       $form->{ "$key" . "$item" } =
 
1771         $form->format_amount($myconfig,
 
1772                              $form->round_amount($form->{ "$key" . "$item" },
 
1773                                                  $form->{decimalplaces}
 
1775                              $form->{decimalplaces},
 
1782   $main::lxdebug->leave_sub();
 
1786   $main::lxdebug->enter_sub();
 
1788   my ($self, $myconfig, $form) = @_;
 
1790   # connect to database
 
1791   my $dbh = $form->dbconnect($myconfig);
 
1793   my $last_period     = 0;
 
1794   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
 
1795     96 66 43 45 53 62 65 67);
 
1796   my @categories_euro = qw(48 51 86 91 97 93 94);
 
1797   $form->{decimalplaces} *= 1;
 
1799   foreach my $item (@categories_cent) {
 
1800     $form->{"$item"} = 0;
 
1802   foreach my $item (@categories_euro) {
 
1803     $form->{"$item"} = 0;
 
1806   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_ustva");
 
1808   #   foreach $item (@categories_cent) {
 
1809   #     if ($form->{$item}{"jetzt"} > 0) {
 
1810   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1811   #             delete $form->{$item}{"jetzt"};
 
1814   #   foreach $item (@categories_euro) {
 
1815   #     if ($form->{$item}{"jetzt"} > 0) {
 
1816   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1817   #             delete $form->{$item}{"jetzt"};
 
1818   #     }  foreach $item (@categories_cent) {
 
1819   #     if ($form->{$item}{"jetzt"} > 0) {
 
1820   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1821   #             delete $form->{$item}{"jetzt"};
 
1824   #   foreach $item (@categories_euro) {
 
1825   #     if ($form->{$item}{"jetzt"} > 0) {
 
1826   #             $form->{$item} = $form->{$item}{"jetzt"};
 
1827   #             delete $form->{$item}{"jetzt"};
 
1834   # Berechnung der USTVA Formularfelder
 
1836   $form->{"51r"} = $form->{"511"};
 
1837   $form->{"86r"} = $form->{"861"};
 
1838   $form->{"97r"} = $form->{"971"};
 
1839   $form->{"93r"} = $form->{"931"};
 
1841   #$form->{"96"}  = $form->{"94"} * 0.16;
 
1843     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
 
1845   $form->{"45"} = $form->{"43"};
 
1846   $form->{"53"} = $form->{"43"};
 
1847   $form->{"62"} = $form->{"43"} - $form->{"66"};
 
1848   $form->{"65"} = $form->{"43"} - $form->{"66"};
 
1849   $form->{"67"} = $form->{"43"} - $form->{"66"};
 
1851   foreach my $item (@categories_cent) {
 
1853       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
 
1857   foreach my $item (@categories_euro) {
 
1859       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
 
1865   $main::lxdebug->leave_sub();
 
1868 sub income_statement {
 
1869   $main::lxdebug->enter_sub();
 
1871   my ($self, $myconfig, $form) = @_;
 
1873   # connect to database
 
1874   my $dbh = $form->dbconnect($myconfig);
 
1876   my $last_period          = 0;
 
1877   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1878   my @categories_ausgaben  =
 
1879     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);
 
1881   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1883   $form->{decimalplaces} *= 1;
 
1887   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1891   foreach my $item (@categories_einnahmen) {
 
1892     $form->{"eur${item}"} =
 
1893       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1894     $form->{"sumeura"} += $form->{$item};
 
1896   foreach my $item (@categories_ausgaben) {
 
1897     $form->{"eur${item}"} =
 
1898       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1899     $form->{"sumeurb"} += $form->{$item};
 
1902   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1904   foreach my $item (@ergebnisse) {
 
1906       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1908   $main::lxdebug->leave_sub();