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., 51 Franklin Street, Fifth Floor, Boston,
 
  30 #======================================================================
 
  32 # backend code for reports
 
  34 #======================================================================
 
  40 use SL::DB::Helper::AccountingPeriod qw(get_balance_starting_date);
 
  41 use List::Util qw(sum);
 
  47 # new implementation of balance sheet
 
  50 # stuff missing from the original implementation:
 
  53 # - proper testing for heading charts
 
  54 # - transmission from $form to TMPL realm is not as clear as i'd like
 
  57   $main::lxdebug->enter_sub();
 
  61   my $myconfig = \%main::myconfig;
 
  62   my $form     = $main::form;
 
  63   my $dbh      = $::form->get_standard_dbh;
 
  66   my @categories  = qw(A C L Q);
 
  68   # if there are any dates construct a where
 
  69   if ($form->{asofdate}) {
 
  70     $form->{period} = $form->{this_period} = conv_dateq($form->{asofdate});
 
  73   # get starting date for calculating balance
 
  74   $form->{this_startdate} = $self->get_balance_starting_date($form->{asofdate});
 
  76   get_accounts($dbh, $last_period, $form->{this_startdate}, $form->{asofdate}, $form, \@categories);
 
  78   # if there are any compare dates
 
  79   if ($form->{compareasofdate}) {
 
  82     $form->{last_startdate} = $self->get_balance_starting_date($form->{compareasofdate});
 
  84     get_accounts($dbh, $last_period, $form->{last_startdate} , $form->{compareasofdate}, $form, \@categories);
 
  85     $form->{last_period} = conv_dateq($form->{compareasofdate});
 
  88   # now we got $form->{A}{accno}{ }    assets
 
  89   # and $form->{L}{accno}{ }           liabilities
 
  90   # and $form->{Q}{accno}{ }           equity
 
  91   # build asset accounts
 
  93   my %account = ('A' => { 'ml'     => -1 },
 
  95                  'Q' => { 'ml'     =>  1 });
 
  99   foreach my $category (grep { !/C/ } @categories) {
 
 101     $TMPL_DATA->{$category} = [];
 
 102     my $ml  = $account{$category}{ml};
 
 104     foreach my $key (sort keys %{ $form->{$category} }) {
 
 106       my $row = { %{ $form->{$category}{$key} } };
 
 108       # if charttype "heading" - calculate this entry, start a new batch of charts belonging to this heading and skip the rest bo the loop
 
 109       # header charts are not real charts. start a sub aggregation with them, but don't calculate anything with them
 
 110       if ($row->{charttype} eq "H") {
 
 111         if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 112           $row->{subdescription} = $account{$category}{subdescription};
 
 113           $row->{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 114           $row->{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 117         $row->{subheader} = 1;
 
 118         $account{$category}{subthis}        = $row->{this};
 
 119         $account{$category}{sublast}        = $row->{last};
 
 120         $account{$category}{subdescription} = $row->{description};
 
 121         $account{$category}{subtotal} = 1;
 
 126         next unless $form->{l_heading};
 
 129       for my $period (qw(this last)) {
 
 130         next if ($period eq 'last' && !$last_period);
 
 132         $row->{$period}                    *= $ml;
 
 135       push @{ $TMPL_DATA->{$category} }, $row;
 
 138     # resolve heading/subtotal
 
 139     if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 140       $TMPL_DATA->{$category}[-1]{subdescription} = $account{$category}{subdescription};
 
 141       $TMPL_DATA->{$category}[-1]{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 142       $TMPL_DATA->{$category}[-1]{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 145     $TMPL_DATA->{total}{$category}{this} = sum map { $_->{this} } @{ $TMPL_DATA->{$category} };
 
 146     $TMPL_DATA->{total}{$category}{last} = sum map { $_->{last} } @{ $TMPL_DATA->{$category} };
 
 149   for my $period (qw(this last)) {
 
 150     next if ($period eq 'last' && !$last_period);
 
 152     $form->{E}{$period}             = $TMPL_DATA->{total}{A}{$period} - $TMPL_DATA->{total}{L}{$period} - $TMPL_DATA->{total}{Q}{$period};
 
 153     $TMPL_DATA->{total}{Q}{$period}     += $form->{E}{$period};
 
 154     $TMPL_DATA->{total}{$period}    = $TMPL_DATA->{total}{L}{$period} + $TMPL_DATA->{total}{Q}{$period};
 
 156     $form->{E}{description}='nicht verbuchter Gewinn/Verlust';
 
 157   push @{ $TMPL_DATA->{Q} }, $form->{E};
 
 159   $main::lxdebug->leave_sub();
 
 165   $main::lxdebug->enter_sub();
 
 167   my ($dbh, $last_period, $fromdate, $todate, $form, $categories) = @_;
 
 169   my ($null, $department_id) = split /--/, $form->{department};
 
 173   my $dpt_where_without_arapgl = '';
 
 180   my $dec = $form->{decimalplaces};
 
 182   my $category = qq| AND (| . join(" OR ", map({ "(c.category = " . $dbh->quote($_) . ")" } @{$categories})) . qq|) |;
 
 186     qq|SELECT c.accno, c.description, c.category
 
 188        WHERE (c.charttype = 'H')
 
 192   $sth = prepare_execute_query($form, $dbh, $query);
 
 194   my @headingaccounts = ();
 
 195   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 196     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
 
 197       "$ref->{description}";
 
 198     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
 
 199     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
 
 201     push @headingaccounts, $ref->{accno};
 
 206   # filter for opening and closing bookings
 
 207   # if l_ob is selected l_cb is always ignored
 
 208   if ( $last_period ) {
 
 209     # ob/cb-settings for "compared to" balance
 
 210     if ( $form->{l_ob_compared} ) {
 
 211       $where .= ' AND ac.ob_transaction is true  '
 
 212     } elsif ( not $form->{l_cb_compared} ) {
 
 213       $where .= ' AND ac.cb_transaction is false ';
 
 216     # ob/cb-settings for "as of" balance
 
 217     if ( $form->{l_ob} ) {
 
 218       $where .= ' AND ac.ob_transaction is true  '
 
 219     } elsif ( not $form->{l_cb} ) {
 
 220       $where .= ' AND ac.cb_transaction is false ';
 
 226     $fromdate = conv_dateq($fromdate);
 
 227     if ($form->{method} eq 'cash') {
 
 228       $subwhere .= " AND (transdate >= $fromdate)";
 
 229       $glwhere = " AND (ac.transdate >= $fromdate)";
 
 231       $where .= " AND (ac.transdate >= $fromdate)";
 
 236     $todate = conv_dateq($todate);
 
 237     $where    .= " AND (ac.transdate <= $todate)";
 
 238     $subwhere .= " AND (transdate <= $todate)";
 
 241   if ($department_id) {
 
 242     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
 245   if ($form->{project_id}) {
 
 246     # Diese Bedingung wird derzeit niemals wahr sein, da man in Bericht->Bilanz keine
 
 247     # Projekte auswählen kann
 
 248     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 251   if ($form->{method} eq 'cash') {
 
 253       qq|SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 255          JOIN chart c ON (c.id = ac.chart_id)
 
 256          JOIN ar a ON (a.id = ac.trans_id)
 
 264                WHERE (a.chart_link LIKE '%AR_paid%')
 
 268          GROUP BY c.accno, c.description, c.category
 
 272          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 274          JOIN chart c ON (c.id = ac.chart_id)
 
 275          JOIN ap a ON (a.id = ac.trans_id)
 
 283                WHERE (a.chart_link LIKE '%AP_paid%')
 
 287          GROUP BY c.accno, c.description, c.category
 
 291          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 293          JOIN chart c ON (c.id = ac.chart_id)
 
 294          JOIN gl a ON (a.id = ac.trans_id)
 
 299              AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 301          GROUP BY c.accno, c.description, c.category |;
 
 303     if ($form->{project_id}) {
 
 304       # s.o. keine Projektauswahl in Bilanz
 
 309          SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 311          JOIN ar a ON (a.id = ac.trans_id)
 
 312          JOIN parts p ON (ac.parts_id = p.id)
 
 313          JOIN chart c on (p.income_accno_id = c.id)
 
 314          -- use transdate from subwhere
 
 315          WHERE (c.category = 'I')
 
 322                WHERE (a.chart_link LIKE '%AR_paid%')
 
 326          GROUP BY c.accno, c.description, c.category
 
 330          SELECT c.accno AS accno, SUM(ac.sellprice) AS amount, c.description AS description, c.category
 
 332          JOIN ap a ON (a.id = ac.trans_id)
 
 333          JOIN parts p ON (ac.parts_id = p.id)
 
 334          JOIN chart c on (p.expense_accno_id = c.id)
 
 335          WHERE (c.category = 'E')
 
 342                WHERE a.chart_link LIKE '%AP_paid%'
 
 346          GROUP BY c.accno, c.description, c.category |;
 
 349   } else {                      # if ($form->{method} eq 'cash')
 
 350     if ($department_id) {
 
 351       $dpt_where = qq| AND a.department_id = | . conv_i($department_id);
 
 352       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 353                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 354                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 358       SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 360       JOIN chart c ON (c.id = ac.chart_id)
 
 362         $dpt_where_without_arapgl
 
 365       GROUP BY c.accno, c.description, c.category |;
 
 367     if ($form->{project_id}) {
 
 368       # s.o. keine Projektauswahl in Bilanz
 
 372       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 374       JOIN ar a ON (a.id = ac.trans_id)
 
 375       JOIN parts p ON (ac.parts_id = p.id)
 
 376       JOIN chart c on (p.income_accno_id = c.id)
 
 377       -- use transdate from subwhere
 
 378       WHERE (c.category = 'I')
 
 382       GROUP BY c.accno, c.description, c.category
 
 386       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount, c.description AS description, c.category
 
 388       JOIN ap a ON (a.id = ac.trans_id)
 
 389       JOIN parts p ON (ac.parts_id = p.id)
 
 390       JOIN chart c on (p.expense_accno_id = c.id)
 
 391       WHERE (c.category = 'E')
 
 395       GROUP BY c.accno, c.description, c.category |;
 
 403   $sth = prepare_execute_query($form, $dbh, $query);
 
 405   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 407     if ($ref->{category} eq 'C') {
 
 408       $ref->{category} = 'A';
 
 411     # get last heading account
 
 412     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
 416         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
 
 418         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
 
 422     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
 
 423     $form->{ $ref->{category} }{ $ref->{accno} }{description} = $ref->{description};
 
 424     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
 
 427       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
 
 429       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
 
 434   # remove accounts with zero balance
 
 435   foreach $category (@{$categories}) {
 
 436     foreach $accno (keys %{ $form->{$category} }) {
 
 437       $form->{$category}{$accno}{last} = $form->round_amount($form->{$category}{$accno}{last}, $dec);
 
 438       $form->{$category}{$accno}{this} = $form->round_amount($form->{$category}{$accno}{this}, $dec);
 
 440       delete $form->{$category}{$accno}
 
 441         if (   $form->{$category}{$accno}{this} == 0
 
 442             && $form->{$category}{$accno}{last} == 0);
 
 446   $main::lxdebug->leave_sub();
 
 450   $main::lxdebug->enter_sub();
 
 452   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
 
 454   my ($null, $department_id) = split /--/, $form->{department};
 
 458   my $dpt_where_without_arapgl;
 
 467   $where .= ' AND ac.cb_transaction is false ' unless $form->{l_cb};
 
 470     $fromdate = conv_dateq($fromdate);
 
 471     if ($form->{method} eq 'cash') {
 
 472       $subwhere .= " AND (transdate    >= $fromdate)";
 
 473       $glwhere   = " AND (ac.transdate >= $fromdate)";
 
 474       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 475       $inwhere   = " AND (acc.transdate >= $fromdate)";
 
 477       $where    .= " AND (ac.transdate >= $fromdate)";
 
 478       # hotfix for projectfilter in guv and bwa
 
 479       # fromdate is otherwise ignored if project is selected
 
 480       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 485     $todate = conv_dateq($todate);
 
 486     $subwhere   .= " AND (transdate    <= $todate)";
 
 487     $where      .= " AND (ac.transdate <= $todate)";
 
 488     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 489     $inwhere    .= " AND (acc.transdate <= $todate)";
 
 492   if ($department_id) {
 
 493     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 496   if ($form->{project_id}) {
 
 497     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
 
 501 # GUV patch by Ronny Rentner (Bug 1190)
 
 503 # GUV IST-Versteuerung
 
 505 # Alle tatsaechlichen _Zahlungseingaenge_
 
 506 # im Zeitraum erfassen
 
 507 # (Teilzahlungen werden prozentual auf verschiedene Steuern aufgeteilt)
 
 511   if ($form->{method} eq 'cash') {
 
 514        SELECT SUM( ac.amount * CASE WHEN COALESCE((SELECT amount FROM ar a WHERE id = ac.trans_id $dpt_where), 0) != 0 THEN
 
 515             /* ar amount is not zero, so we can divide by amount   */
 
 516                     (SELECT SUM(acc.amount) * -1
 
 519                      AND acc.trans_id = ac.trans_id
 
 520                      AND acc.chart_link LIKE '%AR_paid%')
 
 521                   / (SELECT amount FROM ar WHERE id = ac.trans_id)
 
 523             /* ar amount is zero, or we are checking with a non-ar-transaction, so we return 0 in both cases as multiplicator of ac.amount */
 
 525                 ) AS amount, c.$category
 
 527        LEFT JOIN chart c ON (c.id  = ac.chart_id)
 
 528        LEFT JOIN ar      ON (ar.id = ac.trans_id)
 
 529       WHERE ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE 1=1 $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 ar a ON (a.id = ac.trans_id)
 
 538          WHERE $where $dpt_where
 
 539            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 545          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 547          JOIN chart c ON (c.id = ac.chart_id)
 
 548          JOIN ap a ON (a.id = ac.trans_id)
 
 549          WHERE $where $dpt_where
 
 550            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 556          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 558          JOIN chart c ON (c.id = ac.chart_id)
 
 559          JOIN gl a ON (a.id = ac.trans_id)
 
 560          WHERE $where $dpt_where $glwhere
 
 561            AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 566     if ($form->{project_id}) {
 
 570          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 572          JOIN ar a ON (a.id = ac.trans_id)
 
 573          JOIN parts p ON (ac.parts_id = p.id)
 
 574          JOIN chart c on (p.income_accno_id = c.id)
 
 575          WHERE (c.category = 'I') $prwhere $dpt_where
 
 576            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 582          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 584          JOIN ap a ON (a.id = ac.trans_id)
 
 585          JOIN parts p ON (ac.parts_id = p.id)
 
 586          JOIN chart c on (p.expense_accno_id = c.id)
 
 587          WHERE (c.category = 'E') $prwhere $dpt_where
 
 588            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 594   } else {                      # if ($form->{method} eq 'cash')
 
 595     if ($department_id) {
 
 596       $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 597       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 598                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 599                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 603         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 605         JOIN chart c ON (c.id = ac.chart_id)
 
 607           $dpt_where_without_arapgl
 
 609         GROUP BY c.$category |;
 
 611     if ($form->{project_id}) {
 
 615         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 617         JOIN ar a ON (a.id = ac.trans_id)
 
 618         JOIN parts p ON (ac.parts_id = p.id)
 
 619         JOIN chart c on (p.income_accno_id = c.id)
 
 620         WHERE (c.category = 'I')
 
 628         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 630         JOIN ap a ON (a.id = ac.trans_id)
 
 631         JOIN parts p ON (ac.parts_id = p.id)
 
 632         JOIN chart c on (p.expense_accno_id = c.id)
 
 633         WHERE (c.category = 'E')
 
 637         GROUP BY c.$category |;
 
 645   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
 
 646     if ($category eq "pos_bwa") {
 
 648         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 650         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 653       $form->{ $ref->{$category} } += $ref->{amount};
 
 657   $main::lxdebug->leave_sub();
 
 661   $main::lxdebug->enter_sub();
 
 663   my ($self, $myconfig, $form, %options) = @_;
 
 665   my $dbh = SL::DB->client->dbh;
 
 667   my ($query, $sth, $ref);
 
 670   my ($null, $department_id) = split /--/, $form->{department};
 
 671   my @headingaccounts = ();
 
 673   my $dpt_where_without_arapgl;
 
 674   my ($customer_where, $customer_join, $customer_no_union);
 
 678   my $invwhere = $where;
 
 680   if ($department_id) {
 
 681     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 682     $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 683                                                  (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 684                                                  (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 686   if ($form->{customer_id}) {
 
 687     $customer_join     = qq| JOIN ar a ON (ac.trans_id = a.id) |;
 
 688     $customer_where    = qq| AND (a.customer_id = | . conv_i($form->{customer_id}, 'NULL') . qq|) |;
 
 689     $customer_no_union = qq| AND 1=0 |;
 
 692   # project_id only applies to getting transactions
 
 693   # it has nothing to do with a trial balance
 
 694   # but we use the same function to collect information
 
 696   if ($form->{project_id}) {
 
 697     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 700   my $acc_cash_where = "";
 
 701 #  my $ar_cash_where = "";
 
 702 #  my $ap_cash_where = "";
 
 705   if ($form->{method} eq "cash") {
 
 707       qq| AND (ac.trans_id IN (
 
 710             WHERE datepaid >= '$form->{fromdate}'
 
 711               AND datepaid <= '$form->{todate}'
 
 717             WHERE datepaid >= '$form->{fromdate}'
 
 718               AND datepaid <= '$form->{todate}'
 
 724             WHERE transdate >= '$form->{fromdate}'
 
 725               AND transdate <= '$form->{todate}'
 
 727 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 730   if ($options{beginning_balances}) {
 
 731     foreach my $prefix (qw(from to)) {
 
 732       next if ($form->{"${prefix}date"});
 
 734       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 735       $query      = qq|SELECT ${min_max}(transdate)
 
 739                          $dpt_where_without_arapgl
 
 743       ($form->{"${prefix}date"}) = selectfirst_array_query($form, $dbh, $query);
 
 746     # get beginning balances
 
 748       qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
 
 750           LEFT JOIN chart c ON (ac.chart_id = c.id)
 
 752           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 753             $dpt_where_without_arapgl
 
 756           GROUP BY c.accno, c.category, c.description |;
 
 758     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 760     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 762       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 763         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 764         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 765         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 767         if ($ref->{amount} > 0) {
 
 768           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 770           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 772         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 781     qq|SELECT c.accno, c.description, c.category
 
 783        WHERE c.charttype = 'H'
 
 786   $sth = prepare_execute_query($form, $dbh, $query);
 
 788   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 789     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 790     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 791     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 793     push @headingaccounts, $ref->{accno};
 
 799   my $saldowhere    = " 1 = 1 ";
 
 800   my $sumwhere      = " 1 = 1 ";
 
 802   my $sumsubwhere   = '';
 
 803   my $saldosubwhere = '';
 
 804   my $glsaldowhere  = '';
 
 809   my ($fromdate, $todate, $fetch_accounts_before_from);
 
 811   if ($form->{fromdate} || $form->{todate}) {
 
 812     if ($form->{fromdate}) {
 
 813       $fromdate = conv_dateq($form->{fromdate});
 
 814       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 815       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 816       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 817       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 818       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 819       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 820       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 821       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 823     if ($form->{todate}) {
 
 824       $todate = conv_dateq($form->{todate});
 
 825       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 826       $invwhere      .= " AND (a.transdate <= $todate)";
 
 827       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 828       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 829       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 830       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 831       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 832       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 836   if ($form->{method} eq "cash") {
 
 838       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) |;
 
 839     $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) |;
 
 841     $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) |;
 
 843     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 844     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 845     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 847     # get all entries before fromdate, which are not yet fetched
 
 848     # TODO dpt_where_without_arapgl and project - project calculation seems bogus anyway
 
 849     # TODO use fiscal_year_startdate for the whole trial balance
 
 850     #      anyway, if the last booking is in a deviating fiscal year, this already improves the query
 
 851     my $fiscal_year_startdate = conv_dateq($self->get_balance_starting_date($form->{fromdate}));
 
 852     $fetch_accounts_before_from = qq|SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 853                        FROM acc_trans ac JOIN chart c ON (c.id = ac.chart_id) WHERE 1 = 1 AND (ac.transdate <= $fromdate)
 
 854                        AND (ac.transdate >= $fiscal_year_startdate)
 
 855                        AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)
 
 856                        AND c.accno NOT IN (SELECT c.accno FROM acc_trans ac JOIN chart c ON (c.id = ac.chart_id) WHERE 1 = 1 AND (ac.transdate >= $fromdate) AND (ac.transdate <= $todate)
 
 857                        AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL))
 
 858                        GROUP BY c.accno, c.description, c.category ORDER BY accno|;
 
 862        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 864        JOIN chart c ON (c.id = ac.chart_id)
 
 867          $dpt_where_without_arapgl
 
 869        GROUP BY c.accno, c.description, c.category |;
 
 871   if ($form->{project_id}) {
 
 873       -- add project transactions from invoice
 
 877       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 879       JOIN ar a ON (ac.trans_id = a.id)
 
 880       JOIN parts p ON (ac.parts_id = p.id)
 
 881       JOIN chart c ON (p.income_accno_id = c.id)
 
 886       GROUP BY c.accno, c.description, c.category
 
 890       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 892       JOIN ap a ON (ac.trans_id = a.id)
 
 893       JOIN parts p ON (ac.parts_id = p.id)
 
 894       JOIN chart c ON (p.expense_accno_id = c.id)
 
 899       GROUP BY c.accno, c.description, c.category
 
 903   $query .= qq| ORDER BY accno|;
 
 905   $sth = prepare_execute_query($form, $dbh, $query);
 
 907   # calculate the debit and credit in the period
 
 908   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 909     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 910     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 911     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 912     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 916   if ($form->{method} ne "cash") {  # better eq 'accrual'
 
 917     $sth = prepare_execute_query($form, $dbh, $fetch_accounts_before_from);
 
 918     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 919       $trb{ $ref->{accno} }{description} = $ref->{description};
 
 920       $trb{ $ref->{accno} }{charttype}   = 'A';
 
 921       $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 922       $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 927   # prepare query for each account
 
 928   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 932          (SELECT SUM(ac.amount) * -1
 
 934           JOIN chart c ON (c.id = ac.chart_id)
 
 937             $dpt_where_without_arapgl
 
 941           AND (c.accno = ?)) AS debit,
 
 943          (SELECT SUM(ac.amount)
 
 945           JOIN chart c ON (c.id = ac.chart_id)
 
 948             $dpt_where_without_arapgl
 
 952           AND c.accno = ?) AS credit,
 
 953         (SELECT SUM(ac.amount)
 
 955          JOIN chart c ON (ac.chart_id = c.id)
 
 958            $dpt_where_without_arapgl
 
 961          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 963         (SELECT SUM(ac.amount)
 
 965          JOIN chart c ON (ac.chart_id = c.id)
 
 968            $dpt_where_without_arapgl
 
 972          AND c.accno = ?) AS sum_credit,
 
 974         (SELECT SUM(ac.amount)
 
 976          JOIN chart c ON (ac.chart_id = c.id)
 
 979            $dpt_where_without_arapgl
 
 983          AND c.accno = ?) AS sum_debit,
 
 985         (SELECT max(ac.transdate) FROM acc_trans ac
 
 986         JOIN chart c ON (ac.chart_id = c.id)
 
 989           $dpt_where_without_arapgl
 
 992         AND c.accno = ?) AS last_transaction
 
 997   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 999   if ($form->{project_id}) {
 
1000     # prepare query for each account
 
1003           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
1005            JOIN parts p ON (ac.parts_id = p.id)
 
1006            JOIN ap a ON (ac.trans_id = a.id)
 
1007            JOIN chart c ON (p.expense_accno_id = c.id)
 
1012            AND c.accno = ?) AS debit,
 
1014           (SELECT SUM(ac.sellprice * ac.qty)
 
1016            JOIN parts p ON (ac.parts_id = p.id)
 
1017            JOIN ar a ON (ac.trans_id = a.id)
 
1018            JOIN chart c ON (p.income_accno_id = c.id)
 
1023            AND c.accno = ?) AS credit,
 
1025         (SELECT SUM(ac.amount)
 
1027          JOIN chart c ON (ac.chart_id = c.id)
 
1030            $dpt_where_without_arapgl
 
1034          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
1036         (SELECT SUM(ac.amount)
 
1038          JOIN chart c ON (ac.chart_id = c.id)
 
1041            $dpt_where_without_arapgl
 
1046          AND c.accno = ?) AS sum_credit,
 
1048         (SELECT SUM(ac.amount)
 
1050          JOIN chart c ON (ac.chart_id = c.id)
 
1054            $dpt_where_without_arapgl
 
1058          AND c.accno = ?) AS sum_debit,
 
1061         (SELECT max(ac.transdate) FROM acc_trans ac
 
1062         JOIN chart c ON (ac.chart_id = c.id)
 
1065           $dpt_where_without_arapgl
 
1068         AND c.accno = ?) AS last_transaction
 
1071     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
1075   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
1077   foreach my $accno (sort keys %trb) {
 
1080     $ref->{accno} = $accno;
 
1081     map { $ref->{$_} = $trb{$accno}{$_} }
 
1082       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
1084     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
1086     if ($trb{$accno}{charttype} eq 'A') {
 
1089       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1091       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
1092       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
1093       $last_transaction = "";
 
1094       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
1095         $ref->{debit}  += $debit;
 
1096         $ref->{credit} += $credit;
 
1098           $ref->{haben_saldo} += $saldo;
 
1100           $ref->{soll_saldo} += $saldo * -1;
 
1102         $ref->{last_transaction} = $last_transaction;
 
1103         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1104         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1108       if ($form->{project_id}) {
 
1111         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1113         ($debit, $credit) = (0, 0);
 
1114         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1115           $ref->{debit}  += $debit;
 
1116           $ref->{credit} += $credit;
 
1118             $ref->{haben_saldo} += $saldo;
 
1120             $ref->{soll_saldo} += $saldo * -1;
 
1122           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1123           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1125         $project_drcr->finish;
 
1128       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1129       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1131       if ($ref->{haben_saldo} != 0) {
 
1132         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1133         if ($ref->{haben_saldo} < 0) {
 
1134           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1135           $ref->{haben_saldo} = 0;
 
1138         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1139         if ($ref->{soll_saldo} < 0) {
 
1140           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1141           $ref->{soll_saldo} = 0;
 
1144       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1145       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1146       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1147       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1152     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1153     $accno = pop @accno;
 
1155       $trb{$accno}{debit}  += $ref->{debit};
 
1156       $trb{$accno}{credit} += $ref->{credit};
 
1157       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1158       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1159       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1160       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1163     push @{ $form->{TB} }, $ref;
 
1167   # debits and credits for headings
 
1168   foreach my $accno (@headingaccounts) {
 
1169     foreach $ref (@{ $form->{TB} }) {
 
1170       if ($accno eq $ref->{accno}) {
 
1171         $ref->{debit}           = $trb{$accno}{debit};
 
1172         $ref->{credit}          = $trb{$accno}{credit};
 
1173         $ref->{soll_saldo}      = $trb{$accno}{soll_saldo};
 
1174         $ref->{haben_saldo}     = $trb{$accno}{haben_saldo};
 
1175         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
 
1176         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};
 
1181   $main::lxdebug->leave_sub();
 
1185   $main::lxdebug->enter_sub();
 
1186   my ($self, $dbh, $form) = @_;
 
1187   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
 
1188   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
 
1189   my $sth =  $dbh->prepare($query);
 
1190   while(my $ref = $sth->fetchrow_hashref()) {
 
1191     $ref->{invnumer} =~ s/Storno zu //g;
 
1192     $form->{storno}{$ref->{invnumber}} = 1;
 
1194   $main::lxdebug->leave_sub();
 
1198   $main::lxdebug->enter_sub();
 
1200   my ($self, $myconfig, $form) = @_;
 
1202   # connect to database
 
1203   my $dbh     = SL::DB->client->dbh;
 
1205   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
 
1207   # falls customer ziehen wir die offene forderungsliste
 
1208   # anderfalls für die lieferanten die offenen verbindlichkeitne
 
1209   if ($form->{ct} eq "customer") {
 
1222   $ct_id = "${ct}_id";
 
1224   # erweiterung um einen freien zeitraum oder einen stichtag
 
1225   # mit entsprechender altersstrukturliste (s.a. Bug 1842)
 
1226   # eine neue variable an der oberfläche eingeführt, somit ist
 
1227   # todate == freier zeitrau und fordate == stichtag
 
1228   # duedate_where == nur fällige rechnungen anzeigen
 
1230   my ($review_of_aging_list, $todate, $fromdate, $fromwhere, $fordate,
 
1233   if ($form->{reporttype} eq 'custom') {  # altersstrukturliste, nur fällige
 
1235     # explizit rausschmeissen was man für diesen bericht nicht braucht
 
1236     delete $form->{fromdate};
 
1237     delete $form->{todate};
 
1239     # an der oberfläche ist das tagesaktuelle datum vorausgewählt
 
1240     # falls es dennoch per Benutzereingabe gelöscht wird, lieber wieder vorbelegen
 
1241     # ferner muss für die spätere DB-Abfrage muss todate gesetzt sein.
 
1242     $form->{fordate}  = $form->current_date($myconfig) unless ($form->{fordate});
 
1243     $fordate          = conv_dateq($form->{fordate});
 
1246     if ($form->{review_of_aging_list}) { # falls die liste leer ist, alles anzeigen
 
1247       if ($form->{review_of_aging_list} =~ m "-") {             # ..  periode von bis
 
1248         my @period = split(/-/, $form->{review_of_aging_list}); # ... von periode bis periode
 
1249         $review_of_aging_list = " AND $period[0] <  (date $fordate) - duedate
 
1250                                   AND (date $fordate) - duedate  < $period[1]";
 
1252         $form->{review_of_aging_list} =~ s/[^0-9]//g;   # größer 120 das substitute ist nur für das '>' zeichen
 
1253         $review_of_aging_list = " AND $form->{review_of_aging_list} < (date $fordate) - duedate";
 
1256     $duedate_where = " AND (date $fordate) - duedate >= 0 ";
 
1257   } else {  # freier zeitraum, nur rechnungsdatum und OHNE review_of_aging_list
 
1258     $form->{todate}  = $form->current_date($myconfig) unless ($form->{todate});
 
1259     $todate = conv_dateq($form->{todate});
 
1260     $fromdate = conv_dateq($form->{fromdate});
 
1261     $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
 
1263   my $where = " 1 = 1 ";
 
1266   if ($form->{$ct_id}) {
 
1267     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
 
1268   } elsif ($form->{ $form->{ct} }) {
 
1269     $where .= qq| AND (ct.name ILIKE | . $dbh->quote(like($form->{$ct})) . qq|)|;
 
1274   if ($form->{department}) {
 
1275     my ($null, $department_id) = split /--/, $form->{department};
 
1276     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
 
1277     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1278     $where_dpt = qq| AND (${arap}.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1282     SELECT ${ct}.id AS ctid, ${ct}.name,
 
1283       street, zipcode, city, country, contact, email,
 
1284       phone as customerphone, fax as customerfax, ${ct}number,
 
1285       "invnumber", "transdate",
 
1286       (amount - COALESCE((SELECT sum(amount)*$ml FROM acc_trans WHERE chart_link ilike '%paid%' AND acc_trans.trans_id=${arap}.id AND acc_trans.transdate <= (date $todate)),0)) as "open", "amount",
 
1287       "duedate", invoice, ${arap}.id, date_part('days', now() - duedate) as overduedays,
 
1290        WHERE (${arap}.currency_id = exchangerate.currency_id)
 
1291          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
 
1293     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
 
1294       AND NOT COALESCE (${arap}.storno, 'f')
 
1295       AND (${arap}.${ct}_id = ${ct}.id)
 
1298       AND (transdate <= (date $todate) $fromwhere )
 
1299       $review_of_aging_list
 
1301     ORDER BY ctid, transdate, invnumber |;
 
1303   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1305   # select outstanding vendors or customers, depends on $ct
 
1307     qq|SELECT DISTINCT ct.id, ct.name
 
1308        FROM $ct ct, $arap a
 
1311          AND (a.${ct_id} = ct.id)
 
1312          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
 
1313          AND (a.transdate <= $todate $fromwhere)
 
1316   my $sth = prepare_execute_query($form, $dbh, $query);
 
1319   # for each company that has some stuff outstanding
 
1320   while (my ($id) = $sth->fetchrow_array) {
 
1321     do_statement($form, $sth_details, $q_details, $id);
 
1323     while (my $ref = $sth_details->fetchrow_hashref("NAME_lc")) {
 
1324       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
 
1325       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
 
1326       push @{ $form->{AG} }, $ref;
 
1329     $sth_details->finish;
 
1335   $main::lxdebug->leave_sub();
 
1339   $main::lxdebug->enter_sub();
 
1341   my ($self, $myconfig, $form) = @_;
 
1343   my $dbh = SL::DB->client->dbh;
 
1345   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1348     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1351   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1352     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1354   $main::lxdebug->leave_sub();
 
1358   $main::lxdebug->enter_sub();
 
1360   my ($self, $myconfig, $form) = @_;
 
1362   my $dbh = SL::DB->client->dbh;
 
1364   my ($null, $department_id) = split /--/, $form->{department};
 
1367   my $where = "1 = 1";
 
1369   if ($department_id) {
 
1370     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1375   if ($form->{accno}) {
 
1376     $accno = $form->{accno};
 
1377     $rate  = $form->{"$form->{accno}_rate"};
 
1378     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1384   if ($form->{db} eq 'ar') {
 
1385     $table = "customer";
 
1392   my $arap = lc($ARAP);
 
1394   my $transdate = "a.transdate";
 
1396   if ($form->{method} eq 'cash') {
 
1397     $transdate = "a.datepaid";
 
1399     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1406           WHERE (a.chart_link LIKE '%${ARAP}_paid%')
 
1407           AND (transdate <= $todate)
 
1412   # if there are any dates construct a where
 
1413   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1414   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1416   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1418   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1419   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1422       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1423           ac.amount * $ml AS tax
 
1425          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1426          JOIN chart ch ON (ch.id = ac.chart_id)
 
1427          JOIN $table n ON (n.id = a.${table}_id)
 
1431            AND (a.invoice = '0')
 
1435          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1436            i.sellprice * i.qty * $rate * $ml AS tax
 
1438          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1439          JOIN chart ch ON (ch.id = ac.chart_id)
 
1440          JOIN $table n ON (n.id = a.${table}_id)
 
1441          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1442          JOIN invoice i ON (i.trans_id = a.id)
 
1446            AND (a.invoice = '1')
 
1447          ORDER BY $sortorder|;
 
1449   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1451   $main::lxdebug->leave_sub();
 
1454 sub paymentaccounts {
 
1455   $main::lxdebug->enter_sub();
 
1457   my ($self, $myconfig, $form) = @_;
 
1459   # connect to database, turn AutoCommit off
 
1460   my $dbh = SL::DB->client->dbh;
 
1462   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1464   # get A(R|P)_paid accounts
 
1466     qq|SELECT accno, description
 
1468        WHERE link LIKE '%${ARAP}_paid%'|;
 
1469   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1471   $main::lxdebug->leave_sub();
 
1475   $main::lxdebug->enter_sub();
 
1477   my ($self, $myconfig, $form) = @_;
 
1479   # connect to database, turn AutoCommit off
 
1480   my $dbh = SL::DB->client->dbh;
 
1485   if ($form->{db} eq 'ar') {
 
1486     $table = 'customer';
 
1497   if ($form->{department_id}) {
 
1498     $where = qq| AND (a.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1501   if ($form->{fromdate}) {
 
1502     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1504   if ($form->{todate}) {
 
1505     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1507   if (!$form->{fx_transaction}) {
 
1508     $where .= " AND ac.fx_transaction = '0'";
 
1513   if ($form->{reference}) {
 
1514     $reference = $dbh->quote(like($form->{reference}));
 
1515     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1516     $reference = " AND (a.reference LIKE $reference)";
 
1518   if ($form->{source}) {
 
1519     $where .= " AND (ac.source ILIKE " . $dbh->quote(like($form->{source})) . ") ";
 
1521   if ($form->{memo}) {
 
1522     $where .= " AND (ac.memo ILIKE " . $dbh->quote(like($form->{memo})) . ") ";
 
1525   my %sort_columns =  (
 
1526     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1527     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1528     'name'         => [ qw(lower_name transdate)                 ],
 
1529     'source'       => [ qw(lower_source)                         ],
 
1530     'memo'         => [ qw(lower_memo)                           ],
 
1532   my %lowered_columns =  (
 
1533     'invnumber'       => { 'gl' => 'a.reference',   'arap' => 'a.invnumber', },
 
1534     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1535     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1536     'name'            => { 'gl' => 'a.description', 'arap' => 'c.name',      },
 
1539   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1540   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1541   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1544   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1545   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1546     next if ($spec !~ m/^lower_(.*)$/);
 
1549     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1552   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1553   $sth = prepare_query($form, $dbh, $query);
 
1556       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1557            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1558            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1559            $columns_for_sorting{arap}
 
1561          JOIN $arap a ON (ac.trans_id = a.id)
 
1562          JOIN $table c ON (c.id = a.${table}_id)
 
1563          WHERE (ac.chart_id = ?)
 
1569          SELECT a.description, a.reference, NULL AS ordnumber,
 
1570            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1571            '0' as invoice, a.id, ac.memo, 'gl' AS module
 
1572            $columns_for_sorting{gl}
 
1574          JOIN gl a ON (a.id = ac.trans_id)
 
1575          WHERE (ac.chart_id = ?)
 
1578            AND (ac.amount * $ml) > 0
 
1580          ORDER BY $sortorder|;
 
1581   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1585   # cycle through each id
 
1586   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1587     do_statement($form, $sth, $query, $accno);
 
1588     my $ref = $sth->fetchrow_hashref();
 
1589     push(@{ $form->{PR} }, $ref);
 
1592     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1594     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1595     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1596       push(@{ $form->{ $ref->{id} } }, $pr);
 
1598     $sth_details->finish();
 
1601   $main::lxdebug->leave_sub();
 
1605   $main::lxdebug->enter_sub();
 
1607   my ($self, $myconfig, $form) = @_;
 
1609   my $dbh = SL::DB->client->dbh;
 
1611   my $last_period = 0;
 
1614     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);
 
1616   $form->{decimalplaces} *= 1;
 
1618   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1620   # if there are any compare dates
 
1622   if ($form->{fromdate} || $form->{todate}) {
 
1624     if ($form->{fromdate}) {
 
1625       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1628       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1631     my $kummfromdate = $form->{comparefromdate};
 
1632     my $kummtodate   = $form->{comparetodate};
 
1633     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1636   my @periods        = qw(jetzt kumm);
 
1637   my @gesamtleistung = qw(1 3);
 
1638   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 20);
 
1640     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1642   foreach my $key (@periods) {
 
1643     $form->{ "$key" . "gesamtleistung" } = 0;
 
1644     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1646     foreach $category (@categories) {
 
1648       if (defined($form->{$category}{$key})) {
 
1649         $form->{"$key$category"} =
 
1650           $form->format_amount($myconfig,
 
1651                                $form->round_amount($form->{$category}{$key}, 2
 
1653                                $form->{decimalplaces},
 
1657     foreach my $item (@gesamtleistung) {
 
1658       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1660     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1662     foreach my $item (@gesamtkosten) {
 
1663       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1665     $form->{ "$key" . "rohertrag" } =
 
1666       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1667     $form->{ "$key" . "betriebrohertrag" } =
 
1668       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1669     $form->{ "$key" . "betriebsergebnis" } =
 
1670       $form->{ "$key" . "betriebrohertrag" } -
 
1671       $form->{ "$key" . "gesamtkosten" };
 
1672     $form->{ "$key" . "neutraleraufwand" } =
 
1673       $form->{19}{$key} + $form->{30}{$key} + $form->{31}{$key};
 
1674     $form->{ "$key" . "neutralerertrag" } =
 
1675       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1676     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1677       $form->{ "$key" . "betriebsergebnis" } -
 
1678       $form->{ "$key" . "neutraleraufwand" } +
 
1679       $form->{ "$key" . "neutralerertrag" };
 
1680     $form->{ "$key" . "ergebnis" } =
 
1681       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1683     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1684       foreach $category (@categories) {
 
1685         if (defined($form->{$category}{$key})) {
 
1686           $form->{ "$key" . "gl" . "$category" } =
 
1687             $form->format_amount(
 
1689                                $form->round_amount(
 
1690                                  ($form->{$category}{$key} /
 
1691                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1693                                  $form->{decimalplaces}
 
1695                                $form->{decimalplaces},
 
1699       foreach my $item (@ergebnisse) {
 
1700         $form->{ "$key" . "gl" . "$item" } =
 
1701           $form->format_amount($myconfig,
 
1702                                $form->round_amount(
 
1703                                  ( $form->{ "$key" . "$item" } /
 
1704                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1706                                  $form->{decimalplaces}
 
1708                                $form->{decimalplaces},
 
1713     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1714       foreach $category (@categories) {
 
1715         if (defined($form->{$category}{$key})) {
 
1716           $form->{ "$key" . "gk" . "$category" } =
 
1717             $form->format_amount($myconfig,
 
1718                                  $form->round_amount(
 
1719                                    ($form->{$category}{$key} /
 
1720                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1722                                    $form->{decimalplaces}
 
1724                                  $form->{decimalplaces},
 
1728       foreach my $item (@ergebnisse) {
 
1729         $form->{ "$key" . "gk" . "$item" } =
 
1730           $form->format_amount($myconfig,
 
1731                                $form->round_amount(
 
1732                                    ($form->{ "$key" . "$item" } /
 
1733                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1735                                    $form->{decimalplaces}
 
1737                                $form->{decimalplaces},
 
1742     if ($form->{10}{$key} > 0) {
 
1743       foreach $category (@categories) {
 
1744         if (defined($form->{$category}{$key})) {
 
1745           $form->{ "$key" . "pk" . "$category" } =
 
1746             $form->format_amount(
 
1748                         $form->round_amount(
 
1749                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1750                           $form->{decimalplaces}
 
1752                         $form->{decimalplaces},
 
1756       foreach my $item (@ergebnisse) {
 
1757         $form->{ "$key" . "pk" . "$item" } =
 
1758           $form->format_amount($myconfig,
 
1759                                $form->round_amount(
 
1760                                                 ($form->{ "$key" . "$item" } /
 
1761                                                    $form->{10}{$key} * 100
 
1763                                                 $form->{decimalplaces}
 
1765                                $form->{decimalplaces},
 
1770     if ($form->{4}{$key} > 0) {
 
1771       foreach $category (@categories) {
 
1772         if (defined($form->{$category}{$key})) {
 
1773           $form->{ "$key" . "auf" . "$category" } =
 
1774             $form->format_amount(
 
1776                          $form->round_amount(
 
1777                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1778                            $form->{decimalplaces}
 
1780                          $form->{decimalplaces},
 
1784       foreach my $item (@ergebnisse) {
 
1785         $form->{ "$key" . "auf" . "$item" } =
 
1786           $form->format_amount($myconfig,
 
1787                                $form->round_amount(
 
1788                                                 ($form->{ "$key" . "$item" } /
 
1789                                                    $form->{4}{$key} * 100
 
1791                                                 $form->{decimalplaces}
 
1793                                $form->{decimalplaces},
 
1798     foreach my $item (@ergebnisse) {
 
1799       $form->{ "$key" . "$item" } =
 
1800         $form->format_amount($myconfig,
 
1801                              $form->round_amount($form->{ "$key" . "$item" },
 
1802                                                  $form->{decimalplaces}
 
1804                              $form->{decimalplaces},
 
1810   $main::lxdebug->leave_sub();
 
1813 sub income_statement {
 
1814   $main::lxdebug->enter_sub();
 
1816   my ($self, $myconfig, $form) = @_;
 
1818   # connect to database
 
1819   my $dbh = $form->dbconnect($myconfig);
 
1821   my $last_period          = 0;
 
1822   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1823   my @categories_ausgaben  =
 
1824     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);
 
1826   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1828   $form->{decimalplaces} *= 1;
 
1832   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1836   foreach my $item (@categories_einnahmen) {
 
1837     $form->{"eur${item}"} =
 
1838       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1839     $form->{"sumeura"} += $form->{$item};
 
1841   foreach my $item (@categories_ausgaben) {
 
1842     $form->{"eur${item}"} =
 
1843       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1844     $form->{"sumeurb"} += $form->{$item};
 
1847   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1849   foreach my $item (@ergebnisse) {
 
1851       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1853   $main::lxdebug->leave_sub();
 
1856 sub erfolgsrechnung {
 
1857   $main::lxdebug->enter_sub();
 
1859   my ($self, $myconfig, $form) = @_;
 
1860   $form->{company} = $::instance_conf->get_company;
 
1861   $form->{address} = $::instance_conf->get_address;
 
1862   $form->{fromdate} = DateTime->new(year => 2000, month => 1, day => 1)->to_kivitendo unless $form->{fromdate};
 
1863   $form->{todate} = $form->current_date(%{$myconfig}) unless $form->{todate};
 
1865   my %categories = (I => "ERTRAG", E => "AUFWAND");
 
1866   my $fromdate = conv_dateq($form->{fromdate});
 
1867   my $todate = conv_dateq($form->{todate});
 
1871   foreach my $category ('I', 'E') {
 
1873       name => $categories{$category},
 
1875       accounts => get_accounts_ch($category),
 
1877     foreach my $account (@{$category{accounts}}) {
 
1878       $account->{total} += ($account->{category} eq $category ? 1 : -1) * get_total_ch($account->{id}, $fromdate, $todate);
 
1879       $category{total} += $account->{total};
 
1880       $account->{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $account->{total}), 2);
 
1882     $form->{total} += $category{total};
 
1883     $category{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $category{total}), 2);
 
1884     push(@{$form->{categories}}, \%category);
 
1886   $form->{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $form->{total}), 2);
 
1888   $main::lxdebug->leave_sub();
 
1892 sub get_accounts_ch {
 
1893   $main::lxdebug->enter_sub();
 
1895   my ($category) = @_;
 
1898   if ($category eq 'I') {
 
1899     $inclusion = "AND pos_er = NULL OR pos_er = '1'";
 
1900   } elsif ($category eq 'E') {
 
1901     $inclusion = "AND pos_er = NULL OR pos_er = '6'";
 
1907     SELECT id, accno, description, category
 
1909     WHERE category = ? $inclusion
 
1912   my $accounts = _query($query, $category);
 
1914   $main::lxdebug->leave_sub();
 
1919   $main::lxdebug->enter_sub();
 
1921   my ($chart_id, $fromdate, $todate) = @_;
 
1930   $total += _query($query, $chart_id, $fromdate, $todate)->[0]->{sum};
 
1932   $main::lxdebug->leave_sub();
 
1936 sub _query {return selectall_hashref_query($::form, $::form->get_standard_dbh, @_);}