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 SL::DB::Helper::AccountingPeriod qw(get_balance_starting_date);
 
  40 use List::Util qw(sum);
 
  45 # new implementation of balance sheet
 
  48 # stuff missing from the original implementation:
 
  51 # - proper testing for heading charts
 
  52 # - transmission from $form to TMPL realm is not as clear as i'd like
 
  55   $main::lxdebug->enter_sub();
 
  59   my $myconfig = \%main::myconfig;
 
  60   my $form     = $main::form;
 
  61   my $dbh      = $::form->get_standard_dbh;
 
  64   my @categories  = qw(A C L Q);
 
  66   # if there are any dates construct a where
 
  67   if ($form->{asofdate}) {
 
  68     $form->{period} = $form->{this_period} = conv_dateq($form->{asofdate});
 
  71   # get starting date for calculating balance
 
  72   $form->{this_startdate} = $self->get_balance_starting_date($form->{asofdate});
 
  74   get_accounts($dbh, $last_period, $form->{this_startdate}, $form->{asofdate}, $form, \@categories);
 
  76   # if there are any compare dates
 
  77   if ($form->{compareasofdate}) {
 
  80     $form->{last_startdate} = $self->get_balance_starting_date($form->{compareasofdate});
 
  82     get_accounts($dbh, $last_period, $form->{last_startdate} , $form->{compareasofdate}, $form, \@categories);
 
  83     $form->{last_period} = conv_dateq($form->{compareasofdate});
 
  86   # now we got $form->{A}{accno}{ }    assets
 
  87   # and $form->{L}{accno}{ }           liabilities
 
  88   # and $form->{Q}{accno}{ }           equity
 
  89   # build asset accounts
 
  91   my %account = ('A' => { 'ml'     => -1 },
 
  93                  'Q' => { 'ml'     =>  1 });
 
  97   foreach my $category (grep { !/C/ } @categories) {
 
  99     $TMPL_DATA->{$category} = [];
 
 100     my $ml  = $account{$category}{ml};
 
 102     foreach my $key (sort keys %{ $form->{$category} }) {
 
 104       my $row = { %{ $form->{$category}{$key} } };
 
 106       # if charttype "heading" - calculate this entry, start a new batch of charts belonging to this heading and skip the rest bo the loop
 
 107       # header charts are not real charts. start a sub aggregation with them, but don't calculate anything with them
 
 108       if ($row->{charttype} eq "H") {
 
 109         if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 110           $row->{subdescription} = $account{$category}{subdescription};
 
 111           $row->{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 112           $row->{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 115         $row->{subheader} = 1;
 
 116         $account{$category}{subthis}        = $row->{this};
 
 117         $account{$category}{sublast}        = $row->{last};
 
 118         $account{$category}{subdescription} = $row->{description};
 
 119         $account{$category}{subtotal} = 1;
 
 124         next unless $form->{l_heading};
 
 127       for my $period (qw(this last)) {
 
 128         next if ($period eq 'last' && !$last_period);
 
 130         $row->{$period}                    *= $ml;
 
 133       push @{ $TMPL_DATA->{$category} }, $row;
 
 136     # resolve heading/subtotal
 
 137     if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 138       $TMPL_DATA->{$category}[-1]{subdescription} = $account{$category}{subdescription};
 
 139       $TMPL_DATA->{$category}[-1]{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 140       $TMPL_DATA->{$category}[-1]{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 143     $TMPL_DATA->{total}{$category}{this} = sum map { $_->{this} } @{ $TMPL_DATA->{$category} };
 
 144     $TMPL_DATA->{total}{$category}{last} = sum map { $_->{last} } @{ $TMPL_DATA->{$category} };
 
 147   for my $period (qw(this last)) {
 
 148     next if ($period eq 'last' && !$last_period);
 
 150     $form->{E}{$period}             = $TMPL_DATA->{total}{A}{$period} - $TMPL_DATA->{total}{L}{$period} - $TMPL_DATA->{total}{Q}{$period};
 
 151     $TMPL_DATA->{total}{Q}{$period}     += $form->{E}{$period};
 
 152     $TMPL_DATA->{total}{$period}    = $TMPL_DATA->{total}{L}{$period} + $TMPL_DATA->{total}{Q}{$period};
 
 154     $form->{E}{description}='nicht verbuchter Gewinn/Verlust';
 
 155   push @{ $TMPL_DATA->{Q} }, $form->{E};
 
 157   $main::lxdebug->leave_sub();
 
 163   $main::lxdebug->enter_sub();
 
 165   my ($dbh, $last_period, $fromdate, $todate, $form, $categories) = @_;
 
 167   my ($null, $department_id) = split /--/, $form->{department};
 
 171   my $dpt_where_without_arapgl = '';
 
 178   my $dec = $form->{decimalplaces};
 
 180   my $category = qq| AND (| . join(" OR ", map({ "(c.category = " . $dbh->quote($_) . ")" } @{$categories})) . qq|) |;
 
 184     qq|SELECT c.accno, c.description, c.category
 
 186        WHERE (c.charttype = 'H')
 
 190   $sth = prepare_execute_query($form, $dbh, $query);
 
 192   my @headingaccounts = ();
 
 193   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 194     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
 
 195       "$ref->{description}";
 
 196     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
 
 197     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
 
 199     push @headingaccounts, $ref->{accno};
 
 204   # filter for opening and closing bookings
 
 205   # if l_ob is selected l_cb is always ignored
 
 206   if ( $last_period ) {
 
 207     # ob/cb-settings for "compared to" balance
 
 208     if ( $form->{l_ob_compared} ) {
 
 209       $where .= ' AND ac.ob_transaction is true  '
 
 210     } elsif ( not $form->{l_cb_compared} ) {
 
 211       $where .= ' AND ac.cb_transaction is false ';
 
 214     # ob/cb-settings for "as of" balance
 
 215     if ( $form->{l_ob} ) {
 
 216       $where .= ' AND ac.ob_transaction is true  '
 
 217     } elsif ( not $form->{l_cb} ) {
 
 218       $where .= ' AND ac.cb_transaction is false ';
 
 224     $fromdate = conv_dateq($fromdate);
 
 225     if ($form->{method} eq 'cash') {
 
 226       $subwhere .= " AND (transdate >= $fromdate)";
 
 227       $glwhere = " AND (ac.transdate >= $fromdate)";
 
 229       $where .= " AND (ac.transdate >= $fromdate)";
 
 234     $todate = conv_dateq($todate);
 
 235     $where    .= " AND (ac.transdate <= $todate)";
 
 236     $subwhere .= " AND (transdate <= $todate)";
 
 239   if ($department_id) {
 
 240     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
 243   if ($form->{project_id}) {
 
 244     # Diese Bedingung wird derzeit niemals wahr sein, da man in Bericht->Bilanz keine
 
 245     # Projekte auswählen kann
 
 246     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 249   if ($form->{method} eq 'cash') {
 
 251       qq|SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 253          JOIN chart c ON (c.id = ac.chart_id)
 
 254          JOIN ar a ON (a.id = ac.trans_id)
 
 262                WHERE (a.chart_link LIKE '%AR_paid%')
 
 266          GROUP BY c.accno, c.description, c.category
 
 270          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 272          JOIN chart c ON (c.id = ac.chart_id)
 
 273          JOIN ap a ON (a.id = ac.trans_id)
 
 281                WHERE (a.chart_link LIKE '%AP_paid%')
 
 285          GROUP BY c.accno, c.description, c.category
 
 289          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 291          JOIN chart c ON (c.id = ac.chart_id)
 
 292          JOIN gl a ON (a.id = ac.trans_id)
 
 297              AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 299          GROUP BY c.accno, c.description, c.category |;
 
 301     if ($form->{project_id}) {
 
 302       # s.o. keine Projektauswahl in Bilanz
 
 307          SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 309          JOIN ar a ON (a.id = ac.trans_id)
 
 310          JOIN parts p ON (ac.parts_id = p.id)
 
 311          JOIN chart c on (p.income_accno_id = c.id)
 
 312          -- use transdate from subwhere
 
 313          WHERE (c.category = 'I')
 
 320                WHERE (a.chart_link LIKE '%AR_paid%')
 
 324          GROUP BY c.accno, c.description, c.category
 
 328          SELECT c.accno AS accno, SUM(ac.sellprice) AS amount, c.description AS description, c.category
 
 330          JOIN ap a ON (a.id = ac.trans_id)
 
 331          JOIN parts p ON (ac.parts_id = p.id)
 
 332          JOIN chart c on (p.expense_accno_id = c.id)
 
 333          WHERE (c.category = 'E')
 
 340                WHERE a.chart_link LIKE '%AP_paid%'
 
 344          GROUP BY c.accno, c.description, c.category |;
 
 347   } else {                      # if ($form->{method} eq 'cash')
 
 348     if ($department_id) {
 
 349       $dpt_where = qq| AND a.department_id = | . conv_i($department_id);
 
 350       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 351                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 352                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 356       SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 358       JOIN chart c ON (c.id = ac.chart_id)
 
 360         $dpt_where_without_arapgl
 
 363       GROUP BY c.accno, c.description, c.category |;
 
 365     if ($form->{project_id}) {
 
 366       # s.o. keine Projektauswahl in Bilanz
 
 370       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 372       JOIN ar a ON (a.id = ac.trans_id)
 
 373       JOIN parts p ON (ac.parts_id = p.id)
 
 374       JOIN chart c on (p.income_accno_id = c.id)
 
 375       -- use transdate from subwhere
 
 376       WHERE (c.category = 'I')
 
 380       GROUP BY c.accno, c.description, c.category
 
 384       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount, c.description AS description, c.category
 
 386       JOIN ap a ON (a.id = ac.trans_id)
 
 387       JOIN parts p ON (ac.parts_id = p.id)
 
 388       JOIN chart c on (p.expense_accno_id = c.id)
 
 389       WHERE (c.category = 'E')
 
 393       GROUP BY c.accno, c.description, c.category |;
 
 401   $sth = prepare_execute_query($form, $dbh, $query);
 
 403   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 405     if ($ref->{category} eq 'C') {
 
 406       $ref->{category} = 'A';
 
 409     # get last heading account
 
 410     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
 414         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
 
 416         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
 
 420     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
 
 421     $form->{ $ref->{category} }{ $ref->{accno} }{description} = $ref->{description};
 
 422     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
 
 425       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
 
 427       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
 
 432   # remove accounts with zero balance
 
 433   foreach $category (@{$categories}) {
 
 434     foreach $accno (keys %{ $form->{$category} }) {
 
 435       $form->{$category}{$accno}{last} = $form->round_amount($form->{$category}{$accno}{last}, $dec);
 
 436       $form->{$category}{$accno}{this} = $form->round_amount($form->{$category}{$accno}{this}, $dec);
 
 438       delete $form->{$category}{$accno}
 
 439         if (   $form->{$category}{$accno}{this} == 0
 
 440             && $form->{$category}{$accno}{last} == 0);
 
 444   $main::lxdebug->leave_sub();
 
 448   $main::lxdebug->enter_sub();
 
 450   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
 
 452   my ($null, $department_id) = split /--/, $form->{department};
 
 456   my $dpt_where_without_arapgl;
 
 465   $where .= ' AND ac.cb_transaction is false ' unless $form->{l_cb};
 
 468     $fromdate = conv_dateq($fromdate);
 
 469     if ($form->{method} eq 'cash') {
 
 470       $subwhere .= " AND (transdate    >= $fromdate)";
 
 471       $glwhere   = " AND (ac.transdate >= $fromdate)";
 
 472       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 473       $inwhere   = " AND (acc.transdate >= $fromdate)";
 
 475       $where    .= " AND (ac.transdate >= $fromdate)";
 
 480     $todate = conv_dateq($todate);
 
 481     $subwhere   .= " AND (transdate    <= $todate)";
 
 482     $where      .= " AND (ac.transdate <= $todate)";
 
 483     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 484     $inwhere    .= " AND (acc.transdate <= $todate)";
 
 487   if ($department_id) {
 
 488     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 491   if ($form->{project_id}) {
 
 492     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
 
 496 # GUV patch by Ronny Rentner (Bug 1190)
 
 498 # GUV IST-Versteuerung
 
 500 # Alle tatsaechlichen _Zahlungseingaenge_
 
 501 # im Zeitraum erfassen
 
 502 # (Teilzahlungen werden prozentual auf verschiedene Steuern aufgeteilt)
 
 506   if ($form->{method} eq 'cash') {
 
 509        SELECT SUM( ac.amount * CASE WHEN COALESCE((SELECT amount FROM ar a WHERE id = ac.trans_id $dpt_where), 0) != 0 THEN
 
 510             /* ar amount is not zero, so we can divide by amount   */
 
 511                     (SELECT SUM(acc.amount) * -1
 
 514                      AND acc.trans_id = ac.trans_id
 
 515                      AND acc.chart_link LIKE '%AR_paid%')
 
 516                   / (SELECT amount FROM ar WHERE id = ac.trans_id)
 
 518             /* 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 */
 
 520                 ) AS amount, c.$category
 
 522        LEFT JOIN chart c ON (c.id  = ac.chart_id)
 
 523        LEFT JOIN ar      ON (ar.id = ac.trans_id)
 
 524       WHERE ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE 1=1 $subwhere)
 
 529        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 531          JOIN chart c ON (c.id = ac.chart_id)
 
 532          JOIN ar a ON (a.id = ac.trans_id)
 
 533          WHERE $where $dpt_where
 
 534            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 540          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 542          JOIN chart c ON (c.id = ac.chart_id)
 
 543          JOIN ap a ON (a.id = ac.trans_id)
 
 544          WHERE $where $dpt_where
 
 545            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 551          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 553          JOIN chart c ON (c.id = ac.chart_id)
 
 554          JOIN gl a ON (a.id = ac.trans_id)
 
 555          WHERE $where $dpt_where $glwhere
 
 556            AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 561     if ($form->{project_id}) {
 
 565          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 567          JOIN ar a ON (a.id = ac.trans_id)
 
 568          JOIN parts p ON (ac.parts_id = p.id)
 
 569          JOIN chart c on (p.income_accno_id = c.id)
 
 570          WHERE (c.category = 'I') $prwhere $dpt_where
 
 571            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 577          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 579          JOIN ap a ON (a.id = ac.trans_id)
 
 580          JOIN parts p ON (ac.parts_id = p.id)
 
 581          JOIN chart c on (p.expense_accno_id = c.id)
 
 582          WHERE (c.category = 'E') $prwhere $dpt_where
 
 583            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 589   } else {                      # if ($form->{method} eq 'cash')
 
 590     if ($department_id) {
 
 591       $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 592       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 593                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 594                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 598         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 600         JOIN chart c ON (c.id = ac.chart_id)
 
 602           $dpt_where_without_arapgl
 
 604         GROUP BY c.$category |;
 
 606     if ($form->{project_id}) {
 
 610         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 612         JOIN ar a ON (a.id = ac.trans_id)
 
 613         JOIN parts p ON (ac.parts_id = p.id)
 
 614         JOIN chart c on (p.income_accno_id = c.id)
 
 615         WHERE (c.category = 'I')
 
 623         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 625         JOIN ap a ON (a.id = ac.trans_id)
 
 626         JOIN parts p ON (ac.parts_id = p.id)
 
 627         JOIN chart c on (p.expense_accno_id = c.id)
 
 628         WHERE (c.category = 'E')
 
 632         GROUP BY c.$category |;
 
 640   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
 
 641     if ($category eq "pos_bwa") {
 
 643         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 645         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 648       $form->{ $ref->{$category} } += $ref->{amount};
 
 652   $main::lxdebug->leave_sub();
 
 656   $main::lxdebug->enter_sub();
 
 658   my ($self, $myconfig, $form, %options) = @_;
 
 660   my $dbh = $form->dbconnect($myconfig);
 
 662   my ($query, $sth, $ref);
 
 665   my ($null, $department_id) = split /--/, $form->{department};
 
 666   my @headingaccounts = ();
 
 668   my $dpt_where_without_arapgl;
 
 669   my ($customer_where, $customer_join, $customer_no_union);
 
 673   my $invwhere = $where;
 
 675   if ($department_id) {
 
 676     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 677     $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 678                                                  (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 679                                                  (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 681   if ($form->{customer_id}) {
 
 682     $customer_join     = qq| JOIN ar a ON (ac.trans_id = a.id) |;
 
 683     $customer_where    = qq| AND (a.customer_id = | . conv_i($form->{customer_id}, 'NULL') . qq|) |;
 
 684     $customer_no_union = qq| AND 1=0 |;
 
 687   # project_id only applies to getting transactions
 
 688   # it has nothing to do with a trial balance
 
 689   # but we use the same function to collect information
 
 691   if ($form->{project_id}) {
 
 692     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 695   my $acc_cash_where = "";
 
 696 #  my $ar_cash_where = "";
 
 697 #  my $ap_cash_where = "";
 
 700   if ($form->{method} eq "cash") {
 
 702       qq| AND (ac.trans_id IN (
 
 705             WHERE datepaid >= '$form->{fromdate}'
 
 706               AND datepaid <= '$form->{todate}'
 
 712             WHERE datepaid >= '$form->{fromdate}'
 
 713               AND datepaid <= '$form->{todate}'
 
 719             WHERE transdate >= '$form->{fromdate}'
 
 720               AND transdate <= '$form->{todate}'
 
 722 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 725   if ($options{beginning_balances}) {
 
 726     foreach my $prefix (qw(from to)) {
 
 727       next if ($form->{"${prefix}date"});
 
 729       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 730       $query      = qq|SELECT ${min_max}(transdate)
 
 734                          $dpt_where_without_arapgl
 
 738       ($form->{"${prefix}date"}) = selectfirst_array_query($form, $dbh, $query);
 
 741     # get beginning balances
 
 743       qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
 
 745           LEFT JOIN chart c ON (ac.chart_id = c.id)
 
 747           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 748             $dpt_where_without_arapgl
 
 751           GROUP BY c.accno, c.category, c.description |;
 
 753     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 755     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 757       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 758         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 759         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 760         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 762         if ($ref->{amount} > 0) {
 
 763           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 765           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 767         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 776     qq|SELECT c.accno, c.description, c.category
 
 778        WHERE c.charttype = 'H'
 
 781   $sth = prepare_execute_query($form, $dbh, $query);
 
 783   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 784     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 785     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 786     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 788     push @headingaccounts, $ref->{accno};
 
 794   my $saldowhere    = " 1 = 1 ";
 
 795   my $sumwhere      = " 1 = 1 ";
 
 797   my $sumsubwhere   = '';
 
 798   my $saldosubwhere = '';
 
 799   my $glsaldowhere  = '';
 
 804   my ($fromdate, $todate, $fetch_accounts_before_from);
 
 806   if ($form->{fromdate} || $form->{todate}) {
 
 807     if ($form->{fromdate}) {
 
 808       $fromdate = conv_dateq($form->{fromdate});
 
 809       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 810       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 811       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 812       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 813       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 814       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 815       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 816       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 818     if ($form->{todate}) {
 
 819       $todate = conv_dateq($form->{todate});
 
 820       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 821       $invwhere      .= " AND (a.transdate <= $todate)";
 
 822       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 823       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 824       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 825       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 826       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 827       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 831   if ($form->{method} eq "cash") {
 
 833       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) |;
 
 834     $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) |;
 
 836     $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) |;
 
 838     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 839     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 840     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 842     # get all entries before fromdate, which are not yet fetched
 
 843     # TODO dpt_where_without_arapgl and project - project calculation seems bogus anyway
 
 844     # TODO use fiscal_year_startdate for the whole trial balance
 
 845     #      anyway, if the last booking is in a deviating fiscal year, this already improves the query
 
 846     my $fiscal_year_startdate = conv_dateq($self->get_balance_starting_date($form->{fromdate}));
 
 847     $fetch_accounts_before_from = qq|SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 848                        FROM acc_trans ac JOIN chart c ON (c.id = ac.chart_id) WHERE 1 = 1 AND (ac.transdate <= $fromdate)
 
 849                        AND (ac.transdate >= $fiscal_year_startdate)
 
 850                        AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)
 
 851                        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)
 
 852                        AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL))
 
 853                        GROUP BY c.accno, c.description, c.category ORDER BY accno|;
 
 857        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 859        JOIN chart c ON (c.id = ac.chart_id)
 
 862          $dpt_where_without_arapgl
 
 864        GROUP BY c.accno, c.description, c.category |;
 
 866   if ($form->{project_id}) {
 
 868       -- add project transactions from invoice
 
 872       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 874       JOIN ar a ON (ac.trans_id = a.id)
 
 875       JOIN parts p ON (ac.parts_id = p.id)
 
 876       JOIN chart c ON (p.income_accno_id = c.id)
 
 881       GROUP BY c.accno, c.description, c.category
 
 885       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 887       JOIN ap a ON (ac.trans_id = a.id)
 
 888       JOIN parts p ON (ac.parts_id = p.id)
 
 889       JOIN chart c ON (p.expense_accno_id = c.id)
 
 894       GROUP BY c.accno, c.description, c.category
 
 898   $query .= qq| ORDER BY accno|;
 
 900   $sth = prepare_execute_query($form, $dbh, $query);
 
 902   # calculate the debit and credit in the period
 
 903   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 904     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 905     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 906     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 907     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 911   if ($form->{method} ne "cash") {  # better eq 'accrual'
 
 912     $sth = prepare_execute_query($form, $dbh, $fetch_accounts_before_from);
 
 913     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 914       $trb{ $ref->{accno} }{description} = $ref->{description};
 
 915       $trb{ $ref->{accno} }{charttype}   = 'A';
 
 916       $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 917       $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 922   # prepare query for each account
 
 923   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 927          (SELECT SUM(ac.amount) * -1
 
 929           JOIN chart c ON (c.id = ac.chart_id)
 
 932             $dpt_where_without_arapgl
 
 936           AND (c.accno = ?)) AS debit,
 
 938          (SELECT SUM(ac.amount)
 
 940           JOIN chart c ON (c.id = ac.chart_id)
 
 943             $dpt_where_without_arapgl
 
 947           AND c.accno = ?) AS credit,
 
 948         (SELECT SUM(ac.amount)
 
 950          JOIN chart c ON (ac.chart_id = c.id)
 
 953            $dpt_where_without_arapgl
 
 956          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 958         (SELECT SUM(ac.amount)
 
 960          JOIN chart c ON (ac.chart_id = c.id)
 
 963            $dpt_where_without_arapgl
 
 967          AND c.accno = ?) AS sum_credit,
 
 969         (SELECT SUM(ac.amount)
 
 971          JOIN chart c ON (ac.chart_id = c.id)
 
 974            $dpt_where_without_arapgl
 
 978          AND c.accno = ?) AS sum_debit,
 
 980         (SELECT max(ac.transdate) FROM acc_trans ac
 
 981         JOIN chart c ON (ac.chart_id = c.id)
 
 984           $dpt_where_without_arapgl
 
 987         AND c.accno = ?) AS last_transaction
 
 992   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 994   if ($form->{project_id}) {
 
 995     # prepare query for each account
 
 998           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
1000            JOIN parts p ON (ac.parts_id = p.id)
 
1001            JOIN ap a ON (ac.trans_id = a.id)
 
1002            JOIN chart c ON (p.expense_accno_id = c.id)
 
1007            AND c.accno = ?) AS debit,
 
1009           (SELECT SUM(ac.sellprice * ac.qty)
 
1011            JOIN parts p ON (ac.parts_id = p.id)
 
1012            JOIN ar a ON (ac.trans_id = a.id)
 
1013            JOIN chart c ON (p.income_accno_id = c.id)
 
1018            AND c.accno = ?) AS credit,
 
1020         (SELECT SUM(ac.amount)
 
1022          JOIN chart c ON (ac.chart_id = c.id)
 
1025            $dpt_where_without_arapgl
 
1029          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
1031         (SELECT SUM(ac.amount)
 
1033          JOIN chart c ON (ac.chart_id = c.id)
 
1036            $dpt_where_without_arapgl
 
1041          AND c.accno = ?) AS sum_credit,
 
1043         (SELECT SUM(ac.amount)
 
1045          JOIN chart c ON (ac.chart_id = c.id)
 
1049            $dpt_where_without_arapgl
 
1053          AND c.accno = ?) AS sum_debit,
 
1056         (SELECT max(ac.transdate) FROM acc_trans ac
 
1057         JOIN chart c ON (ac.chart_id = c.id)
 
1060           $dpt_where_without_arapgl
 
1063         AND c.accno = ?) AS last_transaction
 
1066     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
1070   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
1072   foreach my $accno (sort keys %trb) {
 
1075     $ref->{accno} = $accno;
 
1076     map { $ref->{$_} = $trb{$accno}{$_} }
 
1077       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
1079     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
1081     if ($trb{$accno}{charttype} eq 'A') {
 
1084       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1086       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
1087       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
1088       $last_transaction = "";
 
1089       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
1090         $ref->{debit}  += $debit;
 
1091         $ref->{credit} += $credit;
 
1093           $ref->{haben_saldo} += $saldo;
 
1095           $ref->{soll_saldo} += $saldo * -1;
 
1097         $ref->{last_transaction} = $last_transaction;
 
1098         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1099         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1103       if ($form->{project_id}) {
 
1106         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1108         ($debit, $credit) = (0, 0);
 
1109         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1110           $ref->{debit}  += $debit;
 
1111           $ref->{credit} += $credit;
 
1113             $ref->{haben_saldo} += $saldo;
 
1115             $ref->{soll_saldo} += $saldo * -1;
 
1117           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1118           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1120         $project_drcr->finish;
 
1123       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1124       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1126       if ($ref->{haben_saldo} != 0) {
 
1127         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1128         if ($ref->{haben_saldo} < 0) {
 
1129           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1130           $ref->{haben_saldo} = 0;
 
1133         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1134         if ($ref->{soll_saldo} < 0) {
 
1135           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1136           $ref->{soll_saldo} = 0;
 
1139       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1140       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1141       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1142       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1147     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1148     $accno = pop @accno;
 
1150       $trb{$accno}{debit}  += $ref->{debit};
 
1151       $trb{$accno}{credit} += $ref->{credit};
 
1152       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1153       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1154       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1155       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1158     push @{ $form->{TB} }, $ref;
 
1164   # debits and credits for headings
 
1165   foreach my $accno (@headingaccounts) {
 
1166     foreach $ref (@{ $form->{TB} }) {
 
1167       if ($accno eq $ref->{accno}) {
 
1168         $ref->{debit}           = $trb{$accno}{debit};
 
1169         $ref->{credit}          = $trb{$accno}{credit};
 
1170         $ref->{soll_saldo}      = $trb{$accno}{soll_saldo};
 
1171         $ref->{haben_saldo}     = $trb{$accno}{haben_saldo};
 
1172         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
 
1173         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};
 
1178   $main::lxdebug->leave_sub();
 
1182   $main::lxdebug->enter_sub();
 
1183   my ($self, $dbh, $form) = @_;
 
1184   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
 
1185   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
 
1186   my $sth =  $dbh->prepare($query);
 
1187   while(my $ref = $sth->fetchrow_hashref()) {
 
1188     $ref->{invnumer} =~ s/Storno zu //g;
 
1189     $form->{storno}{$ref->{invnumber}} = 1;
 
1191   $main::lxdebug->leave_sub();
 
1195   $main::lxdebug->enter_sub();
 
1197   my ($self, $myconfig, $form) = @_;
 
1199   # connect to database
 
1200   my $dbh     = $form->dbconnect($myconfig);
 
1202   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
 
1204   # falls customer ziehen wir die offene forderungsliste
 
1205   # anderfalls für die lieferanten die offenen verbindlichkeitne
 
1206   if ($form->{ct} eq "customer") {
 
1219   $ct_id = "${ct}_id";
 
1221   # erweiterung um einen freien zeitraum oder einen stichtag
 
1222   # mit entsprechender altersstrukturliste (s.a. Bug 1842)
 
1223   # eine neue variable an der oberfläche eingeführt, somit ist
 
1224   # todate == freier zeitrau und fordate == stichtag
 
1225   # duedate_where == nur fällige rechnungen anzeigen
 
1227   my ($review_of_aging_list, $todate, $fromdate, $fromwhere, $fordate,
 
1230   if ($form->{reporttype} eq 'custom') {  # altersstrukturliste, nur fällige
 
1232     # explizit rausschmeissen was man für diesen bericht nicht braucht
 
1233     delete $form->{fromdate};
 
1234     delete $form->{todate};
 
1236     # an der oberfläche ist das tagesaktuelle datum vorausgewählt
 
1237     # falls es dennoch per Benutzereingabe gelöscht wird, lieber wieder vorbelegen
 
1238     # ferner muss für die spätere DB-Abfrage muss todate gesetzt sein.
 
1239     $form->{fordate}  = $form->current_date($myconfig) unless ($form->{fordate});
 
1240     $fordate          = conv_dateq($form->{fordate});
 
1243     if ($form->{review_of_aging_list}) { # falls die liste leer ist, alles anzeigen
 
1244       if ($form->{review_of_aging_list} =~ m "-") {             # ..  periode von bis
 
1245         my @period = split(/-/, $form->{review_of_aging_list}); # ... von periode bis periode
 
1246         $review_of_aging_list = " AND $period[0] <  (date $fordate) - duedate
 
1247                                   AND (date $fordate) - duedate  < $period[1]";
 
1249         $form->{review_of_aging_list} =~ s/[^0-9]//g;   # größer 120 das substitute ist nur für das '>' zeichen
 
1250         $review_of_aging_list = " AND $form->{review_of_aging_list} < (date $fordate) - duedate";
 
1253     $duedate_where = " AND (date $fordate) - duedate >= 0 ";
 
1254   } else {  # freier zeitraum, nur rechnungsdatum und OHNE review_of_aging_list
 
1255     $form->{todate}  = $form->current_date($myconfig) unless ($form->{todate});
 
1256     $todate = conv_dateq($form->{todate});
 
1257     $fromdate = conv_dateq($form->{fromdate});
 
1258     $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
 
1260   my $where = " 1 = 1 ";
 
1263   if ($form->{$ct_id}) {
 
1264     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
 
1265   } elsif ($form->{ $form->{ct} }) {
 
1266     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
 
1271   if ($form->{department}) {
 
1272     my ($null, $department_id) = split /--/, $form->{department};
 
1273     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
 
1274     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1275     $where_dpt = qq| AND (${arap}.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1279     SELECT ${ct}.id AS ctid, ${ct}.name,
 
1280       street, zipcode, city, country, contact, email,
 
1281       phone as customerphone, fax as customerfax, ${ct}number,
 
1282       "invnumber", "transdate",
 
1283       (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",
 
1284       "duedate", invoice, ${arap}.id, date_part('days', now() - duedate) as overduedays,
 
1287        WHERE (${arap}.currency_id = exchangerate.currency_id)
 
1288          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
 
1290     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
 
1291       AND NOT COALESCE (${arap}.storno, 'f')
 
1292       AND (${arap}.${ct}_id = ${ct}.id)
 
1295       AND (transdate <= (date $todate) $fromwhere )
 
1296       $review_of_aging_list
 
1298     ORDER BY ctid, transdate, invnumber |;
 
1300   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1302   # select outstanding vendors or customers, depends on $ct
 
1304     qq|SELECT DISTINCT ct.id, ct.name
 
1305        FROM $ct ct, $arap a
 
1308          AND (a.${ct_id} = ct.id)
 
1309          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
 
1310          AND (a.transdate <= $todate $fromwhere)
 
1313   my $sth = prepare_execute_query($form, $dbh, $query);
 
1316   # for each company that has some stuff outstanding
 
1317   while (my ($id) = $sth->fetchrow_array) {
 
1318     do_statement($form, $sth_details, $q_details, $id);
 
1320     while (my $ref = $sth_details->fetchrow_hashref("NAME_lc")) {
 
1321       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
 
1322       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
 
1323       push @{ $form->{AG} }, $ref;
 
1326     $sth_details->finish;
 
1335   $main::lxdebug->leave_sub();
 
1339   $main::lxdebug->enter_sub();
 
1341   my ($self, $myconfig, $form) = @_;
 
1343   # connect to database
 
1344   my $dbh = $form->dbconnect($myconfig);
 
1346   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1349     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1352   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1353     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1356   $main::lxdebug->leave_sub();
 
1360   $main::lxdebug->enter_sub();
 
1362   my ($self, $myconfig, $form) = @_;
 
1364   # connect to database
 
1365   my $dbh = $form->dbconnect($myconfig);
 
1367   my ($null, $department_id) = split /--/, $form->{department};
 
1370   my $where = "1 = 1";
 
1372   if ($department_id) {
 
1373     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1378   if ($form->{accno}) {
 
1379     $accno = $form->{accno};
 
1380     $rate  = $form->{"$form->{accno}_rate"};
 
1381     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1387   if ($form->{db} eq 'ar') {
 
1388     $table = "customer";
 
1395   my $arap = lc($ARAP);
 
1397   my $transdate = "a.transdate";
 
1399   if ($form->{method} eq 'cash') {
 
1400     $transdate = "a.datepaid";
 
1402     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1409           WHERE (a.chart_link LIKE '%${ARAP}_paid%')
 
1410           AND (transdate <= $todate)
 
1415   # if there are any dates construct a where
 
1416   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1417   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1419   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1421   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1422   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1425       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1426           ac.amount * $ml AS tax
 
1428          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1429          JOIN chart ch ON (ch.id = ac.chart_id)
 
1430          JOIN $table n ON (n.id = a.${table}_id)
 
1434            AND (a.invoice = '0')
 
1438          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1439            i.sellprice * i.qty * $rate * $ml AS tax
 
1441          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1442          JOIN chart ch ON (ch.id = ac.chart_id)
 
1443          JOIN $table n ON (n.id = a.${table}_id)
 
1444          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1445          JOIN invoice i ON (i.trans_id = a.id)
 
1449            AND (a.invoice = '1')
 
1450          ORDER BY $sortorder|;
 
1452   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1456   $main::lxdebug->leave_sub();
 
1459 sub paymentaccounts {
 
1460   $main::lxdebug->enter_sub();
 
1462   my ($self, $myconfig, $form) = @_;
 
1464   # connect to database, turn AutoCommit off
 
1465   my $dbh = $form->dbconnect_noauto($myconfig);
 
1467   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1469   # get A(R|P)_paid accounts
 
1471     qq|SELECT accno, description
 
1473        WHERE link LIKE '%${ARAP}_paid%'|;
 
1474   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1478   $main::lxdebug->leave_sub();
 
1482   $main::lxdebug->enter_sub();
 
1484   my ($self, $myconfig, $form) = @_;
 
1486   # connect to database, turn AutoCommit off
 
1487   my $dbh = $form->dbconnect_noauto($myconfig);
 
1492   if ($form->{db} eq 'ar') {
 
1493     $table = 'customer';
 
1504   if ($form->{department_id}) {
 
1505     $where = qq| AND (a.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1508   if ($form->{fromdate}) {
 
1509     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1511   if ($form->{todate}) {
 
1512     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1514   if (!$form->{fx_transaction}) {
 
1515     $where .= " AND ac.fx_transaction = '0'";
 
1520   if ($form->{reference}) {
 
1521     $reference = $dbh->quote('%' . $form->{reference} . '%');
 
1522     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1523     $reference = " AND (a.reference LIKE $reference)";
 
1525   if ($form->{source}) {
 
1526     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
 
1528   if ($form->{memo}) {
 
1529     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
 
1532   my %sort_columns =  (
 
1533     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1534     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1535     'name'         => [ qw(lower_name transdate)                 ],
 
1536     'source'       => [ qw(lower_source)                         ],
 
1537     'memo'         => [ qw(lower_memo)                           ],
 
1539   my %lowered_columns =  (
 
1540     'invnumber'       => { 'gl' => 'a.reference',   'arap' => 'a.invnumber', },
 
1541     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1542     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1543     'name'            => { 'gl' => 'a.description', 'arap' => 'c.name',      },
 
1546   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1547   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1548   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1551   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1552   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1553     next if ($spec !~ m/^lower_(.*)$/);
 
1556     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1559   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1560   $sth = prepare_query($form, $dbh, $query);
 
1563       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1564            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1565            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1566            $columns_for_sorting{arap}
 
1568          JOIN $arap a ON (ac.trans_id = a.id)
 
1569          JOIN $table c ON (c.id = a.${table}_id)
 
1570          WHERE (ac.chart_id = ?)
 
1576          SELECT a.description, a.reference, NULL AS ordnumber,
 
1577            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1578            '0' as invoice, a.id, ac.memo, 'gl' AS module
 
1579            $columns_for_sorting{gl}
 
1581          JOIN gl a ON (a.id = ac.trans_id)
 
1582          WHERE (ac.chart_id = ?)
 
1585            AND (ac.amount * $ml) > 0
 
1587          ORDER BY $sortorder|;
 
1588   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1592   # cycle through each id
 
1593   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1594     do_statement($form, $sth, $query, $accno);
 
1595     my $ref = $sth->fetchrow_hashref();
 
1596     push(@{ $form->{PR} }, $ref);
 
1599     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1601     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1602     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1603       push(@{ $form->{ $ref->{id} } }, $pr);
 
1605     $sth_details->finish();
 
1610   $main::lxdebug->leave_sub();
 
1614   $main::lxdebug->enter_sub();
 
1616   my ($self, $myconfig, $form) = @_;
 
1618   # connect to database
 
1619   my $dbh = $form->dbconnect($myconfig);
 
1621   my $last_period = 0;
 
1624     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);
 
1626   $form->{decimalplaces} *= 1;
 
1628   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1630   # if there are any compare dates
 
1632   if ($form->{fromdate} || $form->{todate}) {
 
1634     if ($form->{fromdate}) {
 
1635       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1638       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1641     my $kummfromdate = $form->{comparefromdate};
 
1642     my $kummtodate   = $form->{comparetodate};
 
1643     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1646   my @periods        = qw(jetzt kumm);
 
1647   my @gesamtleistung = qw(1 3);
 
1648   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 20);
 
1650     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1652   foreach my $key (@periods) {
 
1653     $form->{ "$key" . "gesamtleistung" } = 0;
 
1654     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1656     foreach $category (@categories) {
 
1658       if (defined($form->{$category}{$key})) {
 
1659         $form->{"$key$category"} =
 
1660           $form->format_amount($myconfig,
 
1661                                $form->round_amount($form->{$category}{$key}, 2
 
1663                                $form->{decimalplaces},
 
1667     foreach my $item (@gesamtleistung) {
 
1668       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1670     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1672     foreach my $item (@gesamtkosten) {
 
1673       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1675     $form->{ "$key" . "rohertrag" } =
 
1676       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1677     $form->{ "$key" . "betriebrohertrag" } =
 
1678       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1679     $form->{ "$key" . "betriebsergebnis" } =
 
1680       $form->{ "$key" . "betriebrohertrag" } -
 
1681       $form->{ "$key" . "gesamtkosten" };
 
1682     $form->{ "$key" . "neutraleraufwand" } =
 
1683       $form->{19}{$key} + $form->{30}{$key} + $form->{31}{$key};
 
1684     $form->{ "$key" . "neutralerertrag" } =
 
1685       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1686     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1687       $form->{ "$key" . "betriebsergebnis" } -
 
1688       $form->{ "$key" . "neutraleraufwand" } +
 
1689       $form->{ "$key" . "neutralerertrag" };
 
1690     $form->{ "$key" . "ergebnis" } =
 
1691       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1693     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1694       foreach $category (@categories) {
 
1695         if (defined($form->{$category}{$key})) {
 
1696           $form->{ "$key" . "gl" . "$category" } =
 
1697             $form->format_amount(
 
1699                                $form->round_amount(
 
1700                                  ($form->{$category}{$key} /
 
1701                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1703                                  $form->{decimalplaces}
 
1705                                $form->{decimalplaces},
 
1709       foreach my $item (@ergebnisse) {
 
1710         $form->{ "$key" . "gl" . "$item" } =
 
1711           $form->format_amount($myconfig,
 
1712                                $form->round_amount(
 
1713                                  ( $form->{ "$key" . "$item" } /
 
1714                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1716                                  $form->{decimalplaces}
 
1718                                $form->{decimalplaces},
 
1723     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1724       foreach $category (@categories) {
 
1725         if (defined($form->{$category}{$key})) {
 
1726           $form->{ "$key" . "gk" . "$category" } =
 
1727             $form->format_amount($myconfig,
 
1728                                  $form->round_amount(
 
1729                                    ($form->{$category}{$key} /
 
1730                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1732                                    $form->{decimalplaces}
 
1734                                  $form->{decimalplaces},
 
1738       foreach my $item (@ergebnisse) {
 
1739         $form->{ "$key" . "gk" . "$item" } =
 
1740           $form->format_amount($myconfig,
 
1741                                $form->round_amount(
 
1742                                    ($form->{ "$key" . "$item" } /
 
1743                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1745                                    $form->{decimalplaces}
 
1747                                $form->{decimalplaces},
 
1752     if ($form->{10}{$key} > 0) {
 
1753       foreach $category (@categories) {
 
1754         if (defined($form->{$category}{$key})) {
 
1755           $form->{ "$key" . "pk" . "$category" } =
 
1756             $form->format_amount(
 
1758                         $form->round_amount(
 
1759                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1760                           $form->{decimalplaces}
 
1762                         $form->{decimalplaces},
 
1766       foreach my $item (@ergebnisse) {
 
1767         $form->{ "$key" . "pk" . "$item" } =
 
1768           $form->format_amount($myconfig,
 
1769                                $form->round_amount(
 
1770                                                 ($form->{ "$key" . "$item" } /
 
1771                                                    $form->{10}{$key} * 100
 
1773                                                 $form->{decimalplaces}
 
1775                                $form->{decimalplaces},
 
1780     if ($form->{4}{$key} > 0) {
 
1781       foreach $category (@categories) {
 
1782         if (defined($form->{$category}{$key})) {
 
1783           $form->{ "$key" . "auf" . "$category" } =
 
1784             $form->format_amount(
 
1786                          $form->round_amount(
 
1787                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1788                            $form->{decimalplaces}
 
1790                          $form->{decimalplaces},
 
1794       foreach my $item (@ergebnisse) {
 
1795         $form->{ "$key" . "auf" . "$item" } =
 
1796           $form->format_amount($myconfig,
 
1797                                $form->round_amount(
 
1798                                                 ($form->{ "$key" . "$item" } /
 
1799                                                    $form->{4}{$key} * 100
 
1801                                                 $form->{decimalplaces}
 
1803                                $form->{decimalplaces},
 
1808     foreach my $item (@ergebnisse) {
 
1809       $form->{ "$key" . "$item" } =
 
1810         $form->format_amount($myconfig,
 
1811                              $form->round_amount($form->{ "$key" . "$item" },
 
1812                                                  $form->{decimalplaces}
 
1814                              $form->{decimalplaces},
 
1821   $main::lxdebug->leave_sub();
 
1824 sub income_statement {
 
1825   $main::lxdebug->enter_sub();
 
1827   my ($self, $myconfig, $form) = @_;
 
1829   # connect to database
 
1830   my $dbh = $form->dbconnect($myconfig);
 
1832   my $last_period          = 0;
 
1833   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1834   my @categories_ausgaben  =
 
1835     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);
 
1837   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1839   $form->{decimalplaces} *= 1;
 
1843   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1847   foreach my $item (@categories_einnahmen) {
 
1848     $form->{"eur${item}"} =
 
1849       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1850     $form->{"sumeura"} += $form->{$item};
 
1852   foreach my $item (@categories_ausgaben) {
 
1853     $form->{"eur${item}"} =
 
1854       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1855     $form->{"sumeurb"} += $form->{$item};
 
1858   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1860   foreach my $item (@ergebnisse) {
 
1862       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1864   $main::lxdebug->leave_sub();
 
1867 sub erfolgsrechnung {
 
1868   $main::lxdebug->enter_sub();
 
1870   my ($self, $myconfig, $form) = @_;
 
1871   $form->{company} = $::instance_conf->get_company;
 
1872   $form->{address} = $::instance_conf->get_address;
 
1874   # wrong user inputs should be handled during users input
 
1875   # e.g.  spaces, tabs, wrong format or wrong dates
 
1876   $form->{fromdate} = "01.01.2000" if !$form->{fromdate};
 
1877   $form->{todate} = $form->current_date(%{$myconfig}) if !$form->{todate};
 
1879   my %categories = (I => "ERTRAG", E => "AUFWAND");
 
1880   my $fromdate = conv_dateq($form->{fromdate});
 
1881   my $todate = conv_dateq($form->{todate});
 
1884   foreach my $category (keys %categories) {
 
1886       name => $categories{$category},
 
1888       accounts => get_accounts_ch($category),
 
1890     foreach my $account (@{$category{accounts}}) {
 
1891       $account->{total} += ($account->{category} eq $category ? 1 : -1) * get_total_ch($account->{id}, $fromdate, $todate);
 
1892       $category{total} += $account->{total};
 
1893       $account->{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $account->{total}), 2);
 
1895     $form->{total} += $category{total};
 
1896     $category{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $category{total}), 2);
 
1897     push(@{$form->{categories}}, \%category);
 
1899   $form->{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $form->{total}), 2);
 
1901   $main::lxdebug->leave_sub();
 
1905 sub get_accounts_ch {
 
1906   $main::lxdebug->enter_sub();
 
1908   my ($category) = @_;
 
1911   if ($category eq 'I') {
 
1912     $inclusion = "AND pos_er = NULL OR pos_er > '0' AND pos_er <= '5'";
 
1913   } elsif ($category eq 'E') {
 
1914     $inclusion = "AND pos_er = NULL OR pos_er >= '6' AND pos_er < '100'";
 
1920     SELECT id, accno, description, category
 
1922     WHERE category = ? $inclusion
 
1925   my $accounts = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, $category);
 
1927   $main::lxdebug->leave_sub();
 
1932   $main::lxdebug->enter_sub();
 
1934   my ($chart_id, $fromdate, $todate) = @_;
 
1943   my $data = selectfirst_hashref_query($::form, $::form->get_standard_dbh, $query, $chart_id, $fromdate, $todate);
 
1944   $total += $data->{sum};
 
1946   $main::lxdebug->leave_sub();