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};
 
 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   # if l_ob is selected l_cb is always ignored
 
 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 ';
 
 222     $fromdate = conv_dateq($fromdate);
 
 223     if ($form->{method} eq 'cash') {
 
 224       $subwhere .= " AND (transdate >= $fromdate)";
 
 225       $glwhere = " AND (ac.transdate >= $fromdate)";
 
 227       $where .= " AND (ac.transdate >= $fromdate)";
 
 232     $todate = conv_dateq($todate);
 
 233     $where    .= " AND (ac.transdate <= $todate)";
 
 234     $subwhere .= " AND (transdate <= $todate)";
 
 237   if ($department_id) {
 
 238     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
 
 239     $dpt_where = qq| AND (t.id = | . conv_i($department_id, 'NULL') . qq|)|;
 
 242   if ($form->{project_id}) {
 
 243     # Diese Bedingung wird derzeit niemals wahr sein, da man in Bericht->Bilanz keine
 
 244     # Projekte auswählen kann
 
 245     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 248   if ($form->{method} eq 'cash') {
 
 250       qq|SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 252          JOIN chart c ON (c.id = ac.chart_id)
 
 253          JOIN ar a ON (a.id = ac.trans_id)
 
 262                JOIN chart c ON (a.chart_id = c.id)
 
 263                WHERE (link LIKE '%AR_paid%')
 
 267          GROUP BY c.accno, c.description, c.category
 
 271          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 273          JOIN chart c ON (c.id = ac.chart_id)
 
 274          JOIN ap a ON (a.id = ac.trans_id)
 
 283                JOIN chart c ON (a.chart_id = c.id)
 
 284                WHERE (link LIKE '%AP_paid%')
 
 288          GROUP BY c.accno, c.description, c.category
 
 292          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 294          JOIN chart c ON (c.id = ac.chart_id)
 
 295          JOIN gl a ON (a.id = ac.trans_id)
 
 301              AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
 
 303          GROUP BY c.accno, c.description, c.category |;
 
 305     if ($form->{project_id}) {
 
 306       # s.o. keine Projektauswahl in Bilanz
 
 311          SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 313          JOIN ar a ON (a.id = ac.trans_id)
 
 314          JOIN parts p ON (ac.parts_id = p.id)
 
 315          JOIN chart c on (p.income_accno_id = c.id)
 
 317          -- use transdate from subwhere
 
 318          WHERE (c.category = 'I')
 
 325                JOIN chart c ON (a.chart_id = c.id)
 
 326                WHERE (link LIKE '%AR_paid%')
 
 330          GROUP BY c.accno, c.description, c.category
 
 334          SELECT c.accno AS accno, SUM(ac.sellprice) AS amount, c.description AS description, c.category
 
 336          JOIN ap a ON (a.id = ac.trans_id)
 
 337          JOIN parts p ON (ac.parts_id = p.id)
 
 338          JOIN chart c on (p.expense_accno_id = c.id)
 
 340          WHERE (c.category = 'E')
 
 347                JOIN chart c ON (a.chart_id = c.id)
 
 348                WHERE link LIKE '%AP_paid%'
 
 352          GROUP BY c.accno, c.description, c.category |;
 
 355   } else {                      # if ($form->{method} eq 'cash')
 
 356     if ($department_id) {
 
 357       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
 358       $dpt_where = qq| AND t.department_id = | . conv_i($department_id);
 
 362       SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
 
 364       JOIN chart c ON (c.id = ac.chart_id)
 
 370       GROUP BY c.accno, c.description, c.category |;
 
 372     if ($form->{project_id}) {
 
 373       # s.o. keine Projektauswahl in Bilanz
 
 377       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
 
 379       JOIN ar a ON (a.id = ac.trans_id)
 
 380       JOIN parts p ON (ac.parts_id = p.id)
 
 381       JOIN chart c on (p.income_accno_id = c.id)
 
 383       -- use transdate from subwhere
 
 384       WHERE (c.category = 'I')
 
 388       GROUP BY c.accno, c.description, c.category
 
 392       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount, c.description AS description, c.category
 
 394       JOIN ap a ON (a.id = ac.trans_id)
 
 395       JOIN parts p ON (ac.parts_id = p.id)
 
 396       JOIN chart c on (p.expense_accno_id = c.id)
 
 398       WHERE (c.category = 'E')
 
 402       GROUP BY c.accno, c.description, c.category |;
 
 410   $sth = prepare_execute_query($form, $dbh, $query);
 
 412   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 414     if ($ref->{category} eq 'C') {
 
 415       $ref->{category} = 'A';
 
 418     # get last heading account
 
 419     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
 423         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
 
 425         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
 
 429     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
 
 430     $form->{ $ref->{category} }{ $ref->{accno} }{description} = $ref->{description};
 
 431     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
 
 434       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
 
 436       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
 
 441   # remove accounts with zero balance
 
 442   foreach $category (@{$categories}) {
 
 443     foreach $accno (keys %{ $form->{$category} }) {
 
 444       $form->{$category}{$accno}{last} = $form->round_amount($form->{$category}{$accno}{last}, $dec);
 
 445       $form->{$category}{$accno}{this} = $form->round_amount($form->{$category}{$accno}{this}, $dec);
 
 447       delete $form->{$category}{$accno}
 
 448         if (   $form->{$category}{$accno}{this} == 0
 
 449             && $form->{$category}{$accno}{last} == 0);
 
 453   $main::lxdebug->leave_sub();
 
 457   $main::lxdebug->enter_sub();
 
 459   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
 
 461   my ($null, $department_id) = split /--/, $form->{department};
 
 474   $where .= ' AND ac.cb_transaction is false ' unless $form->{l_cb};
 
 477     $fromdate = conv_dateq($fromdate);
 
 478     if ($form->{method} eq 'cash') {
 
 479       $subwhere .= " AND (transdate    >= $fromdate)";
 
 480       $glwhere   = " AND (ac.transdate >= $fromdate)";
 
 481       $prwhere   = " AND (a.transdate  >= $fromdate)";
 
 482       $inwhere   = " AND (acc.transdate >= $fromdate)";
 
 484       $where    .= " AND (ac.transdate >= $fromdate)";
 
 489     $todate = conv_dateq($todate);
 
 490     $subwhere   .= " AND (transdate    <= $todate)";
 
 491     $where      .= " AND (ac.transdate <= $todate)";
 
 492     $prwhere    .= " AND (a.transdate  <= $todate)";
 
 493     $inwhere    .= " AND (acc.transdate <= $todate)";
 
 496   if ($department_id) {
 
 497     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
 
 498     $dpt_where = qq| AND (t.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 and amount != 0 ), 0) != 0 THEN
 
 520                     (SELECT SUM(acc.amount) * -1
 
 522                      INNER JOIN chart c ON (acc.chart_id = c.id AND c.link LIKE '%AR_paid%')
 
 523                      WHERE 1=1 $inwhere AND acc.trans_id = ac.trans_id)
 
 524                   / (SELECT amount FROM ar WHERE id = ac.trans_id and amount != 0 ) ELSE 1 END
 
 525                 ) AS amount, c.$category
 
 527        LEFT JOIN chart c ON (c.id  = ac.chart_id)
 
 528        LEFT JOIN ar      ON (ar.id = ac.trans_id)
 
 529        LEFT JOIN taxkeys tk ON (tk.id = (
 
 530                                   SELECT id FROM taxkeys
 
 531                                   WHERE chart_id = ac.chart_id
 
 532                                   AND startdate <= COALESCE(ar.deliverydate,ar.transdate)
 
 533                                   ORDER BY startdate DESC LIMIT 1
 
 536       WHERE ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE 1=1 $subwhere)
 
 541        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 543          JOIN chart c ON (c.id = ac.chart_id)
 
 544          JOIN ar a ON (a.id = ac.trans_id)
 
 546          WHERE $where $dpt_where
 
 547            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a JOIN chart c ON (a.chart_id = c.id) WHERE (link LIKE '%AR_paid%') $subwhere)
 
 553          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 555          JOIN chart c ON (c.id = ac.chart_id)
 
 556          JOIN ap a ON (a.id = ac.trans_id)
 
 558          WHERE $where $dpt_where
 
 559            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a JOIN chart c ON (a.chart_id = c.id) WHERE (link LIKE '%AP_paid%') $subwhere)
 
 565          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 567          JOIN chart c ON (c.id = ac.chart_id)
 
 568          JOIN gl a ON (a.id = ac.trans_id)
 
 570          WHERE $where $dpt_where $glwhere
 
 571            AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
 
 576     if ($form->{project_id}) {
 
 580          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 582          JOIN ar a ON (a.id = ac.trans_id)
 
 583          JOIN parts p ON (ac.parts_id = p.id)
 
 584          JOIN chart c on (p.income_accno_id = c.id)
 
 586          WHERE (c.category = 'I') $prwhere $dpt_where
 
 587            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans a JOIN chart c ON (a.chart_id = c.id) WHERE (link LIKE '%AR_paid%') $subwhere)
 
 593          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 595          JOIN ap a ON (a.id = ac.trans_id)
 
 596          JOIN parts p ON (ac.parts_id = p.id)
 
 597          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 JOIN chart c ON (a.chart_id = c.id) WHERE (link LIKE '%AP_paid%') $subwhere)
 
 606   } else {                      # if ($form->{method} eq 'cash')
 
 607     if ($department_id) {
 
 608       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
 609       $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 613         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 615         JOIN chart c ON (c.id = ac.chart_id)
 
 620         GROUP BY c.$category |;
 
 622     if ($form->{project_id}) {
 
 626         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
 
 628         JOIN ar a ON (a.id = ac.trans_id)
 
 629         JOIN parts p ON (ac.parts_id = p.id)
 
 630         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)
 
 646         WHERE (c.category = 'E')
 
 650         GROUP BY c.$category |;
 
 658   foreach my $ref (selectall_hashref_query($form, $dbh, $query)) {
 
 659     if ($category eq "pos_bwa") {
 
 661         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
 
 663         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
 
 666       $form->{ $ref->{$category} } += $ref->{amount};
 
 670   $main::lxdebug->leave_sub();
 
 674   $main::lxdebug->enter_sub();
 
 676   my ($self, $myconfig, $form, %options) = @_;
 
 678   my $dbh = $form->dbconnect($myconfig);
 
 680   my ($query, $sth, $ref);
 
 683   my ($null, $department_id) = split /--/, $form->{department};
 
 684   my @headingaccounts = ();
 
 690   my $invwhere = $where;
 
 692   if ($department_id) {
 
 693     $dpt_join = qq| JOIN dpt_trans t ON (ac.trans_id = t.trans_id) |;
 
 694     $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
 697   # project_id only applies to getting transactions
 
 698   # it has nothing to do with a trial balance
 
 699   # but we use the same function to collect information
 
 701   if ($form->{project_id}) {
 
 702     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
 
 705   my $acc_cash_where = "";
 
 706 #  my $ar_cash_where = "";
 
 707 #  my $ap_cash_where = "";
 
 710   if ($form->{method} eq "cash") {
 
 712       qq| AND (ac.trans_id IN (
 
 715             WHERE datepaid >= '$form->{fromdate}'
 
 716               AND datepaid <= '$form->{todate}'
 
 722             WHERE datepaid >= '$form->{fromdate}'
 
 723               AND datepaid <= '$form->{todate}'
 
 729             WHERE transdate >= '$form->{fromdate}'
 
 730               AND transdate <= '$form->{todate}'
 
 732 #    $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
 
 735   if ($options{beginning_balances}) {
 
 736     foreach my $prefix (qw(from to)) {
 
 737       next if ($form->{"${prefix}date"});
 
 739       my $min_max = $prefix eq 'from' ? 'min' : 'max';
 
 740       $query      = qq|SELECT ${min_max}(transdate)
 
 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)
 
 755           WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction
 
 758           GROUP BY c.accno, c.category, c.description |;
 
 760     $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
 
 762     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 764       if ($ref->{amount} != 0 || $form->{all_accounts}) {
 
 765         $trb{ $ref->{accno} }{description} = $ref->{description};
 
 766         $trb{ $ref->{accno} }{charttype}   = 'A';
 
 767         $trb{ $ref->{accno} }{beginning_balance} = $ref->{amount};
 
 769         if ($ref->{amount} > 0) {
 
 770           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
 
 772           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
 
 774         $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 783     qq|SELECT c.accno, c.description, c.category
 
 785        WHERE c.charttype = 'H'
 
 788   $sth = prepare_execute_query($form, $dbh, $query);
 
 790   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 791     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 792     $trb{ $ref->{accno} }{charttype}   = 'H';
 
 793     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 795     push @headingaccounts, $ref->{accno};
 
 801   my $saldowhere    = " 1 = 1 ";
 
 802   my $sumwhere      = " 1 = 1 ";
 
 804   my $sumsubwhere   = '';
 
 805   my $saldosubwhere = '';
 
 806   my $glsaldowhere  = '';
 
 811   my ($fromdate, $todate);
 
 813   if ($form->{fromdate} || $form->{todate}) {
 
 814     if ($form->{fromdate}) {
 
 815       $fromdate = conv_dateq($form->{fromdate});
 
 816       $tofrom        .= " AND (ac.transdate >= $fromdate)";
 
 817       $subwhere      .= " AND (ac.transdate >= $fromdate)";
 
 818       $sumsubwhere   .= " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 819       $saldosubwhere .= " AND (ac,transdate>=(select date_trunc('year', date $fromdate)))  ";
 
 820       $invwhere      .= " AND (a.transdate >= $fromdate)";
 
 821       $glsaldowhere  .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
 
 822       $glwhere        = " AND (ac.transdate >= $fromdate)";
 
 823       $glsumwhere     = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
 
 825     if ($form->{todate}) {
 
 826       $todate = conv_dateq($form->{todate});
 
 827       $tofrom        .= " AND (ac.transdate <= $todate)";
 
 828       $invwhere      .= " AND (a.transdate <= $todate)";
 
 829       $saldosubwhere .= " AND (ac.transdate <= $todate)";
 
 830       $sumsubwhere   .= " AND (ac.transdate <= $todate)";
 
 831       $subwhere      .= " AND (ac.transdate <= $todate)";
 
 832       $glwhere       .= " AND (ac.transdate <= $todate)";
 
 833       $glsumwhere    .= " AND (ac.transdate <= $todate) ";
 
 834       $glsaldowhere  .= " AND (ac.transdate <= $todate) ";
 
 838   if ($form->{method} eq "cash") {
 
 840       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     $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) |;
 
 843     $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) |;
 
 845     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 846     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 847     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
 
 851        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
 
 853        JOIN chart c ON (c.id = ac.chart_id)
 
 858        GROUP BY c.accno, c.description, c.category |;
 
 860   if ($form->{project_id}) {
 
 862       -- add project transactions from invoice
 
 866       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
 
 868       JOIN ar a ON (ac.trans_id = a.id)
 
 869       JOIN parts p ON (ac.parts_id = p.id)
 
 870       JOIN chart c ON (p.income_accno_id = c.id)
 
 875       GROUP BY c.accno, c.description, c.category
 
 879       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
 
 881       JOIN ap a ON (ac.trans_id = a.id)
 
 882       JOIN parts p ON (ac.parts_id = p.id)
 
 883       JOIN chart c ON (p.expense_accno_id = c.id)
 
 888       GROUP BY c.accno, c.description, c.category
 
 892   $query .= qq| ORDER BY accno|;
 
 894   $sth = prepare_execute_query($form, $dbh, $query);
 
 896   # calculate the debit and credit in the period
 
 897   while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 898     $trb{ $ref->{accno} }{description} = $ref->{description};
 
 899     $trb{ $ref->{accno} }{charttype}   = 'A';
 
 900     $trb{ $ref->{accno} }{category}    = $ref->{category};
 
 901     $trb{ $ref->{accno} }{amount} += $ref->{amount};
 
 905   # prepare query for each account
 
 906   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
 
 910          (SELECT SUM(ac.amount) * -1
 
 912           JOIN chart c ON (c.id = ac.chart_id)
 
 918           AND (c.accno = ?)) AS debit,
 
 920          (SELECT SUM(ac.amount)
 
 922           JOIN chart c ON (c.id = ac.chart_id)
 
 928           AND c.accno = ?) AS credit,
 
 929         (SELECT SUM(ac.amount)
 
 931          JOIN chart c ON (ac.chart_id = c.id)
 
 936          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
 938         (SELECT SUM(ac.amount)
 
 940          JOIN chart c ON (ac.chart_id = c.id)
 
 946          AND c.accno = ?) AS sum_credit,
 
 948         (SELECT SUM(ac.amount)
 
 950          JOIN chart c ON (ac.chart_id = c.id)
 
 956          AND c.accno = ?) AS sum_debit,
 
 958         (SELECT max(ac.transdate) FROM acc_trans ac
 
 959         JOIN chart c ON (ac.chart_id = c.id)
 
 964         AND c.accno = ?) AS last_transaction
 
 969   $drcr = prepare_query($form, $dbh, $q_drcr);
 
 971   if ($form->{project_id}) {
 
 972     # prepare query for each account
 
 975           (SELECT SUM(ac.sellprice * ac.qty) * -1
 
 977            JOIN parts p ON (ac.parts_id = p.id)
 
 978            JOIN ap a ON (ac.trans_id = a.id)
 
 979            JOIN chart c ON (p.expense_accno_id = c.id)
 
 984            AND c.accno = ?) AS debit,
 
 986           (SELECT SUM(ac.sellprice * ac.qty)
 
 988            JOIN parts p ON (ac.parts_id = p.id)
 
 989            JOIN ar a ON (ac.trans_id = a.id)
 
 990            JOIN chart c ON (p.income_accno_id = c.id)
 
 995            AND c.accno = ?) AS credit,
 
 997         (SELECT SUM(ac.amount)
 
 999          JOIN chart c ON (ac.chart_id = c.id)
 
1004          AND c.accno = ? AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL)) AS saldo,
 
1006         (SELECT SUM(ac.amount)
 
1008          JOIN chart c ON (ac.chart_id = c.id)
 
1014          AND c.accno = ?) AS sum_credit,
 
1016         (SELECT SUM(ac.amount)
 
1018          JOIN chart c ON (ac.chart_id = c.id)
 
1024          AND c.accno = ?) AS sum_debit,
 
1027         (SELECT max(ac.transdate) FROM acc_trans ac
 
1028         JOIN chart c ON (ac.chart_id = c.id)
 
1033         AND c.accno = ?) AS last_transaction
 
1036     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
 
1040   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
 
1042   foreach my $accno (sort keys %trb) {
 
1045     $ref->{accno} = $accno;
 
1046     map { $ref->{$_} = $trb{$accno}{$_} }
 
1047       qw(description category charttype amount soll_eb haben_eb beginning_balance);
 
1049     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
 
1051     if ($trb{$accno}{charttype} eq 'A') {
 
1054       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1056       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo) = (0, 0, 0, 0, 0);
 
1057       my ($soll_kumuliert, $haben_kumuliert) = (0, 0);
 
1058       $last_transaction = "";
 
1059       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
 
1060         $ref->{debit}  += $debit;
 
1061         $ref->{credit} += $credit;
 
1063           $ref->{haben_saldo} += $saldo;
 
1065           $ref->{soll_saldo} += $saldo * -1;
 
1067         $ref->{last_transaction} = $last_transaction;
 
1068         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
 
1069         $ref->{haben_kumuliert} = $haben_kumuliert;
 
1073       if ($form->{project_id}) {
 
1076         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
 
1078         ($debit, $credit) = (0, 0);
 
1079         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
 
1080           $ref->{debit}  += $debit;
 
1081           $ref->{credit} += $credit;
 
1083             $ref->{haben_saldo} += $saldo;
 
1085             $ref->{soll_saldo} += $saldo * -1;
 
1087           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
 
1088           $ref->{haben_kumuliert} += $haben_kumuliert;
 
1090         $project_drcr->finish;
 
1093       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
 
1094       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
 
1096       if ($ref->{haben_saldo} != 0) {
 
1097         $ref->{haben_saldo}  = $ref->{haben_saldo} + $ref->{beginning_balance};
 
1098         if ($ref->{haben_saldo} < 0) {
 
1099           $ref->{soll_saldo} = $form->round_amount(($ref->{haben_saldo} *- 1), 2);
 
1100           $ref->{haben_saldo} = 0;
 
1103         $ref->{soll_saldo} = $ref->{soll_saldo} - $ref->{beginning_balance};
 
1104         if ($ref->{soll_saldo} < 0) {
 
1105           $ref->{haben_saldo} = $form->round_amount(($ref->{soll_saldo} * -1), 2);
 
1106           $ref->{soll_saldo} = 0;
 
1109       $ref->{haben_saldo} = $form->round_amount($ref->{haben_saldo}, 2);
 
1110       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
 
1111       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
 
1112       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
 
1117     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
 
1118     $accno = pop @accno;
 
1120       $trb{$accno}{debit}  += $ref->{debit};
 
1121       $trb{$accno}{credit} += $ref->{credit};
 
1122       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
 
1123       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
 
1124       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
 
1125       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
 
1128     push @{ $form->{TB} }, $ref;
 
1134   # debits and credits for headings
 
1135   foreach my $accno (@headingaccounts) {
 
1136     foreach $ref (@{ $form->{TB} }) {
 
1137       if ($accno eq $ref->{accno}) {
 
1138         $ref->{debit}           = $trb{$accno}{debit};
 
1139         $ref->{credit}          = $trb{$accno}{credit};
 
1140         $ref->{soll_saldo}      = $trb{$accno}{soll_saldo};
 
1141         $ref->{haben_saldo}     = $trb{$accno}{haben_saldo};
 
1142         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
 
1143         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};
 
1148   $main::lxdebug->leave_sub();
 
1152   $main::lxdebug->enter_sub();
 
1153   my ($self, $dbh, $form) = @_;
 
1154   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
 
1155   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
 
1156   my $sth =  $dbh->prepare($query);
 
1157   while(my $ref = $sth->fetchrow_hashref()) {
 
1158     $ref->{invnumer} =~ s/Storno zu //g;
 
1159     $form->{storno}{$ref->{invnumber}} = 1;
 
1161   $main::lxdebug->leave_sub();
 
1165   $main::lxdebug->enter_sub();
 
1167   my ($self, $myconfig, $form) = @_;
 
1169   # connect to database
 
1170   my $dbh     = $form->dbconnect($myconfig);
 
1172   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
 
1174   if ($form->{ct} eq "customer") {
 
1187   $ct_id = "${ct}_id";
 
1189   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
 
1190   my $todate = conv_dateq($form->{todate});
 
1191   my $fromdate = conv_dateq($form->{fromdate});
 
1193   my $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
 
1195   my $where = " 1 = 1 ";
 
1198   if ($form->{$ct_id}) {
 
1199     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
 
1200   } elsif ($form->{ $form->{ct} }) {
 
1201     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
 
1206   if ($form->{department}) {
 
1207     my ($null, $department_id) = split /--/, $form->{department};
 
1208     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
 
1209     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1210     $where_dpt = qq| AND (${arap}.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
 
1212   my $review_of_aging_list;
 
1213   if ($form->{review_of_aging_list}) {
 
1214     if ($form->{review_of_aging_list} =~ m "-"){
 
1215       my @period = split(/-/, $form->{review_of_aging_list});
 
1216       $review_of_aging_list = " AND $period[0] < date_part('days', now() - duedate)
 
1217                                 AND date_part('days', now() - duedate)  < $period[1]";
 
1219       $form->{review_of_aging_list} =~ s/[^0-9]//g;
 
1220       $review_of_aging_list = " AND $form->{review_of_aging_list} < date_part('days', now() - duedate)";
 
1226     SELECT ${ct}.id AS ctid, ${ct}.name,
 
1227       street, zipcode, city, country, contact, email,
 
1228       phone as customerphone, fax as customerfax, ${ct}number,
 
1229       "invnumber", "transdate",
 
1230       (amount - COALESCE((SELECT sum(amount)*$ml FROM acc_trans LEFT JOIN chart ON (acc_trans.chart_id=chart.id) WHERE link ilike '%paid%' AND acc_trans.trans_id=${arap}.id AND acc_trans.transdate <= (date $todate)),0)) as "open", "amount",
 
1231       "duedate", invoice, ${arap}.id, date_part('days', now() - duedate) as overduedays,
 
1234        WHERE (${arap}.curr = exchangerate.curr)
 
1235          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
 
1237     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
 
1238       AND NOT COALESCE (${arap}.storno, 'f')
 
1239       AND (${arap}.${ct}_id = ${ct}.id)
 
1242       AND (transdate <= (date $todate) $fromwhere )
 
1243       $review_of_aging_list
 
1244     ORDER BY ctid, transdate, invnumber |;
 
1246   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1248   # select outstanding vendors or customers, depends on $ct
 
1250     qq|SELECT DISTINCT ct.id, ct.name
 
1251        FROM $ct ct, $arap a
 
1254          AND (a.${ct_id} = ct.id)
 
1255          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
 
1256          AND (a.transdate <= $todate $fromwhere)
 
1259   my $sth = prepare_execute_query($form, $dbh, $query);
 
1262   # for each company that has some stuff outstanding
 
1263   while (my ($id) = $sth->fetchrow_array) {
 
1264     do_statement($form, $sth_details, $q_details, $id);
 
1266     while (my $ref = $sth_details->fetchrow_hashref("NAME_lc")) {
 
1267       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
 
1268       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
 
1269       push @{ $form->{AG} }, $ref;
 
1272     $sth_details->finish;
 
1281   $main::lxdebug->leave_sub();
 
1285   $main::lxdebug->enter_sub();
 
1287   my ($self, $myconfig, $form) = @_;
 
1289   # connect to database
 
1290   my $dbh = $form->dbconnect($myconfig);
 
1292   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
 
1295     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
 
1298   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
 
1299     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
 
1302   $main::lxdebug->leave_sub();
 
1306   $main::lxdebug->enter_sub();
 
1308   my ($self, $myconfig, $form) = @_;
 
1310   # connect to database
 
1311   my $dbh = $form->dbconnect($myconfig);
 
1313   my ($null, $department_id) = split /--/, $form->{department};
 
1316   my $where = "1 = 1";
 
1318   if ($department_id) {
 
1319     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
 
1324   if ($form->{accno}) {
 
1325     $accno = $form->{accno};
 
1326     $rate  = $form->{"$form->{accno}_rate"};
 
1327     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
 
1333   if ($form->{db} eq 'ar') {
 
1334     $table = "customer";
 
1341   my $arap = lc($ARAP);
 
1343   my $transdate = "a.transdate";
 
1345   if ($form->{method} eq 'cash') {
 
1346     $transdate = "a.datepaid";
 
1348     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
 
1355           JOIN chart c ON (a.chart_id = c.id)
 
1356           WHERE (link LIKE '%${ARAP}_paid%')
 
1357           AND (transdate <= $todate)
 
1362   # if there are any dates construct a where
 
1363   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
 
1364   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
 
1366   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
 
1368   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
 
1369   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
 
1372   if ($form->{report} !~ /nontaxable/) {
 
1374       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
 
1375           ac.amount * $ml AS tax
 
1377          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1378          JOIN chart ch ON (ch.id = ac.chart_id)
 
1379          JOIN $table n ON (n.id = a.${table}_id)
 
1383            AND (a.invoice = '0')
 
1387          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
 
1388            i.sellprice * i.qty * $rate * $ml AS tax
 
1390          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1391          JOIN chart ch ON (ch.id = ac.chart_id)
 
1392          JOIN $table n ON (n.id = a.${table}_id)
 
1393          JOIN ${table}tax t ON (t.${table}_id = n.id)
 
1394          JOIN invoice i ON (i.trans_id = a.id)
 
1395          JOIN partstax p ON (p.parts_id = i.parts_id)
 
1399            AND (a.invoice = '1')
 
1400          ORDER BY $sortorder|;
 
1402     # only gather up non-taxable transactions
 
1404       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount
 
1406          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1407          JOIN $table n ON (n.id = a.${table}_id)
 
1410            AND (a.invoice = '0')
 
1411            AND (a.netamount = a.amount)
 
1415          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount
 
1417          JOIN ${arap} a ON (a.id = ac.trans_id)
 
1418          JOIN $table n ON (n.id = a.${table}_id)
 
1419          JOIN invoice i ON (i.trans_id = a.id)
 
1422            AND (a.invoice = '1')
 
1424              a.${table}_id NOT IN (SELECT ${table}_id FROM ${table}tax t (${table}_id))
 
1426              i.parts_id NOT IN (SELECT parts_id FROM partstax p (parts_id))
 
1428          GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
 
1429          ORDER by $sortorder|;
 
1432   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
 
1436   $main::lxdebug->leave_sub();
 
1439 sub paymentaccounts {
 
1440   $main::lxdebug->enter_sub();
 
1442   my ($self, $myconfig, $form) = @_;
 
1444   # connect to database, turn AutoCommit off
 
1445   my $dbh = $form->dbconnect_noauto($myconfig);
 
1447   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
 
1449   # get A(R|P)_paid accounts
 
1451     qq|SELECT accno, description
 
1453        WHERE link LIKE '%${ARAP}_paid%'|;
 
1454   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
 
1458   $main::lxdebug->leave_sub();
 
1462   $main::lxdebug->enter_sub();
 
1464   my ($self, $myconfig, $form) = @_;
 
1466   # connect to database, turn AutoCommit off
 
1467   my $dbh = $form->dbconnect_noauto($myconfig);
 
1472   if ($form->{db} eq 'ar') {
 
1473     $table = 'customer';
 
1485   if ($form->{department_id}) {
 
1486     $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
 
1487     $where = qq| AND (t.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
 
1490   if ($form->{fromdate}) {
 
1491     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
 
1493   if ($form->{todate}) {
 
1494     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
 
1496   if (!$form->{fx_transaction}) {
 
1497     $where .= " AND ac.fx_transaction = '0'";
 
1502   if ($form->{reference}) {
 
1503     $reference = $dbh->quote('%' . $form->{reference} . '%');
 
1504     $invnumber = " AND (a.invnumber LIKE $reference)";
 
1505     $reference = " AND (g.reference LIKE $reference)";
 
1507   if ($form->{source}) {
 
1508     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
 
1510   if ($form->{memo}) {
 
1511     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
 
1514   my %sort_columns =  (
 
1515     'transdate'    => [ qw(transdate lower_invnumber lower_name) ],
 
1516     'invnumber'    => [ qw(lower_invnumber lower_name transdate) ],
 
1517     'name'         => [ qw(lower_name transdate)                 ],
 
1518     'source'       => [ qw(lower_source)                         ],
 
1519     'memo'         => [ qw(lower_memo)                           ],
 
1521   my %lowered_columns =  (
 
1522     'invnumber'       => { 'gl' => 'g.reference',   'arap' => 'a.invnumber', },
 
1523     'memo'            => { 'gl' => 'ac.memo',       'arap' => 'ac.memo',     },
 
1524     'source'          => { 'gl' => 'ac.source',     'arap' => 'ac.source',   },
 
1525     'name'            => { 'gl' => 'g.description', 'arap' => 'c.name',      },
 
1528   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
 
1529   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'transdate';
 
1530   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
1533   my %columns_for_sorting = ( 'gl' => '', 'arap' => '', );
 
1534   foreach my $spec (@{ $sort_columns{$sortkey} }) {
 
1535     next if ($spec !~ m/^lower_(.*)$/);
 
1538     map { $columns_for_sorting{$_} .= sprintf(', lower(%s) AS lower_%s', $lowered_columns{$column}->{$_}, $column) } qw(gl arap);
 
1541   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
 
1542   $sth = prepare_query($form, $dbh, $query);
 
1545       qq|SELECT c.name, a.invnumber, a.ordnumber,
 
1546            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1547            a.invoice, a.id, ac.memo, '${arap}' AS module
 
1548            $columns_for_sorting{arap}
 
1550          JOIN $arap a ON (ac.trans_id = a.id)
 
1551          JOIN $table c ON (c.id = a.${table}_id)
 
1553          WHERE (ac.chart_id = ?)
 
1559          SELECT g.description, g.reference, NULL AS ordnumber,
 
1560            ac.transdate, ac.amount * $ml AS paid, ac.source,
 
1561            '0' as invoice, g.id, ac.memo, 'gl' AS module
 
1562            $columns_for_sorting{gl}
 
1564          JOIN gl g ON (g.id = ac.trans_id)
 
1566          WHERE (ac.chart_id = ?)
 
1569            AND (ac.amount * $ml) > 0
 
1571          ORDER BY $sortorder|;
 
1572   my $sth_details = prepare_query($form, $dbh, $q_details);
 
1576   # cycle through each id
 
1577   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
 
1578     do_statement($form, $sth, $query, $accno);
 
1579     my $ref = $sth->fetchrow_hashref();
 
1580     push(@{ $form->{PR} }, $ref);
 
1583     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
 
1585     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
 
1586     while (my $pr = $sth_details->fetchrow_hashref()) {
 
1587       push(@{ $form->{ $ref->{id} } }, $pr);
 
1589     $sth_details->finish();
 
1594   $main::lxdebug->leave_sub();
 
1598   $main::lxdebug->enter_sub();
 
1600   my ($self, $myconfig, $form) = @_;
 
1602   # connect to database
 
1603   my $dbh = $form->dbconnect($myconfig);
 
1605   my $last_period = 0;
 
1608     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);
 
1610   $form->{decimalplaces} *= 1;
 
1612   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
 
1614   # if there are any compare dates
 
1616   if ($form->{fromdate} || $form->{todate}) {
 
1618     if ($form->{fromdate}) {
 
1619       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1622       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
 
1625     my $kummfromdate = $form->{comparefromdate};
 
1626     my $kummtodate   = $form->{comparetodate};
 
1627     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
 
1630   my @periods        = qw(jetzt kumm);
 
1631   my @gesamtleistung = qw(1 3);
 
1632   my @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
 
1634     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
 
1636   foreach my $key (@periods) {
 
1637     $form->{ "$key" . "gesamtleistung" } = 0;
 
1638     $form->{ "$key" . "gesamtkosten" }   = 0;
 
1640     foreach $category (@categories) {
 
1642       if (defined($form->{$category}{$key})) {
 
1643         $form->{"$key$category"} =
 
1644           $form->format_amount($myconfig,
 
1645                                $form->round_amount($form->{$category}{$key}, 2
 
1647                                $form->{decimalplaces},
 
1651     foreach my $item (@gesamtleistung) {
 
1652       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
 
1654     $form->{ "$key" . "gesamtleistung" } -= $form->{2}{$key};
 
1656     foreach my $item (@gesamtkosten) {
 
1657       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
 
1659     $form->{ "$key" . "rohertrag" } =
 
1660       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
 
1661     $form->{ "$key" . "betriebrohertrag" } =
 
1662       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
 
1663     $form->{ "$key" . "betriebsergebnis" } =
 
1664       $form->{ "$key" . "betriebrohertrag" } -
 
1665       $form->{ "$key" . "gesamtkosten" };
 
1666     $form->{ "$key" . "neutraleraufwand" } =
 
1667       $form->{30}{$key} + $form->{31}{$key};
 
1668     $form->{ "$key" . "neutralertrag" } =
 
1669       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
 
1670     $form->{ "$key" . "ergebnisvorsteuern" } =
 
1671       $form->{ "$key" . "betriebsergebnis" } -
 
1672       $form->{ "$key" . "neutraleraufwand" } +
 
1673       $form->{ "$key" . "neutralertrag" };
 
1674     $form->{ "$key" . "ergebnis" } =
 
1675       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
 
1677     if ($form->{ "$key" . "gesamtleistung" } > 0) {
 
1678       foreach $category (@categories) {
 
1679         if (defined($form->{$category}{$key})) {
 
1680           $form->{ "$key" . "gl" . "$category" } =
 
1681             $form->format_amount(
 
1683                                $form->round_amount(
 
1684                                  ($form->{$category}{$key} /
 
1685                                     $form->{ "$key" . "gesamtleistung" } * 100
 
1687                                  $form->{decimalplaces}
 
1689                                $form->{decimalplaces},
 
1693       foreach my $item (@ergebnisse) {
 
1694         $form->{ "$key" . "gl" . "$item" } =
 
1695           $form->format_amount($myconfig,
 
1696                                $form->round_amount(
 
1697                                  ( $form->{ "$key" . "$item" } /
 
1698                                      $form->{ "$key" . "gesamtleistung" } * 100
 
1700                                  $form->{decimalplaces}
 
1702                                $form->{decimalplaces},
 
1707     if ($form->{ "$key" . "gesamtkosten" } > 0) {
 
1708       foreach $category (@categories) {
 
1709         if (defined($form->{$category}{$key})) {
 
1710           $form->{ "$key" . "gk" . "$category" } =
 
1711             $form->format_amount($myconfig,
 
1712                                  $form->round_amount(
 
1713                                    ($form->{$category}{$key} /
 
1714                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1716                                    $form->{decimalplaces}
 
1718                                  $form->{decimalplaces},
 
1722       foreach my $item (@ergebnisse) {
 
1723         $form->{ "$key" . "gk" . "$item" } =
 
1724           $form->format_amount($myconfig,
 
1725                                $form->round_amount(
 
1726                                    ($form->{ "$key" . "$item" } /
 
1727                                       $form->{ "$key" . "gesamtkosten" } * 100
 
1729                                    $form->{decimalplaces}
 
1731                                $form->{decimalplaces},
 
1736     if ($form->{10}{$key} > 0) {
 
1737       foreach $category (@categories) {
 
1738         if (defined($form->{$category}{$key})) {
 
1739           $form->{ "$key" . "pk" . "$category" } =
 
1740             $form->format_amount(
 
1742                         $form->round_amount(
 
1743                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
 
1744                           $form->{decimalplaces}
 
1746                         $form->{decimalplaces},
 
1750       foreach my $item (@ergebnisse) {
 
1751         $form->{ "$key" . "pk" . "$item" } =
 
1752           $form->format_amount($myconfig,
 
1753                                $form->round_amount(
 
1754                                                 ($form->{ "$key" . "$item" } /
 
1755                                                    $form->{10}{$key} * 100
 
1757                                                 $form->{decimalplaces}
 
1759                                $form->{decimalplaces},
 
1764     if ($form->{4}{$key} > 0) {
 
1765       foreach $category (@categories) {
 
1766         if (defined($form->{$category}{$key})) {
 
1767           $form->{ "$key" . "auf" . "$category" } =
 
1768             $form->format_amount(
 
1770                          $form->round_amount(
 
1771                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
 
1772                            $form->{decimalplaces}
 
1774                          $form->{decimalplaces},
 
1778       foreach my $item (@ergebnisse) {
 
1779         $form->{ "$key" . "auf" . "$item" } =
 
1780           $form->format_amount($myconfig,
 
1781                                $form->round_amount(
 
1782                                                 ($form->{ "$key" . "$item" } /
 
1783                                                    $form->{4}{$key} * 100
 
1785                                                 $form->{decimalplaces}
 
1787                                $form->{decimalplaces},
 
1792     foreach my $item (@ergebnisse) {
 
1793       $form->{ "$key" . "$item" } =
 
1794         $form->format_amount($myconfig,
 
1795                              $form->round_amount($form->{ "$key" . "$item" },
 
1796                                                  $form->{decimalplaces}
 
1798                              $form->{decimalplaces},
 
1805   $main::lxdebug->leave_sub();
 
1809   $main::lxdebug->enter_sub();
 
1811   my ($self, $myconfig, $form) = @_;
 
1813   # connect to database
 
1814   my $dbh = $form->dbconnect($myconfig);
 
1816   my $last_period     = 0;
 
1817   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
 
1818     96 66 43 45 53 62 65 67);
 
1819   my @categories_euro = qw(48 51 86 91 97 93 94);
 
1820   $form->{decimalplaces} *= 1;
 
1822   foreach my $item (@categories_cent) {
 
1823     $form->{"$item"} = 0;
 
1825   foreach my $item (@categories_euro) {
 
1826     $form->{"$item"} = 0;
 
1829   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_ustva");
 
1831   #   foreach $item (@categories_cent) {
 
1832   #     if ($form->{$item}{"jetzt"} > 0) {
 
1833   #       $form->{$item} = $form->{$item}{"jetzt"};
 
1834   #       delete $form->{$item}{"jetzt"};
 
1837   #   foreach $item (@categories_euro) {
 
1838   #     if ($form->{$item}{"jetzt"} > 0) {
 
1839   #       $form->{$item} = $form->{$item}{"jetzt"};
 
1840   #       delete $form->{$item}{"jetzt"};
 
1841   #     }  foreach $item (@categories_cent) {
 
1842   #     if ($form->{$item}{"jetzt"} > 0) {
 
1843   #       $form->{$item} = $form->{$item}{"jetzt"};
 
1844   #       delete $form->{$item}{"jetzt"};
 
1847   #   foreach $item (@categories_euro) {
 
1848   #     if ($form->{$item}{"jetzt"} > 0) {
 
1849   #       $form->{$item} = $form->{$item}{"jetzt"};
 
1850   #       delete $form->{$item}{"jetzt"};
 
1857   # Berechnung der USTVA Formularfelder
 
1859   $form->{"51r"} = $form->{"511"};
 
1860   $form->{"86r"} = $form->{"861"};
 
1861   $form->{"97r"} = $form->{"971"};
 
1862   $form->{"93r"} = $form->{"931"};
 
1864   #$form->{"96"}  = $form->{"94"} * 0.16;
 
1866     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
 
1868   $form->{"45"} = $form->{"43"};
 
1869   $form->{"53"} = $form->{"43"};
 
1870   $form->{"62"} = $form->{"43"} - $form->{"66"};
 
1871   $form->{"65"} = $form->{"43"} - $form->{"66"};
 
1872   $form->{"67"} = $form->{"43"} - $form->{"66"};
 
1874   foreach my $item (@categories_cent) {
 
1876       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
 
1880   foreach my $item (@categories_euro) {
 
1882       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
 
1888   $main::lxdebug->leave_sub();
 
1891 sub income_statement {
 
1892   $main::lxdebug->enter_sub();
 
1894   my ($self, $myconfig, $form) = @_;
 
1896   # connect to database
 
1897   my $dbh = $form->dbconnect($myconfig);
 
1899   my $last_period          = 0;
 
1900   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
 
1901   my @categories_ausgaben  =
 
1902     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);
 
1904   my @ergebnisse = qw(sumeura sumeurb guvsumme);
 
1906   $form->{decimalplaces} *= 1;
 
1910   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
 
1914   foreach my $item (@categories_einnahmen) {
 
1915     $form->{"eur${item}"} =
 
1916       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1917     $form->{"sumeura"} += $form->{$item};
 
1919   foreach my $item (@categories_ausgaben) {
 
1920     $form->{"eur${item}"} =
 
1921       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1922     $form->{"sumeurb"} += $form->{$item};
 
1925   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
 
1927   foreach my $item (@ergebnisse) {
 
1929       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),2);
 
1931   $main::lxdebug->leave_sub();