1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 #  Contributors: Benjamin Lee <benjaminlee@consultant.com>
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # backend code for reports
 
  33 #======================================================================
 
  39 use List::Util qw(sum);
 
  44 # new implementation of balance sheet
 
  47 # stuff missing from the original implementation:
 
  50 # - proper testing for heading charts
 
  51 # - transmission from $form to TMPL realm is not as clear as i'd like
 
  53 sub get_openbalance_date {
 
  54   my ($closedto, $target) = map { $::locale->parse_date_to_object(\%::myconfig, $_) } @_;
 
  56   return unless $closedto;
 
  58   $closedto->subtract(years => 1) while ($target - $closedto)->is_negative;
 
  59   $closedto->add(days => 1);
 
  60   return $::locale->format_date(\%::myconfig, $closedto);
 
  64   $main::lxdebug->enter_sub();
 
  66   my $myconfig = \%main::myconfig;
 
  67   my $form     = $main::form;
 
  68   my $dbh      = $::form->get_standard_dbh;
 
  71   my @categories  = qw(A C L Q);
 
  73   # if there are any dates construct a where
 
  74   if ($form->{asofdate}) {
 
  75     $form->{period} = $form->{this_period} = conv_dateq($form->{asofdate});
 
  78   # get end of financial year and convert to Date format
 
  79   my ($closedto) = selectfirst_array_query($form, $dbh, 'SELECT closedto FROM defaults');
 
  81   # get date of last opening balance
 
  82   my $startdate = get_openbalance_date($closedto, $form->{asofdate});
 
  84   get_accounts($dbh, $last_period, $startdate, $form->{asofdate}, $form, \@categories);
 
  86   # if there are any compare dates
 
  87   if ($form->{compareasofdate}) {
 
  90     $startdate = get_openbalance_date($closedto, $form->{compareasofdate});
 
  92     get_accounts($dbh, $last_period, $startdate, $form->{compareasofdate}, $form, \@categories);
 
  93     $form->{last_period} = conv_dateq($form->{compareasofdate});
 
  96   # now we got $form->{A}{accno}{ }    assets
 
  97   # and $form->{L}{accno}{ }           liabilities
 
  98   # and $form->{Q}{accno}{ }           equity
 
  99   # build asset accounts
 
 101   my %account = ('A' => { 'ml'     => -1 },
 
 102                  'L' => { 'ml'     =>  1 },
 
 103                  'Q' => { 'ml'     =>  1 });
 
 107   foreach my $category (grep { !/C/ } @categories) {
 
 109     $TMPL_DATA->{$category} = [];
 
 110     my $ml  = $account{$category}{ml};
 
 112     foreach my $key (sort keys %{ $form->{$category} }) {
 
 114       my $row = { %{ $form->{$category}{$key} } };
 
 116       # if charttype "heading" - calculate this entry, start a new batch of charts belonging to this heading and skip the rest bo the loop
 
 117       # header charts are not real charts. start a sub aggregation with them, but don't calculate anything with them
 
 118       if ($row->{charttype} eq "H") {
 
 119         if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 120           $row->{subdescription} = $account{$category}{subdescription};
 
 121           $row->{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 122           $row->{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 125         $row->{subheader} = 1;
 
 126         $account{$category}{subthis}        = $row->{this};
 
 127         $account{$category}{sublast}        = $row->{last};
 
 128         $account{$category}{subdescription} = $row->{description};
 
 129         $account{$category}{subtotal} = 1;
 
 134         next unless $form->{l_heading};
 
 137       for my $period (qw(this last)) {
 
 138         next if ($period eq 'last' && !$last_period);
 
 140         $row->{$period}                    *= $ml;
 
 143       push @{ $TMPL_DATA->{$category} }, $row;
 
 146     # resolve heading/subtotal
 
 147     if ($account{$category}{subtotal} && $form->{l_subtotal}) {
 
 148       $TMPL_DATA->{$category}[-1]{subdescription} = $account{$category}{subdescription};
 
 149       $TMPL_DATA->{$category}[-1]{this}           = $account{$category}{subthis} * $ml;                   # format: $dec, $dash
 
 150       $TMPL_DATA->{$category}[-1]{last}           = $account{$category}{sublast} * $ml if $last_period;   # format: $dec, $dash
 
 153     $TMPL_DATA->{total}{$category}{this} = sum map { $_->{this} } @{ $TMPL_DATA->{$category} };
 
 154     $TMPL_DATA->{total}{$category}{last} = sum map { $_->{last} } @{ $TMPL_DATA->{$category} };
 
 157   for my $period (qw(this last)) {
 
 158     next if ($period eq 'last' && !$last_period);
 
 160     $form->{E}{$period}             = $TMPL_DATA->{total}{A}{$period} - $TMPL_DATA->{total}{L}{$period} - $TMPL_DATA->{total}{Q}{$period};
 
 161     $TMPL_DATA->{total}{Q}{$period}     += $form->{E}{$period};
 
 162     $TMPL_DATA->{total}{$period}    = $TMPL_DATA->{total}{L}{$period} + $TMPL_DATA->{total}{Q}{$period};
 
 164     $form->{E}{description}='nicht verbuchter Gewinn/Verlust';
 
 165   push @{ $TMPL_DATA->{Q} }, $form->{E};
 
 167   $main::lxdebug->leave_sub();
 
 173   $main::lxdebug->enter_sub();
 
 175   my ($dbh, $last_period, $fromdate, $todate, $form, $categories) = @_;
 
 177   my ($null, $department_id) = split /--/, $form->{department};
 
 181   my $dpt_where_without_arapgl = '';
 
 188   my $dec = $form->{decimalplaces};
 
 190   my $category = qq| AND (| . join(" OR ", map({ "(c.category = " . $dbh->quote($_) . ")" } @{$categories})) . qq|) |;
 
 194     qq|SELECT c.accno, c.description, c.category
 
 196        WHERE (c.charttype = 'H')
 
 200   $sth = prepare_execute_query($form, $dbh, $query);
 
 202   my @headingaccounts = ();
 
 203   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 204     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
 
 205       "$ref->{description}";
 
 206     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
 
 207     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
 
 209     push @headingaccounts, $ref->{accno};
 
 214   # filter for opening and closing bookings
 
 215   # if l_ob is selected l_cb is always ignored
 
 216   if ( $last_period ) {
 
 217     # ob/cb-settings for "compared to" balance
 
 218     if ( $form->{l_ob_compared} ) {
 
 219       $where .= ' AND ac.ob_transaction is true  '
 
 220     } elsif ( not $form->{l_cb_compared} ) {
 
 221       $where .= ' AND ac.cb_transaction is false ';
 
 224     # ob/cb-settings for "as of" balance
 
 225     if ( $form->{l_ob} ) {
 
 226       $where .= ' AND ac.ob_transaction is true  '
 
 227     } elsif ( not $form->{l_cb} ) {
 
 228       $where .= ' AND ac.cb_transaction is false ';
 
 234     $fromdate = conv_dateq($fromdate);
 
 235     if ($form->{method} eq 'cash') {
 
 236       $subwhere .= " AND (transdate >= $fromdate)";
 
 237       $glwhere = " AND (ac.transdate >= $fromdate)";
 
 239       $where .= " AND (ac.transdate >= $fromdate)";
 
 244     $todate = conv_dateq($todate);
 
 245     $where    .= " AND (ac.transdate <= $todate)";
 
 246     $subwhere .= " AND (transdate <= $todate)";
 
 249   if ($department_id) {
 
 250     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
 253   if ($form->{project_id}) {
 
 254     # Diese Bedingung wird derzeit niemals wahr sein, da man in Bericht->Bilanz keine
 
 255     # Projekte auswählen kann
 
 256     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 259   if ($form->{method} eq 'cash') {
 
 261       qq|SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 263          JOIN chart c ON (c.id = ac.chart_id)
 
 264          JOIN ar a ON (a.id = ac.trans_id)
 
 272                WHERE (a.chart_link LIKE '%AR_paid%')
 
 276          GROUP BY c.accno, c.description, c.category
 
 280          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 282          JOIN chart c ON (c.id = ac.chart_id)
 
 283          JOIN ap a ON (a.id = ac.trans_id)
 
 291                WHERE (a.chart_link LIKE '%AP_paid%')
 
 295          GROUP BY c.accno, c.description, c.category
 
 299          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 301          JOIN chart c ON (c.id = ac.chart_id)
 
 302          JOIN gl a ON (a.id = ac.trans_id)
 
 307              AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 309          GROUP BY c.accno, c.description, c.category |;
 
 311     if ($form->{project_id}) {
 
 312       # s.o. keine Projektauswahl in Bilanz
 
 317          SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 319          JOIN ar a ON (a.id = ac.trans_id)
 
 320          JOIN parts p ON (ac.parts_id = p.id)
 
 321          JOIN chart c on (p.income_accno_id = c.id)
 
 322          -- use transdate from subwhere
 
 323          WHERE (c.category = 'I')
 
 330                WHERE (a.chart_link LIKE '%AR_paid%')
 
 334          GROUP BY c.accno, c.description, c.category
 
 338          SELECT c.accno AS accno, SUM(ac.sellprice) AS amount, c.description AS description, c.category
 
 340          JOIN ap a ON (a.id = ac.trans_id)
 
 341          JOIN parts p ON (ac.parts_id = p.id)
 
 342          JOIN chart c on (p.expense_accno_id = c.id)
 
 343          WHERE (c.category = 'E')
 
 350                WHERE a.chart_link LIKE '%AP_paid%'
 
 354          GROUP BY c.accno, c.description, c.category |;
 
 357   } else {                      # if ($form->{method} eq 'cash')
 
 358     if ($department_id) {
 
 359       $dpt_where = qq| AND a.department_id = | . conv_i($department_id);
 
 360       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 361                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 362                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 366       SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 368       JOIN chart c ON (c.id = ac.chart_id)
 
 370         $dpt_where_without_arapgl
 
 373       GROUP BY c.accno, c.description, c.category |;
 
 375     if ($form->{project_id}) {
 
 376       # s.o. keine Projektauswahl in Bilanz
 
 380       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 382       JOIN ar a ON (a.id = ac.trans_id)
 
 383       JOIN parts p ON (ac.parts_id = p.id)
 
 384       JOIN chart c on (p.income_accno_id = c.id)
 
 385       -- use transdate from subwhere
 
 386       WHERE (c.category = 'I')
 
 390       GROUP BY c.accno, c.description, c.category
 
 394       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount, c.description AS description, c.category
 
 396       JOIN ap a ON (a.id = ac.trans_id)
 
 397       JOIN parts p ON (ac.parts_id = p.id)
 
 398       JOIN chart c on (p.expense_accno_id = c.id)
 
 399       WHERE (c.category = 'E')
 
 403       GROUP BY c.accno, c.description, c.category |;
 
 411   $sth = prepare_execute_query($form, $dbh, $query);
 
 413   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 415     if ($ref->{category} eq 'C') {
 
 416       $ref->{category} = 'A';
 
 419     # get last heading account
 
 420     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
 424         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
 
 426         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
 
 430     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
 
 431     $form->{ $ref->{category} }{ $ref->{accno} }{description} = $ref->{description};
 
 432     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
 
 435       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
 
 437       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
 
 442   # remove accounts with zero balance
 
 443   foreach $category (@{$categories}) {
 
 444     foreach $accno (keys %{ $form->{$category} }) {
 
 445       $form->{$category}{$accno}{last} = $form->round_amount($form->{$category}{$accno}{last}, $dec);
 
 446       $form->{$category}{$accno}{this} = $form->round_amount($form->{$category}{$accno}{this}, $dec);
 
 448       delete $form->{$category}{$accno}
 
 449         if (   $form->{$category}{$accno}{this} == 0
 
 450             && $form->{$category}{$accno}{last} == 0);
 
 454   $main::lxdebug->leave_sub();
 
 458   $main::lxdebug->enter_sub();
 
 460   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
 
 462   my ($null, $department_id) = split /--/, $form->{department};
 
 466   my $dpt_where_without_arapgl;
 
 475   $where .= ' AND ac.cb_transaction is false ' unless $form->{l_cb};
 
 478     $fromdate = conv_dateq($fromdate);
 
 479     if ($form->{method} eq 'cash') {
 
 480       $subwhere .= " AND (transdate    >= $fromdate)";
 
 481       $glwhere   = " AND (ac.transdate >= $fromdate)";
 
 482       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 483       $inwhere   = " AND (acc.transdate >= $fromdate)";
 
 485       $where    .= " AND (ac.transdate >= $fromdate)";
 
 490     $todate = conv_dateq($todate);
 
 491     $subwhere   .= " AND (transdate    <= $todate)";
 
 492     $where      .= " AND (ac.transdate <= $todate)";
 
 493     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 494     $inwhere    .= " AND (acc.transdate <= $todate)";
 
 497   if ($department_id) {
 
 498     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 501   if ($form->{project_id}) {
 
 502     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
 
 506 # GUV patch by Ronny Rentner (Bug 1190)
 
 508 # GUV IST-Versteuerung
 
 510 # Alle tatsaechlichen _Zahlungseingaenge_
 
 511 # im Zeitraum erfassen
 
 512 # (Teilzahlungen werden prozentual auf verschiedene Steuern aufgeteilt)
 
 516   if ($form->{method} eq 'cash') {
 
 519        SELECT SUM( ac.amount * CASE WHEN COALESCE((SELECT amount FROM ar WHERE id = ac.trans_id), 0) != 0 THEN
 
 520             /* ar amount is not zero, so we can divide by amount   */
 
 521                     (SELECT SUM(acc.amount) * -1
 
 524                      AND acc.trans_id = ac.trans_id
 
 525                      AND acc.chart_link LIKE '%AR_paid%')
 
 526                   / (SELECT amount FROM ar WHERE id = ac.trans_id)
 
 528             /* 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 */
 
 530                 ) AS amount, c.$category
 
 532        LEFT JOIN chart c ON (c.id  = ac.chart_id)
 
 533        LEFT JOIN ar      ON (ar.id = ac.trans_id)
 
 534        LEFT JOIN taxkeys tk ON (tk.id = (
 
 535                                   SELECT id FROM taxkeys
 
 536                                   WHERE chart_id = ac.chart_id
 
 537                                   AND startdate <= COALESCE(ar.deliverydate,ar.transdate)
 
 538                                   ORDER BY startdate DESC LIMIT 1
 
 541       WHERE ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE 1=1 $subwhere)
 
 546        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 548          JOIN chart c ON (c.id = ac.chart_id)
 
 549          JOIN ar a ON (a.id = ac.trans_id)
 
 550          WHERE $where $dpt_where
 
 551            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 557          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 559          JOIN chart c ON (c.id = ac.chart_id)
 
 560          JOIN ap a ON (a.id = ac.trans_id)
 
 561          WHERE $where $dpt_where
 
 562            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 568          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 570          JOIN chart c ON (c.id = ac.chart_id)
 
 571          JOIN gl a ON (a.id = ac.trans_id)
 
 572          WHERE $where $dpt_where $glwhere
 
 573            AND NOT ((ac.chart_link = 'AR') OR (ac.chart_link = 'AP'))
 
 578     if ($form->{project_id}) {
 
 582          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 584          JOIN ar a ON (a.id = ac.trans_id)
 
 585          JOIN parts p ON (ac.parts_id = p.id)
 
 586          JOIN chart c on (p.income_accno_id = c.id)
 
 587          WHERE (c.category = 'I') $prwhere $dpt_where
 
 588            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AR_paid%') $subwhere)
 
 594          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 596          JOIN ap a ON (a.id = ac.trans_id)
 
 597          JOIN parts p ON (ac.parts_id = p.id)
 
 598          JOIN chart c on (p.expense_accno_id = c.id)
 
 599          WHERE (c.category = 'E') $prwhere $dpt_where
 
 600            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a WHERE (a.chart_link LIKE '%AP_paid%') $subwhere)
 
 606   } else {                      # if ($form->{method} eq 'cash')
 
 607     if ($department_id) {
 
 608       $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 609       $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 610                                                    (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 611                                                    (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 615         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 617         JOIN chart c ON (c.id = ac.chart_id)
 
 619           $dpt_where_without_arapgl
 
 621         GROUP BY c.$category |;
 
 623     if ($form->{project_id}) {
 
 627         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 629         JOIN ar a ON (a.id = ac.trans_id)
 
 630         JOIN parts p ON (ac.parts_id = p.id)
 
 631         JOIN chart c on (p.income_accno_id = c.id)
 
 632         WHERE (c.category = 'I')
 
 640         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 642         JOIN ap a ON (a.id = ac.trans_id)
 
 643         JOIN parts p ON (ac.parts_id = p.id)
 
 644         JOIN chart c on (p.expense_accno_id = c.id)
 
 645         WHERE (c.category = 'E')
 
 649         GROUP BY c.$category |;
 
 657   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
 
 658     if ($category eq "pos_bwa") {
 
 660         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 662         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 665       $form->{ $ref->{$category} } += $ref->{amount};
 
 669   $main::lxdebug->leave_sub();
 
 673   $main::lxdebug->enter_sub();
 
 675   my ($self, $myconfig, $form, %options) = @_;
 
 677   my $dbh = $form->dbconnect($myconfig);
 
 679   my ($query, $sth, $ref);
 
 682   my ($null, $department_id) = split /--/, $form->{department};
 
 683   my @headingaccounts = ();
 
 685   my $dpt_where_without_arapgl;
 
 689   my $invwhere = $where;
 
 691   if ($department_id) {
 
 692     $dpt_where = qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 693     $dpt_where_without_arapgl = qq| AND COALESCE((SELECT department_id FROM ar WHERE ar.id=ac.trans_id),
 
 694                                                  (SELECT department_id FROM gl WHERE gl.id=ac.trans_id),
 
 695                                                  (SELECT department_id FROM ap WHERE ap.id=ac.trans_id)) = | . conv_i($department_id);
 
 698   # project_id only applies to getting transactions
 
 699   # it has nothing to do with a trial balance
 
 700   # but we use the same function to collect information
 
 702   if ($form->{project_id}) {
 
 703     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 706   my $acc_cash_where = "";
 
 707 #  my $ar_cash_where = "";
 
 708 #  my $ap_cash_where = "";
 
 711   if ($form->{method} eq "cash") {
 
 713       qq| AND (ac.trans_id IN (
 
 716             WHERE datepaid >= '$form->{fromdate}'
 
 717               AND datepaid <= '$form->{todate}'
 
 723             WHERE datepaid >= '$form->{fromdate}'
 
 724               AND datepaid <= '$form->{todate}'
 
 730             WHERE transdate >= '$form->{fromdate}'
 
 731               AND transdate <= '$form->{todate}'
 
 733 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 736   if ($options{beginning_balances}) {
 
 737     foreach my $prefix (qw(from to)) {
 
 738       next if ($form->{"${prefix}date"});
 
 740       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 741       $query      = qq|SELECT ${min_max}(transdate)
 
 744                          $dpt_where_without_arapgl
 
 746       ($form->{"${prefix}date"}) = selectfirst_array_query($form, $dbh, $query);
 
 749     # get beginning balances
 
 751       qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
 
 753           LEFT JOIN chart c ON (ac.chart_id = c.id)
 
 754           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 755             $dpt_where_without_arapgl
 
 757           GROUP BY c.accno, c.category, c.description |;
 
 759     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 761     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 763       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 764         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 765         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 766         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 768         if ($ref->{amount} > 0) {
 
 769           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 771           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 773         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 782     qq|SELECT c.accno, c.description, c.category
 
 784        WHERE c.charttype = 'H'
 
 787   $sth = prepare_execute_query($form, $dbh, $query);
 
 789   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 790     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 791     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 792     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 794     push @headingaccounts, $ref->{accno};
 
 800   my $saldowhere    = " 1 = 1 ";
 
 801   my $sumwhere      = " 1 = 1 ";
 
 803   my $sumsubwhere   = '';
 
 804   my $saldosubwhere = '';
 
 805   my $glsaldowhere  = '';
 
 810   my ($fromdate, $todate);
 
 812   if ($form->{fromdate} || $form->{todate}) {
 
 813     if ($form->{fromdate}) {
 
 814       $fromdate = conv_dateq($form->{fromdate});
 
 815       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 816       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 817       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 818       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 819       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 820       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 821       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 822       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 824     if ($form->{todate}) {
 
 825       $todate = conv_dateq($form->{todate});
 
 826       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 827       $invwhere      .= " AND (a.transdate <= $todate)";
 
 828       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 829       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 830       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 831       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 832       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 833       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 837   if ($form->{method} eq "cash") {
 
 839       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) |;
 
 840     $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) |;
 
 842     $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) |;
 
 844     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 845     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 846     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 850        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 852        JOIN chart c ON (c.id = ac.chart_id)
 
 854          $dpt_where_without_arapgl
 
 856        GROUP BY c.accno, c.description, c.category |;
 
 858   if ($form->{project_id}) {
 
 860       -- add project transactions from invoice
 
 864       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 866       JOIN ar a ON (ac.trans_id = a.id)
 
 867       JOIN parts p ON (ac.parts_id = p.id)
 
 868       JOIN chart c ON (p.income_accno_id = c.id)
 
 872       GROUP BY c.accno, c.description, c.category
 
 876       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 878       JOIN ap a ON (ac.trans_id = a.id)
 
 879       JOIN parts p ON (ac.parts_id = p.id)
 
 880       JOIN chart c ON (p.expense_accno_id = c.id)
 
 884       GROUP BY c.accno, c.description, c.category
 
 888   $query .= qq| ORDER BY accno|;
 
 890   $sth = prepare_execute_query($form, $dbh, $query);
 
 892   # calculate the debit and credit in the period
 
 893   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 894     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 895     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 896     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 897     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 901   # prepare query for each account
 
 902   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 906          (SELECT SUM(ac.amount) * -1
 
 908           JOIN chart c ON (c.id = ac.chart_id)
 
 910             $dpt_where_without_arapgl
 
 913           AND (c.accno = ?)) AS debit,
 
 915          (SELECT SUM(ac.amount)
 
 917           JOIN chart c ON (c.id = ac.chart_id)
 
 919             $dpt_where_without_arapgl
 
 922           AND c.accno = ?) AS credit,
 
 923         (SELECT SUM(ac.amount)
 
 925          JOIN chart c ON (ac.chart_id = c.id)
 
 927            $dpt_where_without_arapgl
 
 929          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 931         (SELECT SUM(ac.amount)
 
 933          JOIN chart c ON (ac.chart_id = c.id)
 
 935            $dpt_where_without_arapgl
 
 938          AND c.accno = ?) AS sum_credit,
 
 940         (SELECT SUM(ac.amount)
 
 942          JOIN chart c ON (ac.chart_id = c.id)
 
 944            $dpt_where_without_arapgl
 
 947          AND c.accno = ?) AS sum_debit,
 
 949         (SELECT max(ac.transdate) FROM acc_trans ac
 
 950         JOIN chart c ON (ac.chart_id = c.id)
 
 952           $dpt_where_without_arapgl
 
 954         AND c.accno = ?) AS last_transaction
 
 959   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 961   if ($form->{project_id}) {
 
 962     # prepare query for each account
 
 965           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
 967            JOIN parts p ON (ac.parts_id = p.id)
 
 968            JOIN ap a ON (ac.trans_id = a.id)
 
 969            JOIN chart c ON (p.expense_accno_id = c.id)
 
 973            AND c.accno = ?) AS debit,
 
 975           (SELECT SUM(ac.sellprice * ac.qty)
 
 977            JOIN parts p ON (ac.parts_id = p.id)
 
 978            JOIN ar a ON (ac.trans_id = a.id)
 
 979            JOIN chart c ON (p.income_accno_id = c.id)
 
 983            AND c.accno = ?) AS credit,
 
 985         (SELECT SUM(ac.amount)
 
 987          JOIN chart c ON (ac.chart_id = c.id)
 
 989            $dpt_where_without_arapgl
 
 991          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 993         (SELECT SUM(ac.amount)
 
 995          JOIN chart c ON (ac.chart_id = c.id)
 
 997            $dpt_where_without_arapgl
 
1000          AND c.accno = ?) AS sum_credit,
 
1002         (SELECT SUM(ac.amount)
 
1004          JOIN chart c ON (ac.chart_id = c.id)
 
1006            $dpt_where_without_arapgl
 
1009          AND c.accno = ?) AS sum_debit,
 
1012         (SELECT max(ac.transdate) FROM acc_trans ac
 
1013         JOIN chart c ON (ac.chart_id = c.id)
 
1015           $dpt_where_without_arapgl
 
1017         AND c.accno = ?) AS last_transaction
 
1020     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
1024   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
1026   foreach my $accno (sort keys %trb) {
 
1029     $ref->{accno} = $accno;
 
1030     map { $ref->{$_} = $trb{$accno}{$_} }
 
1031       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
1033     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
1035     if ($trb{$accno}{charttype} eq 'A') {
 
1038       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1040       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
1041       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
1042       $last_transaction = "";
 
1043       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
1044         $ref->{debit}  += $debit;
 
1045         $ref->{credit} += $credit;
 
1047           $ref->{haben_saldo} += $saldo;
 
1049           $ref->{soll_saldo} += $saldo * -1;
 
1051         $ref->{last_transaction} = $last_transaction;
 
1052         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1053         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1057       if ($form->{project_id}) {
 
1060         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1062         ($debit, $credit) = (0, 0);
 
1063         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1064           $ref->{debit}  += $debit;
 
1065           $ref->{credit} += $credit;
 
1067             $ref->{haben_saldo} += $saldo;
 
1069             $ref->{soll_saldo} += $saldo * -1;
 
1071           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1072           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1074         $project_drcr->finish;
 
1077       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1078       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1080       if ($ref->{haben_saldo} != 0) {
 
1081         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1082         if ($ref->{haben_saldo} < 0) {
 
1083           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1084           $ref->{haben_saldo} = 0;
 
1087         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1088         if ($ref->{soll_saldo} < 0) {
 
1089           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1090           $ref->{soll_saldo} = 0;
 
1093       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1094       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1095       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1096       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1101     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1102     $accno = pop @accno;
 
1104       $trb{$accno}{debit}  += $ref->{debit};
 
1105       $trb{$accno}{credit} += $ref->{credit};
 
1106       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1107       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1108       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1109       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1112     push @{ $form->{TB} }, $ref;
 
1118   # debits and credits for headings
 
1119   foreach my $accno (@headingaccounts) {
 
1120     foreach $ref (@{ $form->{TB} }) {
 
1121       if ($accno eq $ref->{accno}) {
 
1122         $ref->{debit}           = $trb{$accno}{debit};
 
1123         $ref->{credit}          = $trb{$accno}{credit};
 
1124         $ref->{soll_saldo}      = $trb{$accno}{soll_saldo};
 
1125         $ref->{haben_saldo}     = $trb{$accno}{haben_saldo};
 
1126         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
 
1127         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};
 
1132   $main::lxdebug->leave_sub();
 
1136   $main::lxdebug->enter_sub();
 
1137   my ($self, $dbh, $form) = @_;
 
1138   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
 
1139   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
 
1140   my $sth =  $dbh->prepare($query);
 
1141   while(my $ref = $sth->fetchrow_hashref()) {
 
1142     $ref->{invnumer} =~ s/Storno zu //g;
 
1143     $form->{storno}{$ref->{invnumber}} = 1;
 
1145   $main::lxdebug->leave_sub();
 
1149   $main::lxdebug->enter_sub();
 
1151   my ($self, $myconfig, $form) = @_;
 
1153   # connect to database
 
1154   my $dbh     = $form->dbconnect($myconfig);
 
1156   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
 
1158   # falls customer ziehen wir die offene forderungsliste
 
1159   # anderfalls für die lieferanten die offenen verbindlichkeitne
 
1160   if ($form->{ct} eq "customer") {
 
1173   $ct_id = "${ct}_id";
 
1175   # erweiterung um einen freien zeitraum oder einen stichtag
 
1176   # mit entsprechender altersstrukturliste (s.a. Bug 1842)
 
1177   # eine neue variable an der oberfläche eingeführt, somit ist
 
1178   # todate == freier zeitrau und fordate == stichtag
 
1179   # duedate_where == nur fällige rechnungen anzeigen
 
1181   my ($review_of_aging_list, $todate, $fromdate, $fromwhere, $fordate,
 
1184   if ($form->{reporttype} eq 'custom') {  # altersstrukturliste, nur fällige
 
1186     # explizit rausschmeissen was man für diesen bericht nicht braucht
 
1187     delete $form->{fromdate};
 
1188     delete $form->{todate};
 
1190     # an der oberfläche ist das tagesaktuelle datum vorausgewählt
 
1191     # falls es dennoch per Benutzereingabe gelöscht wird, lieber wieder vorbelegen
 
1192     # ferner muss für die spätere DB-Abfrage muss todate gesetzt sein.
 
1193     $form->{fordate}  = $form->current_date($myconfig) unless ($form->{fordate});
 
1194     $fordate          = conv_dateq($form->{fordate});
 
1197     if ($form->{review_of_aging_list}) { # falls die liste leer ist, alles anzeigen
 
1198       if ($form->{review_of_aging_list} =~ m "-") {             # ..  periode von bis
 
1199         my @period = split(/-/, $form->{review_of_aging_list}); # ... von periode bis periode
 
1200         $review_of_aging_list = " AND $period[0] <  (date $fordate) - duedate
 
1201                                   AND (date $fordate) - duedate  < $period[1]";
 
1203         $form->{review_of_aging_list} =~ s/[^0-9]//g;   # größer 120 das substitute ist nur für das '>' zeichen
 
1204         $review_of_aging_list = " AND $form->{review_of_aging_list} < (date $fordate) - duedate";
 
1207     $duedate_where = " AND (date $fordate) - duedate >= 0 ";
 
1208   } else {  # freier zeitraum, nur rechnungsdatum und OHNE review_of_aging_list
 
1209     $form->{todate}  = $form->current_date($myconfig) unless ($form->{todate});
 
1210     $todate = conv_dateq($form->{todate});
 
1211     $fromdate = conv_dateq($form->{fromdate});
 
1212     $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
 
1214   my $where = " 1 = 1 ";
 
1217   if ($form->{$ct_id}) {
 
1218     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
 
1219   } elsif ($form->{ $form->{ct} }) {
 
1220     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
 
1225   if ($form->{department}) {
 
1226     my ($null, $department_id) = split /--/, $form->{department};
 
1227     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
 
1228     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1229     $where_dpt = qq| AND (${arap}.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1233     SELECT ${ct}.id AS ctid, ${ct}.name,
 
1234       street, zipcode, city, country, contact, email,
 
1235       phone as customerphone, fax as customerfax, ${ct}number,
 
1236       "invnumber", "transdate",
 
1237       (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",
 
1238       "duedate", invoice, ${arap}.id, date_part('days', now() - duedate) as overduedays,
 
1241        WHERE (${arap}.curr = exchangerate.curr)
 
1242          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
 
1244     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
 
1245       AND NOT COALESCE (${arap}.storno, 'f')
 
1246       AND (${arap}.${ct}_id = ${ct}.id)
 
1249       AND (transdate <= (date $todate) $fromwhere )
 
1250       $review_of_aging_list
 
1252     ORDER BY ctid, transdate, invnumber |;
 
1254   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1256   # select outstanding vendors or customers, depends on $ct
 
1258     qq|SELECT DISTINCT ct.id, ct.name
 
1259        FROM $ct ct, $arap a
 
1262          AND (a.${ct_id} = ct.id)
 
1263          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
 
1264          AND (a.transdate <= $todate $fromwhere)
 
1267   my $sth = prepare_execute_query($form, $dbh, $query);
 
1270   # for each company that has some stuff outstanding
 
1271   while (my ($id) = $sth->fetchrow_array) {
 
1272     do_statement($form, $sth_details, $q_details, $id);
 
1274     while (my $ref = $sth_details->fetchrow_hashref("NAME_lc")) {
 
1275       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
 
1276       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
 
1277       push @{ $form->{AG} }, $ref;
 
1280     $sth_details->finish;
 
1289   $main::lxdebug->leave_sub();
 
1293   $main::lxdebug->enter_sub();
 
1295   my ($self, $myconfig, $form) = @_;
 
1297   # connect to database
 
1298   my $dbh = $form->dbconnect($myconfig);
 
1300   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1303     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1306   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1307     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1310   $main::lxdebug->leave_sub();
 
1314   $main::lxdebug->enter_sub();
 
1316   my ($self, $myconfig, $form) = @_;
 
1318   # connect to database
 
1319   my $dbh = $form->dbconnect($myconfig);
 
1321   my ($null, $department_id) = split /--/, $form->{department};
 
1324   my $where = "1 = 1";
 
1326   if ($department_id) {
 
1327     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1332   if ($form->{accno}) {
 
1333     $accno = $form->{accno};
 
1334     $rate  = $form->{"$form->{accno}_rate"};
 
1335     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1341   if ($form->{db} eq 'ar') {
 
1342     $table = "customer";
 
1349   my $arap = lc($ARAP);
 
1351   my $transdate = "a.transdate";
 
1353   if ($form->{method} eq 'cash') {
 
1354     $transdate = "a.datepaid";
 
1356     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1363           WHERE (a.chart_link LIKE '%${ARAP}_paid%')
 
1364           AND (transdate <= $todate)
 
1369   # if there are any dates construct a where
 
1370   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1371   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1373   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1375   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1376   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1379       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1380           ac.amount * $ml AS tax
 
1382          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1383          JOIN chart ch ON (ch.id = ac.chart_id)
 
1384          JOIN $table n ON (n.id = a.${table}_id)
 
1388            AND (a.invoice = '0')
 
1392          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1393            i.sellprice * i.qty * $rate * $ml AS tax
 
1395          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1396          JOIN chart ch ON (ch.id = ac.chart_id)
 
1397          JOIN $table n ON (n.id = a.${table}_id)
 
1398          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1399          JOIN invoice i ON (i.trans_id = a.id)
 
1403            AND (a.invoice = '1')
 
1404          ORDER BY $sortorder|;
 
1406   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1410   $main::lxdebug->leave_sub();
 
1413 sub paymentaccounts {
 
1414   $main::lxdebug->enter_sub();
 
1416   my ($self, $myconfig, $form) = @_;
 
1418   # connect to database, turn AutoCommit off
 
1419   my $dbh = $form->dbconnect_noauto($myconfig);
 
1421   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1423   # get A(R|P)_paid accounts
 
1425     qq|SELECT accno, description
 
1427        WHERE link LIKE '%${ARAP}_paid%'|;
 
1428   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1432   $main::lxdebug->leave_sub();
 
1436   $main::lxdebug->enter_sub();
 
1438   my ($self, $myconfig, $form) = @_;
 
1440   # connect to database, turn AutoCommit off
 
1441   my $dbh = $form->dbconnect_noauto($myconfig);
 
1446   if ($form->{db} eq 'ar') {
 
1447     $table = 'customer';
 
1458   if ($form->{department_id}) {
 
1459     $where = qq| AND (a.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1462   if ($form->{fromdate}) {
 
1463     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1465   if ($form->{todate}) {
 
1466     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1468   if (!$form->{fx_transaction}) {
 
1469     $where .= " AND ac.fx_transaction = '0'";
 
1474   if ($form->{reference}) {
 
1475     $reference = $dbh->quote('%' . $form->{reference} . '%');
 
1476     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1477     $reference = " AND (a.reference LIKE $reference)";
 
1479   if ($form->{source}) {
 
1480     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
 
1482   if ($form->{memo}) {
 
1483     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
 
1486   my %sort_columns =  (
 
1487     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1488     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1489     'name'         => [ qw(lower_name transdate)                 ],
 
1490     'source'       => [ qw(lower_source)                         ],
 
1491     'memo'         => [ qw(lower_memo)                           ],
 
1493   my %lowered_columns =  (
 
1494     'invnumber'       => { 'gl' => 'a.reference',   'arap' => 'a.invnumber', },
 
1495     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1496     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1497     'name'            => { 'gl' => 'a.description', 'arap' => 'c.name',      },
 
1500   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1501   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1502   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1505   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1506   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1507     next if ($spec !~ m/^lower_(.*)$/);
 
1510     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1513   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1514   $sth = prepare_query($form, $dbh, $query);
 
1517       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1518            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1519            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1520            $columns_for_sorting{arap}
 
1522          JOIN $arap a ON (ac.trans_id = a.id)
 
1523          JOIN $table c ON (c.id = a.${table}_id)
 
1524          WHERE (ac.chart_id = ?)
 
1530          SELECT a.description, a.reference, NULL AS ordnumber,
 
1531            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1532            '0' as invoice, a.id, ac.memo, 'gl' AS module
 
1533            $columns_for_sorting{gl}
 
1535          JOIN gl a ON (a.id = ac.trans_id)
 
1536          WHERE (ac.chart_id = ?)
 
1539            AND (ac.amount * $ml) > 0
 
1541          ORDER BY $sortorder|;
 
1542   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1546   # cycle through each id
 
1547   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1548     do_statement($form, $sth, $query, $accno);
 
1549     my $ref = $sth->fetchrow_hashref();
 
1550     push(@{ $form->{PR} }, $ref);
 
1553     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1555     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1556     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1557       push(@{ $form->{ $ref->{id} } }, $pr);
 
1559     $sth_details->finish();
 
1564   $main::lxdebug->leave_sub();
 
1568   $main::lxdebug->enter_sub();
 
1570   my ($self, $myconfig, $form) = @_;
 
1572   # connect to database
 
1573   my $dbh = $form->dbconnect($myconfig);
 
1575   my $last_period = 0;
 
1578     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);
 
1580   $form->{decimalplaces} *= 1;
 
1582   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1584   # if there are any compare dates
 
1586   if ($form->{fromdate} || $form->{todate}) {
 
1588     if ($form->{fromdate}) {
 
1589       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1592       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1595     my $kummfromdate = $form->{comparefromdate};
 
1596     my $kummtodate   = $form->{comparetodate};
 
1597     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1600   my @periods        = qw(jetzt kumm);
 
1601   my @gesamtleistung = qw(1 3);
 
1602   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 20);
 
1604     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1606   foreach my $key (@periods) {
 
1607     $form->{ "$key" . "gesamtleistung" } = 0;
 
1608     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1610     foreach $category (@categories) {
 
1612       if (defined($form->{$category}{$key})) {
 
1613         $form->{"$key$category"} =
 
1614           $form->format_amount($myconfig,
 
1615                                $form->round_amount($form->{$category}{$key}, 2
 
1617                                $form->{decimalplaces},
 
1621     foreach my $item (@gesamtleistung) {
 
1622       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1624     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1626     foreach my $item (@gesamtkosten) {
 
1627       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1629     $form->{ "$key" . "rohertrag" } =
 
1630       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1631     $form->{ "$key" . "betriebrohertrag" } =
 
1632       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1633     $form->{ "$key" . "betriebsergebnis" } =
 
1634       $form->{ "$key" . "betriebrohertrag" } -
 
1635       $form->{ "$key" . "gesamtkosten" };
 
1636     $form->{ "$key" . "neutraleraufwand" } =
 
1637       $form->{19}{$key} + $form->{30}{$key} + $form->{31}{$key};
 
1638     $form->{ "$key" . "neutralerertrag" } =
 
1639       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1640     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1641       $form->{ "$key" . "betriebsergebnis" } -
 
1642       $form->{ "$key" . "neutraleraufwand" } +
 
1643       $form->{ "$key" . "neutralerertrag" };
 
1644     $form->{ "$key" . "ergebnis" } =
 
1645       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1647     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1648       foreach $category (@categories) {
 
1649         if (defined($form->{$category}{$key})) {
 
1650           $form->{ "$key" . "gl" . "$category" } =
 
1651             $form->format_amount(
 
1653                                $form->round_amount(
 
1654                                  ($form->{$category}{$key} /
 
1655                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1657                                  $form->{decimalplaces}
 
1659                                $form->{decimalplaces},
 
1663       foreach my $item (@ergebnisse) {
 
1664         $form->{ "$key" . "gl" . "$item" } =
 
1665           $form->format_amount($myconfig,
 
1666                                $form->round_amount(
 
1667                                  ( $form->{ "$key" . "$item" } /
 
1668                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1670                                  $form->{decimalplaces}
 
1672                                $form->{decimalplaces},
 
1677     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1678       foreach $category (@categories) {
 
1679         if (defined($form->{$category}{$key})) {
 
1680           $form->{ "$key" . "gk" . "$category" } =
 
1681             $form->format_amount($myconfig,
 
1682                                  $form->round_amount(
 
1683                                    ($form->{$category}{$key} /
 
1684                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1686                                    $form->{decimalplaces}
 
1688                                  $form->{decimalplaces},
 
1692       foreach my $item (@ergebnisse) {
 
1693         $form->{ "$key" . "gk" . "$item" } =
 
1694           $form->format_amount($myconfig,
 
1695                                $form->round_amount(
 
1696                                    ($form->{ "$key" . "$item" } /
 
1697                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1699                                    $form->{decimalplaces}
 
1701                                $form->{decimalplaces},
 
1706     if ($form->{10}{$key} > 0) {
 
1707       foreach $category (@categories) {
 
1708         if (defined($form->{$category}{$key})) {
 
1709           $form->{ "$key" . "pk" . "$category" } =
 
1710             $form->format_amount(
 
1712                         $form->round_amount(
 
1713                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1714                           $form->{decimalplaces}
 
1716                         $form->{decimalplaces},
 
1720       foreach my $item (@ergebnisse) {
 
1721         $form->{ "$key" . "pk" . "$item" } =
 
1722           $form->format_amount($myconfig,
 
1723                                $form->round_amount(
 
1724                                                 ($form->{ "$key" . "$item" } /
 
1725                                                    $form->{10}{$key} * 100
 
1727                                                 $form->{decimalplaces}
 
1729                                $form->{decimalplaces},
 
1734     if ($form->{4}{$key} > 0) {
 
1735       foreach $category (@categories) {
 
1736         if (defined($form->{$category}{$key})) {
 
1737           $form->{ "$key" . "auf" . "$category" } =
 
1738             $form->format_amount(
 
1740                          $form->round_amount(
 
1741                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1742                            $form->{decimalplaces}
 
1744                          $form->{decimalplaces},
 
1748       foreach my $item (@ergebnisse) {
 
1749         $form->{ "$key" . "auf" . "$item" } =
 
1750           $form->format_amount($myconfig,
 
1751                                $form->round_amount(
 
1752                                                 ($form->{ "$key" . "$item" } /
 
1753                                                    $form->{4}{$key} * 100
 
1755                                                 $form->{decimalplaces}
 
1757                                $form->{decimalplaces},
 
1762     foreach my $item (@ergebnisse) {
 
1763       $form->{ "$key" . "$item" } =
 
1764         $form->format_amount($myconfig,
 
1765                              $form->round_amount($form->{ "$key" . "$item" },
 
1766                                                  $form->{decimalplaces}
 
1768                              $form->{decimalplaces},
 
1775   $main::lxdebug->leave_sub();
 
1778 sub income_statement {
 
1779   $main::lxdebug->enter_sub();
 
1781   my ($self, $myconfig, $form) = @_;
 
1783   # connect to database
 
1784   my $dbh = $form->dbconnect($myconfig);
 
1786   my $last_period          = 0;
 
1787   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1788   my @categories_ausgaben  =
 
1789     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);
 
1791   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1793   $form->{decimalplaces} *= 1;
 
1797   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1801   foreach my $item (@categories_einnahmen) {
 
1802     $form->{"eur${item}"} =
 
1803       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1804     $form->{"sumeura"} += $form->{$item};
 
1806   foreach my $item (@categories_ausgaben) {
 
1807     $form->{"eur${item}"} =
 
1808       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1809     $form->{"sumeurb"} += $form->{$item};
 
1812   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1814   foreach my $item (@ergebnisse) {
 
1816       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1818   $main::lxdebug->leave_sub();