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)";
 
 476       # hotfix for projectfilter in guv and bwa
 
 477       # fromdate is otherwise ignored if project is selected
 
 478       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 483     $todate = conv_dateq($todate);
 
 484     $subwhere   .= " AND (transdate    <= $todate)";
 
 485     $where      .= " AND (ac.transdate <= $todate)";
 
 486     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 487     $inwhere    .= " AND (acc.transdate <= $todate)";
 
 490   if ($department_id) {
 
 491     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 494   if ($form->{project_id}) {
 
 495     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
 
 499 # GUV patch by Ronny Rentner (Bug 1190)
 
 501 # GUV IST-Versteuerung
 
 503 # Alle tatsaechlichen _Zahlungseingaenge_
 
 504 # im Zeitraum erfassen
 
 505 # (Teilzahlungen werden prozentual auf verschiedene Steuern aufgeteilt)
 
 509   if ($form->{method} eq 'cash') {
 
 512        SELECT SUM( ac.amount * CASE WHEN COALESCE((SELECT amount FROM ar a WHERE id = ac.trans_id $dpt_where), 0) != 0 THEN
 
 513             /* ar amount is not zero, so we can divide by amount   */
 
 514                     (SELECT SUM(acc.amount) * -1
 
 517                      AND acc.trans_id = ac.trans_id
 
 518                      AND acc.chart_link LIKE '%AR_paid%')
 
 519                   / (SELECT amount FROM ar WHERE id = ac.trans_id)
 
 521             /* 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 */
 
 523                 ) AS amount, c.$category
 
 525        LEFT JOIN chart c ON (c.id  = ac.chart_id)
 
 526        LEFT JOIN ar      ON (ar.id = ac.trans_id)
 
 527       WHERE ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE 1=1 $subwhere)
 
 532        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 534          JOIN chart c ON (c.id = ac.chart_id)
 
 535          JOIN ar a ON (a.id = ac.trans_id)
 
 536          WHERE $where $dpt_where
 
 537            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 543          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 545          JOIN chart c ON (c.id = ac.chart_id)
 
 546          JOIN ap a ON (a.id = ac.trans_id)
 
 547          WHERE $where $dpt_where
 
 548            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 554          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 556          JOIN chart c ON (c.id = ac.chart_id)
 
 557          JOIN gl a ON (a.id = ac.trans_id)
 
 558          WHERE $where $dpt_where $glwhere
 
 559            AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 564     if ($form->{project_id}) {
 
 568          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 570          JOIN ar a ON (a.id = ac.trans_id)
 
 571          JOIN parts p ON (ac.parts_id = p.id)
 
 572          JOIN chart c on (p.income_accno_id = c.id)
 
 573          WHERE (c.category = 'I') $prwhere $dpt_where
 
 574            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 580          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 582          JOIN ap a ON (a.id = ac.trans_id)
 
 583          JOIN parts p ON (ac.parts_id = p.id)
 
 584          JOIN chart c on (p.expense_accno_id = c.id)
 
 585          WHERE (c.category = 'E') $prwhere $dpt_where
 
 586            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 592   } else {                      # if ($form->{method} eq 'cash')
 
 593     if ($department_id) {
 
 594       $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 595       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 596                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 597                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 601         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 603         JOIN chart c ON (c.id = ac.chart_id)
 
 605           $dpt_where_without_arapgl
 
 607         GROUP BY c.$category |;
 
 609     if ($form->{project_id}) {
 
 613         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 615         JOIN ar a ON (a.id = ac.trans_id)
 
 616         JOIN parts p ON (ac.parts_id = p.id)
 
 617         JOIN chart c on (p.income_accno_id = c.id)
 
 618         WHERE (c.category = 'I')
 
 626         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 628         JOIN ap a ON (a.id = ac.trans_id)
 
 629         JOIN parts p ON (ac.parts_id = p.id)
 
 630         JOIN chart c on (p.expense_accno_id = c.id)
 
 631         WHERE (c.category = 'E')
 
 635         GROUP BY c.$category |;
 
 643   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
 
 644     if ($category eq "pos_bwa") {
 
 646         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 648         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 651       $form->{ $ref->{$category} } += $ref->{amount};
 
 655   $main::lxdebug->leave_sub();
 
 659   $main::lxdebug->enter_sub();
 
 661   my ($self, $myconfig, $form, %options) = @_;
 
 663   my $dbh = $form->dbconnect($myconfig);
 
 665   my ($query, $sth, $ref);
 
 668   my ($null, $department_id) = split /--/, $form->{department};
 
 669   my @headingaccounts = ();
 
 671   my $dpt_where_without_arapgl;
 
 672   my ($customer_where, $customer_join, $customer_no_union);
 
 676   my $invwhere = $where;
 
 678   if ($department_id) {
 
 679     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 680     $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 681                                                  (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 682                                                  (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 684   if ($form->{customer_id}) {
 
 685     $customer_join     = qq| JOIN ar a ON (ac.trans_id = a.id) |;
 
 686     $customer_where    = qq| AND (a.customer_id = | . conv_i($form->{customer_id}, 'NULL') . qq|) |;
 
 687     $customer_no_union = qq| AND 1=0 |;
 
 690   # project_id only applies to getting transactions
 
 691   # it has nothing to do with a trial balance
 
 692   # but we use the same function to collect information
 
 694   if ($form->{project_id}) {
 
 695     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 698   my $acc_cash_where = "";
 
 699 #  my $ar_cash_where = "";
 
 700 #  my $ap_cash_where = "";
 
 703   if ($form->{method} eq "cash") {
 
 705       qq| AND (ac.trans_id IN (
 
 708             WHERE datepaid >= '$form->{fromdate}'
 
 709               AND datepaid <= '$form->{todate}'
 
 715             WHERE datepaid >= '$form->{fromdate}'
 
 716               AND datepaid <= '$form->{todate}'
 
 722             WHERE transdate >= '$form->{fromdate}'
 
 723               AND transdate <= '$form->{todate}'
 
 725 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 728   if ($options{beginning_balances}) {
 
 729     foreach my $prefix (qw(from to)) {
 
 730       next if ($form->{"${prefix}date"});
 
 732       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 733       $query      = qq|SELECT ${min_max}(transdate)
 
 737                          $dpt_where_without_arapgl
 
 741       ($form->{"${prefix}date"}) = selectfirst_array_query($form, $dbh, $query);
 
 744     # get beginning balances
 
 746       qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
 
 748           LEFT JOIN chart c ON (ac.chart_id = c.id)
 
 750           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 751             $dpt_where_without_arapgl
 
 754           GROUP BY c.accno, c.category, c.description |;
 
 756     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 758     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 760       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 761         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 762         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 763         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 765         if ($ref->{amount} > 0) {
 
 766           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 768           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 770         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 779     qq|SELECT c.accno, c.description, c.category
 
 781        WHERE c.charttype = 'H'
 
 784   $sth = prepare_execute_query($form, $dbh, $query);
 
 786   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 787     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 788     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 789     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 791     push @headingaccounts, $ref->{accno};
 
 797   my $saldowhere    = " 1 = 1 ";
 
 798   my $sumwhere      = " 1 = 1 ";
 
 800   my $sumsubwhere   = '';
 
 801   my $saldosubwhere = '';
 
 802   my $glsaldowhere  = '';
 
 807   my ($fromdate, $todate, $fetch_accounts_before_from);
 
 809   if ($form->{fromdate} || $form->{todate}) {
 
 810     if ($form->{fromdate}) {
 
 811       $fromdate = conv_dateq($form->{fromdate});
 
 812       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 813       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 814       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 815       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 816       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 817       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 818       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 819       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 821     if ($form->{todate}) {
 
 822       $todate = conv_dateq($form->{todate});
 
 823       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 824       $invwhere      .= " AND (a.transdate <= $todate)";
 
 825       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 826       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 827       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 828       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 829       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 830       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 834   if ($form->{method} eq "cash") {
 
 836       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) |;
 
 837     $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) |;
 
 839     $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) |;
 
 841     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 842     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 843     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 845     # get all entries before fromdate, which are not yet fetched
 
 846     # TODO dpt_where_without_arapgl and project - project calculation seems bogus anyway
 
 847     # TODO use fiscal_year_startdate for the whole trial balance
 
 848     #      anyway, if the last booking is in a deviating fiscal year, this already improves the query
 
 849     my $fiscal_year_startdate = conv_dateq($self->get_balance_starting_date($form->{fromdate}));
 
 850     $fetch_accounts_before_from = qq|SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 851                        FROM acc_trans ac JOIN chart c ON (c.id = ac.chart_id) WHERE 1 = 1 AND (ac.transdate <= $fromdate)
 
 852                        AND (ac.transdate >= $fiscal_year_startdate)
 
 853                        AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)
 
 854                        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)
 
 855                        AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL))
 
 856                        GROUP BY c.accno, c.description, c.category ORDER BY accno|;
 
 860        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 862        JOIN chart c ON (c.id = ac.chart_id)
 
 865          $dpt_where_without_arapgl
 
 867        GROUP BY c.accno, c.description, c.category |;
 
 869   if ($form->{project_id}) {
 
 871       -- add project transactions from invoice
 
 875       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 877       JOIN ar a ON (ac.trans_id = a.id)
 
 878       JOIN parts p ON (ac.parts_id = p.id)
 
 879       JOIN chart c ON (p.income_accno_id = c.id)
 
 884       GROUP BY c.accno, c.description, c.category
 
 888       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 890       JOIN ap a ON (ac.trans_id = a.id)
 
 891       JOIN parts p ON (ac.parts_id = p.id)
 
 892       JOIN chart c ON (p.expense_accno_id = c.id)
 
 897       GROUP BY c.accno, c.description, c.category
 
 901   $query .= qq| ORDER BY accno|;
 
 903   $sth = prepare_execute_query($form, $dbh, $query);
 
 905   # calculate the debit and credit in the period
 
 906   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 907     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 908     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 909     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 910     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 914   if ($form->{method} ne "cash") {  # better eq 'accrual'
 
 915     $sth = prepare_execute_query($form, $dbh, $fetch_accounts_before_from);
 
 916     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 917       $trb{ $ref->{accno} }{description} = $ref->{description};
 
 918       $trb{ $ref->{accno} }{charttype}   = 'A';
 
 919       $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 920       $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 925   # prepare query for each account
 
 926   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 930          (SELECT SUM(ac.amount) * -1
 
 932           JOIN chart c ON (c.id = ac.chart_id)
 
 935             $dpt_where_without_arapgl
 
 939           AND (c.accno = ?)) AS debit,
 
 941          (SELECT SUM(ac.amount)
 
 943           JOIN chart c ON (c.id = ac.chart_id)
 
 946             $dpt_where_without_arapgl
 
 950           AND c.accno = ?) AS credit,
 
 951         (SELECT SUM(ac.amount)
 
 953          JOIN chart c ON (ac.chart_id = c.id)
 
 956            $dpt_where_without_arapgl
 
 959          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 961         (SELECT SUM(ac.amount)
 
 963          JOIN chart c ON (ac.chart_id = c.id)
 
 966            $dpt_where_without_arapgl
 
 970          AND c.accno = ?) AS sum_credit,
 
 972         (SELECT SUM(ac.amount)
 
 974          JOIN chart c ON (ac.chart_id = c.id)
 
 977            $dpt_where_without_arapgl
 
 981          AND c.accno = ?) AS sum_debit,
 
 983         (SELECT max(ac.transdate) FROM acc_trans ac
 
 984         JOIN chart c ON (ac.chart_id = c.id)
 
 987           $dpt_where_without_arapgl
 
 990         AND c.accno = ?) AS last_transaction
 
 995   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 997   if ($form->{project_id}) {
 
 998     # prepare query for each account
 
1001           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
1003            JOIN parts p ON (ac.parts_id = p.id)
 
1004            JOIN ap a ON (ac.trans_id = a.id)
 
1005            JOIN chart c ON (p.expense_accno_id = c.id)
 
1010            AND c.accno = ?) AS debit,
 
1012           (SELECT SUM(ac.sellprice * ac.qty)
 
1014            JOIN parts p ON (ac.parts_id = p.id)
 
1015            JOIN ar a ON (ac.trans_id = a.id)
 
1016            JOIN chart c ON (p.income_accno_id = c.id)
 
1021            AND c.accno = ?) AS credit,
 
1023         (SELECT SUM(ac.amount)
 
1025          JOIN chart c ON (ac.chart_id = c.id)
 
1028            $dpt_where_without_arapgl
 
1032          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
1034         (SELECT SUM(ac.amount)
 
1036          JOIN chart c ON (ac.chart_id = c.id)
 
1039            $dpt_where_without_arapgl
 
1044          AND c.accno = ?) AS sum_credit,
 
1046         (SELECT SUM(ac.amount)
 
1048          JOIN chart c ON (ac.chart_id = c.id)
 
1052            $dpt_where_without_arapgl
 
1056          AND c.accno = ?) AS sum_debit,
 
1059         (SELECT max(ac.transdate) FROM acc_trans ac
 
1060         JOIN chart c ON (ac.chart_id = c.id)
 
1063           $dpt_where_without_arapgl
 
1066         AND c.accno = ?) AS last_transaction
 
1069     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
1073   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
1075   foreach my $accno (sort keys %trb) {
 
1078     $ref->{accno} = $accno;
 
1079     map { $ref->{$_} = $trb{$accno}{$_} }
 
1080       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
1082     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
1084     if ($trb{$accno}{charttype} eq 'A') {
 
1087       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1089       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
1090       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
1091       $last_transaction = "";
 
1092       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
1093         $ref->{debit}  += $debit;
 
1094         $ref->{credit} += $credit;
 
1096           $ref->{haben_saldo} += $saldo;
 
1098           $ref->{soll_saldo} += $saldo * -1;
 
1100         $ref->{last_transaction} = $last_transaction;
 
1101         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1102         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1106       if ($form->{project_id}) {
 
1109         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1111         ($debit, $credit) = (0, 0);
 
1112         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1113           $ref->{debit}  += $debit;
 
1114           $ref->{credit} += $credit;
 
1116             $ref->{haben_saldo} += $saldo;
 
1118             $ref->{soll_saldo} += $saldo * -1;
 
1120           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1121           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1123         $project_drcr->finish;
 
1126       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1127       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1129       if ($ref->{haben_saldo} != 0) {
 
1130         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1131         if ($ref->{haben_saldo} < 0) {
 
1132           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1133           $ref->{haben_saldo} = 0;
 
1136         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1137         if ($ref->{soll_saldo} < 0) {
 
1138           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1139           $ref->{soll_saldo} = 0;
 
1142       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1143       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1144       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1145       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1150     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1151     $accno = pop @accno;
 
1153       $trb{$accno}{debit}  += $ref->{debit};
 
1154       $trb{$accno}{credit} += $ref->{credit};
 
1155       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1156       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1157       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1158       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1161     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     = $form->dbconnect($myconfig);
 
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;
 
1338   $main::lxdebug->leave_sub();
 
1342   $main::lxdebug->enter_sub();
 
1344   my ($self, $myconfig, $form) = @_;
 
1346   # connect to database
 
1347   my $dbh = $form->dbconnect($myconfig);
 
1349   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1352     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1355   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1356     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1359   $main::lxdebug->leave_sub();
 
1363   $main::lxdebug->enter_sub();
 
1365   my ($self, $myconfig, $form) = @_;
 
1367   # connect to database
 
1368   my $dbh = $form->dbconnect($myconfig);
 
1370   my ($null, $department_id) = split /--/, $form->{department};
 
1373   my $where = "1 = 1";
 
1375   if ($department_id) {
 
1376     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1381   if ($form->{accno}) {
 
1382     $accno = $form->{accno};
 
1383     $rate  = $form->{"$form->{accno}_rate"};
 
1384     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1390   if ($form->{db} eq 'ar') {
 
1391     $table = "customer";
 
1398   my $arap = lc($ARAP);
 
1400   my $transdate = "a.transdate";
 
1402   if ($form->{method} eq 'cash') {
 
1403     $transdate = "a.datepaid";
 
1405     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1412           WHERE (a.chart_link LIKE '%${ARAP}_paid%')
 
1413           AND (transdate <= $todate)
 
1418   # if there are any dates construct a where
 
1419   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1420   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1422   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1424   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1425   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1428       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1429           ac.amount * $ml AS tax
 
1431          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1432          JOIN chart ch ON (ch.id = ac.chart_id)
 
1433          JOIN $table n ON (n.id = a.${table}_id)
 
1437            AND (a.invoice = '0')
 
1441          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1442            i.sellprice * i.qty * $rate * $ml AS tax
 
1444          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1445          JOIN chart ch ON (ch.id = ac.chart_id)
 
1446          JOIN $table n ON (n.id = a.${table}_id)
 
1447          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1448          JOIN invoice i ON (i.trans_id = a.id)
 
1452            AND (a.invoice = '1')
 
1453          ORDER BY $sortorder|;
 
1455   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1459   $main::lxdebug->leave_sub();
 
1462 sub paymentaccounts {
 
1463   $main::lxdebug->enter_sub();
 
1465   my ($self, $myconfig, $form) = @_;
 
1467   # connect to database, turn AutoCommit off
 
1468   my $dbh = $form->dbconnect_noauto($myconfig);
 
1470   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1472   # get A(R|P)_paid accounts
 
1474     qq|SELECT accno, description
 
1476        WHERE link LIKE '%${ARAP}_paid%'|;
 
1477   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1481   $main::lxdebug->leave_sub();
 
1485   $main::lxdebug->enter_sub();
 
1487   my ($self, $myconfig, $form) = @_;
 
1489   # connect to database, turn AutoCommit off
 
1490   my $dbh = $form->dbconnect_noauto($myconfig);
 
1495   if ($form->{db} eq 'ar') {
 
1496     $table = 'customer';
 
1507   if ($form->{department_id}) {
 
1508     $where = qq| AND (a.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1511   if ($form->{fromdate}) {
 
1512     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1514   if ($form->{todate}) {
 
1515     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1517   if (!$form->{fx_transaction}) {
 
1518     $where .= " AND ac.fx_transaction = '0'";
 
1523   if ($form->{reference}) {
 
1524     $reference = $dbh->quote(like($form->{reference}));
 
1525     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1526     $reference = " AND (a.reference LIKE $reference)";
 
1528   if ($form->{source}) {
 
1529     $where .= " AND (ac.source ILIKE " . $dbh->quote(like($form->{source})) . ") ";
 
1531   if ($form->{memo}) {
 
1532     $where .= " AND (ac.memo ILIKE " . $dbh->quote(like($form->{memo})) . ") ";
 
1535   my %sort_columns =  (
 
1536     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1537     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1538     'name'         => [ qw(lower_name transdate)                 ],
 
1539     'source'       => [ qw(lower_source)                         ],
 
1540     'memo'         => [ qw(lower_memo)                           ],
 
1542   my %lowered_columns =  (
 
1543     'invnumber'       => { 'gl' => 'a.reference',   'arap' => 'a.invnumber', },
 
1544     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1545     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1546     'name'            => { 'gl' => 'a.description', 'arap' => 'c.name',      },
 
1549   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1550   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1551   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1554   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1555   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1556     next if ($spec !~ m/^lower_(.*)$/);
 
1559     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1562   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1563   $sth = prepare_query($form, $dbh, $query);
 
1566       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1567            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1568            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1569            $columns_for_sorting{arap}
 
1571          JOIN $arap a ON (ac.trans_id = a.id)
 
1572          JOIN $table c ON (c.id = a.${table}_id)
 
1573          WHERE (ac.chart_id = ?)
 
1579          SELECT a.description, a.reference, NULL AS ordnumber,
 
1580            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1581            '0' as invoice, a.id, ac.memo, 'gl' AS module
 
1582            $columns_for_sorting{gl}
 
1584          JOIN gl a ON (a.id = ac.trans_id)
 
1585          WHERE (ac.chart_id = ?)
 
1588            AND (ac.amount * $ml) > 0
 
1590          ORDER BY $sortorder|;
 
1591   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1595   # cycle through each id
 
1596   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1597     do_statement($form, $sth, $query, $accno);
 
1598     my $ref = $sth->fetchrow_hashref();
 
1599     push(@{ $form->{PR} }, $ref);
 
1602     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1604     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1605     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1606       push(@{ $form->{ $ref->{id} } }, $pr);
 
1608     $sth_details->finish();
 
1613   $main::lxdebug->leave_sub();
 
1617   $main::lxdebug->enter_sub();
 
1619   my ($self, $myconfig, $form) = @_;
 
1621   # connect to database
 
1622   my $dbh = $form->dbconnect($myconfig);
 
1624   my $last_period = 0;
 
1627     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);
 
1629   $form->{decimalplaces} *= 1;
 
1631   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1633   # if there are any compare dates
 
1635   if ($form->{fromdate} || $form->{todate}) {
 
1637     if ($form->{fromdate}) {
 
1638       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1641       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1644     my $kummfromdate = $form->{comparefromdate};
 
1645     my $kummtodate   = $form->{comparetodate};
 
1646     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1649   my @periods        = qw(jetzt kumm);
 
1650   my @gesamtleistung = qw(1 3);
 
1651   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 20);
 
1653     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1655   foreach my $key (@periods) {
 
1656     $form->{ "$key" . "gesamtleistung" } = 0;
 
1657     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1659     foreach $category (@categories) {
 
1661       if (defined($form->{$category}{$key})) {
 
1662         $form->{"$key$category"} =
 
1663           $form->format_amount($myconfig,
 
1664                                $form->round_amount($form->{$category}{$key}, 2
 
1666                                $form->{decimalplaces},
 
1670     foreach my $item (@gesamtleistung) {
 
1671       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1673     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1675     foreach my $item (@gesamtkosten) {
 
1676       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1678     $form->{ "$key" . "rohertrag" } =
 
1679       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1680     $form->{ "$key" . "betriebrohertrag" } =
 
1681       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1682     $form->{ "$key" . "betriebsergebnis" } =
 
1683       $form->{ "$key" . "betriebrohertrag" } -
 
1684       $form->{ "$key" . "gesamtkosten" };
 
1685     $form->{ "$key" . "neutraleraufwand" } =
 
1686       $form->{19}{$key} + $form->{30}{$key} + $form->{31}{$key};
 
1687     $form->{ "$key" . "neutralerertrag" } =
 
1688       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1689     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1690       $form->{ "$key" . "betriebsergebnis" } -
 
1691       $form->{ "$key" . "neutraleraufwand" } +
 
1692       $form->{ "$key" . "neutralerertrag" };
 
1693     $form->{ "$key" . "ergebnis" } =
 
1694       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1696     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1697       foreach $category (@categories) {
 
1698         if (defined($form->{$category}{$key})) {
 
1699           $form->{ "$key" . "gl" . "$category" } =
 
1700             $form->format_amount(
 
1702                                $form->round_amount(
 
1703                                  ($form->{$category}{$key} /
 
1704                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1706                                  $form->{decimalplaces}
 
1708                                $form->{decimalplaces},
 
1712       foreach my $item (@ergebnisse) {
 
1713         $form->{ "$key" . "gl" . "$item" } =
 
1714           $form->format_amount($myconfig,
 
1715                                $form->round_amount(
 
1716                                  ( $form->{ "$key" . "$item" } /
 
1717                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1719                                  $form->{decimalplaces}
 
1721                                $form->{decimalplaces},
 
1726     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1727       foreach $category (@categories) {
 
1728         if (defined($form->{$category}{$key})) {
 
1729           $form->{ "$key" . "gk" . "$category" } =
 
1730             $form->format_amount($myconfig,
 
1731                                  $form->round_amount(
 
1732                                    ($form->{$category}{$key} /
 
1733                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1735                                    $form->{decimalplaces}
 
1737                                  $form->{decimalplaces},
 
1741       foreach my $item (@ergebnisse) {
 
1742         $form->{ "$key" . "gk" . "$item" } =
 
1743           $form->format_amount($myconfig,
 
1744                                $form->round_amount(
 
1745                                    ($form->{ "$key" . "$item" } /
 
1746                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1748                                    $form->{decimalplaces}
 
1750                                $form->{decimalplaces},
 
1755     if ($form->{10}{$key} > 0) {
 
1756       foreach $category (@categories) {
 
1757         if (defined($form->{$category}{$key})) {
 
1758           $form->{ "$key" . "pk" . "$category" } =
 
1759             $form->format_amount(
 
1761                         $form->round_amount(
 
1762                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1763                           $form->{decimalplaces}
 
1765                         $form->{decimalplaces},
 
1769       foreach my $item (@ergebnisse) {
 
1770         $form->{ "$key" . "pk" . "$item" } =
 
1771           $form->format_amount($myconfig,
 
1772                                $form->round_amount(
 
1773                                                 ($form->{ "$key" . "$item" } /
 
1774                                                    $form->{10}{$key} * 100
 
1776                                                 $form->{decimalplaces}
 
1778                                $form->{decimalplaces},
 
1783     if ($form->{4}{$key} > 0) {
 
1784       foreach $category (@categories) {
 
1785         if (defined($form->{$category}{$key})) {
 
1786           $form->{ "$key" . "auf" . "$category" } =
 
1787             $form->format_amount(
 
1789                          $form->round_amount(
 
1790                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1791                            $form->{decimalplaces}
 
1793                          $form->{decimalplaces},
 
1797       foreach my $item (@ergebnisse) {
 
1798         $form->{ "$key" . "auf" . "$item" } =
 
1799           $form->format_amount($myconfig,
 
1800                                $form->round_amount(
 
1801                                                 ($form->{ "$key" . "$item" } /
 
1802                                                    $form->{4}{$key} * 100
 
1804                                                 $form->{decimalplaces}
 
1806                                $form->{decimalplaces},
 
1811     foreach my $item (@ergebnisse) {
 
1812       $form->{ "$key" . "$item" } =
 
1813         $form->format_amount($myconfig,
 
1814                              $form->round_amount($form->{ "$key" . "$item" },
 
1815                                                  $form->{decimalplaces}
 
1817                              $form->{decimalplaces},
 
1824   $main::lxdebug->leave_sub();
 
1827 sub income_statement {
 
1828   $main::lxdebug->enter_sub();
 
1830   my ($self, $myconfig, $form) = @_;
 
1832   # connect to database
 
1833   my $dbh = $form->dbconnect($myconfig);
 
1835   my $last_period          = 0;
 
1836   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1837   my @categories_ausgaben  =
 
1838     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);
 
1840   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1842   $form->{decimalplaces} *= 1;
 
1846   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1850   foreach my $item (@categories_einnahmen) {
 
1851     $form->{"eur${item}"} =
 
1852       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1853     $form->{"sumeura"} += $form->{$item};
 
1855   foreach my $item (@categories_ausgaben) {
 
1856     $form->{"eur${item}"} =
 
1857       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1858     $form->{"sumeurb"} += $form->{$item};
 
1861   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1863   foreach my $item (@ergebnisse) {
 
1865       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1867   $main::lxdebug->leave_sub();
 
1870 sub erfolgsrechnung {
 
1871   $main::lxdebug->enter_sub();
 
1873   my ($self, $myconfig, $form) = @_;
 
1874   $form->{company} = $::instance_conf->get_company;
 
1875   $form->{address} = $::instance_conf->get_address;
 
1876   $form->{fromdate} = DateTime->new(year => 2000, month => 1, day => 1)->to_kivitendo unless $form->{fromdate};
 
1877   $form->{todate} = $form->current_date(%{$myconfig}) unless $form->{todate};
 
1879   my %categories = (I => "ERTRAG", E => "AUFWAND");
 
1880   my $fromdate = conv_dateq($form->{fromdate});
 
1881   my $todate = conv_dateq($form->{todate});
 
1885   foreach my $category ('I', 'E') {
 
1887       name => $categories{$category},
 
1889       accounts => get_accounts_ch($category),
 
1891     foreach my $account (@{$category{accounts}}) {
 
1892       $account->{total} += ($account->{category} eq $category ? 1 : -1) * get_total_ch($account->{id}, $fromdate, $todate);
 
1893       $category{total} += $account->{total};
 
1894       $account->{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $account->{total}), 2);
 
1896     $form->{total} += $category{total};
 
1897     $category{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $category{total}), 2);
 
1898     push(@{$form->{categories}}, \%category);
 
1900   $form->{total} = $form->format_amount($myconfig, $form->parse_amount($myconfig, $form->{total}), 2);
 
1902   $main::lxdebug->leave_sub();
 
1906 sub get_accounts_ch {
 
1907   $main::lxdebug->enter_sub();
 
1909   my ($category) = @_;
 
1912   if ($category eq 'I') {
 
1913     $inclusion = "AND pos_er = NULL OR pos_er > '0' AND pos_er <= '5'";
 
1914   } elsif ($category eq 'E') {
 
1915     $inclusion = "AND pos_er = NULL OR pos_er >= '6' AND pos_er < '100'";
 
1921     SELECT id, accno, description, category
 
1923     WHERE category = ? $inclusion
 
1926   my $accounts = _query($query, $category);
 
1928   $main::lxdebug->leave_sub();
 
1933   $main::lxdebug->enter_sub();
 
1935   my ($chart_id, $fromdate, $todate) = @_;
 
1944   $total += _query($query, $chart_id, $fromdate, $todate)->[0]->{sum};
 
1946   $main::lxdebug->leave_sub();
 
1950 sub _query {return selectall_hashref_query($::form, $::form->get_standard_dbh, @_);}