Fix für SQL-Fehler, dass transdate mehrdeutig ist, wenn auch nach Projekten gefiltert...
[kivitendo-erp.git] / SL / RP.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors: Benjamin Lee <benjaminlee@consultant.com>
16 #
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.
21 #
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 #======================================================================
30 #
31 # backend code for reports
32 #
33 #======================================================================
34
35 package RP;
36
37 sub balance_sheet {
38   $main::lxdebug->enter_sub();
39
40   my ($self, $myconfig, $form) = @_;
41
42   # connect to database
43   my $dbh = $form->dbconnect($myconfig);
44
45   my $last_period = 0;
46   my @categories  = qw(A C L Q);
47
48   # if there are any dates construct a where
49   if ($form->{asofdate}) {
50
51     $form->{this_period} = "$form->{asofdate}";
52     $form->{period}      = "$form->{asofdate}";
53
54   }
55
56   $form->{decimalplaces} *= 1;
57
58   &get_accounts($dbh, $last_period, "", $form->{asofdate}, $form,
59                 \@categories);
60
61   # if there are any compare dates
62   if ($form->{compareasofdate}) {
63
64     $last_period = 1;
65     &get_accounts($dbh, $last_period, "", $form->{compareasofdate},
66                   $form, \@categories);
67
68     $form->{last_period} = "$form->{compareasofdate}";
69
70   }
71
72   # disconnect
73   $dbh->disconnect;
74
75   # now we got $form->{A}{accno}{ }    assets
76   # and $form->{L}{accno}{ }           liabilities
77   # and $form->{Q}{accno}{ }           equity
78   # build asset accounts
79
80   my $str;
81   my $key;
82
83   my %account = (
84                  'A' => { 'label'  => 'asset',
85                           'labels' => 'assets',
86                           'ml'     => -1
87                  },
88                  'L' => { 'label'  => 'liability',
89                           'labels' => 'liabilities',
90                           'ml'     => 1
91                  },
92                  'Q' => { 'label'  => 'equity',
93                           'labels' => 'equity',
94                           'ml'     => 1
95                  });
96
97   foreach $category (grep { !/C/ } @categories) {
98
99     foreach $key (sort keys %{ $form->{$category} }) {
100
101       $str = ($form->{l_heading}) ? $form->{padding} : "";
102
103       if ($form->{$category}{$key}{charttype} eq "A") {
104         $str .=
105           ($form->{l_accno})
106           ? "$form->{$category}{$key}{accno} - $form->{$category}{$key}{description}"
107           : "$form->{$category}{$key}{description}";
108       }
109       if ($form->{$category}{$key}{charttype} eq "H") {
110         if ($account{$category}{subtotal} && $form->{l_subtotal}) {
111           $dash = "- ";
112           push(@{ $form->{"$account{$category}{label}_account"} },
113                "$str$form->{bold}$account{$category}{subdescription}$form->{endbold}"
114           );
115           push(@{ $form->{"$account{$category}{label}_this_period"} },
116                $form->format_amount(
117                         $myconfig,
118                         $account{$category}{subthis} * $account{$category}{ml},
119                         $form->{decimalplaces}, $dash
120                ));
121
122           if ($last_period) {
123             push(@{ $form->{"$account{$category}{label}_last_period"} },
124                  $form->format_amount(
125                         $myconfig,
126                         $account{$category}{sublast} * $account{$category}{ml},
127                         $form->{decimalplaces}, $dash
128                  ));
129           }
130         }
131
132         $str =
133           "$form->{bold}$form->{$category}{$key}{description}$form->{endbold}";
134
135         $account{$category}{subthis}        = $form->{$category}{$key}{this};
136         $account{$category}{sublast}        = $form->{$category}{$key}{last};
137         $account{$category}{subdescription} =
138           $form->{$category}{$key}{description};
139         $account{$category}{subtotal} = 1;
140
141         $form->{$category}{$key}{this} = 0;
142         $form->{$category}{$key}{last} = 0;
143
144         next unless $form->{l_heading};
145
146         $dash = " ";
147       }
148
149       # push description onto array
150       push(@{ $form->{"$account{$category}{label}_account"} }, $str);
151
152       if ($form->{$category}{$key}{charttype} eq 'A') {
153         $form->{"total_$account{$category}{labels}_this_period"} +=
154           $form->{$category}{$key}{this} * $account{$category}{ml};
155         $dash = "- ";
156       }
157
158       push(@{ $form->{"$account{$category}{label}_this_period"} },
159            $form->format_amount(
160                       $myconfig,
161                       $form->{$category}{$key}{this} * $account{$category}{ml},
162                       $form->{decimalplaces}, $dash
163            ));
164
165       if ($last_period) {
166         $form->{"total_$account{$category}{labels}_last_period"} +=
167           $form->{$category}{$key}{last} * $account{$category}{ml};
168
169         push(@{ $form->{"$account{$category}{label}_last_period"} },
170              $form->format_amount(
171                       $myconfig,
172                       $form->{$category}{$key}{last} * $account{$category}{ml},
173                       $form->{decimalplaces}, $dash
174              ));
175       }
176     }
177
178     $str = ($form->{l_heading}) ? $form->{padding} : "";
179     if ($account{$category}{subtotal} && $form->{l_subtotal}) {
180       push(@{ $form->{"$account{$category}{label}_account"} },
181            "$str$form->{bold}$account{$category}{subdescription}$form->{endbold}"
182       );
183       push(@{ $form->{"$account{$category}{label}_this_period"} },
184            $form->format_amount(
185                         $myconfig,
186                         $account{$category}{subthis} * $account{$category}{ml},
187                         $form->{decimalplaces}, $dash
188            ));
189
190       if ($last_period) {
191         push(@{ $form->{"$account{$category}{label}_last_period"} },
192              $form->format_amount(
193                         $myconfig,
194                         $account{$category}{sublast} * $account{$category}{ml},
195                         $form->{decimalplaces}, $dash
196              ));
197       }
198     }
199
200   }
201
202   # totals for assets, liabilities
203   $form->{total_assets_this_period} =
204     $form->round_amount($form->{total_assets_this_period},
205                         $form->{decimalplaces});
206   $form->{total_liabilities_this_period} =
207     $form->round_amount($form->{total_liabilities_this_period},
208                         $form->{decimalplaces});
209   $form->{total_equity_this_period} =
210     $form->round_amount($form->{total_equity_this_period},
211                         $form->{decimalplaces});
212
213   # calculate earnings
214   $form->{earnings_this_period} =
215     $form->{total_assets_this_period} -
216     $form->{total_liabilities_this_period} - $form->{total_equity_this_period};
217
218   push(@{ $form->{equity_this_period} },
219        $form->format_amount($myconfig,
220                             $form->{earnings_this_period},
221                             $form->{decimalplaces}, "- "
222        ));
223
224   $form->{total_equity_this_period} =
225     $form->round_amount(
226              $form->{total_equity_this_period} + $form->{earnings_this_period},
227              $form->{decimalplaces});
228
229   # add liability + equity
230   $form->{total_this_period} =
231     $form->format_amount(
232     $myconfig,
233     $form->{total_liabilities_this_period} + $form->{total_equity_this_period},
234     $form->{decimalplaces},
235     "- ");
236
237   if ($last_period) {
238
239     # totals for assets, liabilities
240     $form->{total_assets_last_period} =
241       $form->round_amount($form->{total_assets_last_period},
242                           $form->{decimalplaces});
243     $form->{total_liabilities_last_period} =
244       $form->round_amount($form->{total_liabilities_last_period},
245                           $form->{decimalplaces});
246     $form->{total_equity_last_period} =
247       $form->round_amount($form->{total_equity_last_period},
248                           $form->{decimalplaces});
249
250     # calculate retained earnings
251     $form->{earnings_last_period} =
252       $form->{total_assets_last_period} -
253       $form->{total_liabilities_last_period} -
254       $form->{total_equity_last_period};
255
256     push(@{ $form->{equity_last_period} },
257          $form->format_amount($myconfig,
258                               $form->{earnings_last_period},
259                               $form->{decimalplaces}, "- "
260          ));
261
262     $form->{total_equity_last_period} =
263       $form->round_amount(
264              $form->{total_equity_last_period} + $form->{earnings_last_period},
265              $form->{decimalplaces});
266
267     # add liability + equity
268     $form->{total_last_period} =
269       $form->format_amount($myconfig,
270                            $form->{total_liabilities_last_period} +
271                              $form->{total_equity_last_period},
272                            $form->{decimalplaces},
273                            "- ");
274
275   }
276
277   $form->{total_liabilities_last_period} =
278     $form->format_amount($myconfig,
279                          $form->{total_liabilities_last_period},
280                          $form->{decimalplaces}, "- ")
281     if ($form->{total_liabilities_last_period} != 0);
282
283   $form->{total_equity_last_period} =
284     $form->format_amount($myconfig,
285                          $form->{total_equity_last_period},
286                          $form->{decimalplaces}, "- ")
287     if ($form->{total_equity_last_period} != 0);
288
289   $form->{total_assets_last_period} =
290     $form->format_amount($myconfig,
291                          $form->{total_assets_last_period},
292                          $form->{decimalplaces}, "- ")
293     if ($form->{total_assets_last_period} != 0);
294
295   $form->{total_assets_this_period} =
296     $form->format_amount($myconfig,
297                          $form->{total_assets_this_period},
298                          $form->{decimalplaces}, "- ");
299
300   $form->{total_liabilities_this_period} =
301     $form->format_amount($myconfig,
302                          $form->{total_liabilities_this_period},
303                          $form->{decimalplaces}, "- ");
304
305   $form->{total_equity_this_period} =
306     $form->format_amount($myconfig,
307                          $form->{total_equity_this_period},
308                          $form->{decimalplaces}, "- ");
309
310   $main::lxdebug->leave_sub();
311 }
312
313 sub get_accounts {
314   $main::lxdebug->enter_sub();
315
316   my ($dbh, $last_period, $fromdate, $todate, $form, $categories) = @_;
317
318   my ($null, $department_id) = split /--/, $form->{department};
319
320   my $query;
321   my $dpt_where;
322   my $dpt_join;
323   my $project;
324   my $where    = "1 = 1";
325   my $glwhere  = "";
326   my $subwhere = "";
327   my $item;
328
329   my $category = "AND (";
330   foreach $item (@{$categories}) {
331     $category .= qq|c.category = '$item' OR |;
332   }
333   $category =~ s/OR $/\)/;
334
335   # get headings
336   $query = qq|SELECT c.accno, c.description, c.category
337               FROM chart c
338               WHERE c.charttype = 'H'
339               $category
340               ORDER by c.accno|;
341
342   if ($form->{accounttype} eq 'gifi') {
343     $query = qq|SELECT g.accno, g.description, c.category
344                 FROM gifi g
345                 JOIN chart c ON (c.gifi_accno = g.accno)
346                 WHERE c.charttype = 'H'
347                 $category
348                 ORDER BY g.accno|;
349   }
350
351   $sth = $dbh->prepare($query);
352   $sth->execute || $form->dberror($query);
353
354   my @headingaccounts = ();
355   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
356     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
357       "$ref->{description}";
358     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
359     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
360
361     push @headingaccounts, $ref->{accno};
362   }
363
364   $sth->finish;
365
366   if ($fromdate) {
367     if ($form->{method} eq 'cash') {
368       $subwhere .= " AND transdate >= '$fromdate'";
369       $glwhere = " AND ac.transdate >= '$fromdate'";
370     } else {
371       $where .= " AND ac.transdate >= '$fromdate'";
372     }
373   }
374
375   if ($todate) {
376     $where    .= " AND ac.transdate <= '$todate'";
377     $subwhere .= " AND transdate <= '$todate'";
378   }
379
380   if ($department_id) {
381     $dpt_join = qq|
382                JOIN department t ON (a.department_id = t.id)
383                   |;
384     $dpt_where = qq|
385                AND t.id = $department_id
386                    |;
387   }
388
389   if ($form->{project_id}) {
390     $project = qq|
391                  AND ac.project_id = $form->{project_id}
392                  |;
393   }
394
395   if ($form->{accounttype} eq 'gifi') {
396
397     if ($form->{method} eq 'cash') {
398
399       $query = qq|
400
401                  SELECT g.accno, sum(ac.amount) AS amount,
402                  g.description, c.category
403                  FROM acc_trans ac
404                  JOIN chart c ON (c.id = ac.chart_id)
405                  JOIN ar a ON (a.id = ac.trans_id)
406                  JOIN gifi g ON (g.accno = c.gifi_accno)
407                  $dpt_join
408                  WHERE $where
409                  $dpt_where
410                  $category
411                  AND ac.trans_id IN
412                    (
413                      SELECT trans_id
414                      FROM acc_trans
415                      JOIN chart ON (chart_id = id)
416                      WHERE link LIKE '%AR_paid%'
417                      $subwhere
418                    )
419                  $project
420                  GROUP BY g.accno, g.description, c.category
421
422        UNION ALL
423
424                  SELECT '' AS accno, SUM(ac.amount) AS amount,
425                  '' AS description, c.category
426                  FROM acc_trans ac
427                  JOIN chart c ON (c.id = ac.chart_id)
428                  JOIN ar a ON (a.id = ac.trans_id)
429                  $dpt_join
430                  WHERE $where
431                  $dpt_where
432                  $category
433                  AND c.gifi_accno = ''
434                  AND ac.trans_id IN
435                    (
436                      SELECT trans_id
437                      FROM acc_trans
438                      JOIN chart ON (chart_id = id)
439                      WHERE link LIKE '%AR_paid%'
440                      $subwhere
441                    )
442                  $project
443                  GROUP BY c.category
444
445        UNION ALL
446
447                  SELECT g.accno, sum(ac.amount) AS amount,
448                  g.description, c.category
449                  FROM acc_trans ac
450                  JOIN chart c ON (c.id = ac.chart_id)
451                  JOIN ap a ON (a.id = ac.trans_id)
452                  JOIN gifi g ON (g.accno = c.gifi_accno)
453                  $dpt_join
454                  WHERE $where
455                  $dpt_where
456                  $category
457                  AND ac.trans_id IN
458                    (
459                      SELECT trans_id
460                      FROM acc_trans
461                      JOIN chart ON (chart_id = id)
462                      WHERE link LIKE '%AP_paid%'
463                      $subwhere
464                    )
465                  $project
466                  GROUP BY g.accno, g.description, c.category
467
468        UNION ALL
469
470                  SELECT '' AS accno, SUM(ac.amount) AS amount,
471                  '' AS description, c.category
472                  FROM acc_trans ac
473                  JOIN chart c ON (c.id = ac.chart_id)
474                  JOIN ap a ON (a.id = ac.trans_id)
475                  $dpt_join
476                  WHERE $where
477                  $dpt_where
478                  $category
479                  AND c.gifi_accno = ''
480                  AND ac.trans_id IN
481                    (
482                      SELECT trans_id
483                      FROM acc_trans
484                      JOIN chart ON (chart_id = id)
485                      WHERE link LIKE '%AP_paid%'
486                      $subwhere
487                    )
488                  $project
489                  GROUP BY c.category
490
491        UNION ALL
492
493 -- add gl
494
495                  SELECT g.accno, sum(ac.amount) AS amount,
496                  g.description, c.category
497                  FROM acc_trans ac
498                  JOIN chart c ON (c.id = ac.chart_id)
499                  JOIN gifi g ON (g.accno = c.gifi_accno)
500                  JOIN gl a ON (a.id = ac.trans_id)
501                  $dpt_join
502                  WHERE $where
503                  $glwhere
504                  $dpt_where
505                  $category
506                  AND NOT (c.link = 'AR' OR c.link = 'AP')
507                  $project
508                  GROUP BY g.accno, g.description, c.category
509
510        UNION ALL
511
512                  SELECT '' AS accno, SUM(ac.amount) AS amount,
513                  '' AS description, c.category
514                  FROM acc_trans ac
515                  JOIN chart c ON (c.id = ac.chart_id)
516                  JOIN gl a ON (a.id = ac.trans_id)
517                  $dpt_join
518                  WHERE $where
519                  $glwhere
520                  $dpt_where
521                  $category
522                  AND c.gifi_accno = ''
523                  AND NOT (c.link = 'AR' OR c.link = 'AP')
524                  $project
525                  GROUP BY c.category
526                  |;
527
528       if ($form->{project_id}) {
529
530         $query .= qq|
531
532        UNION ALL
533
534                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
535                  g.description AS description, c.category
536                  FROM invoice ac
537                  JOIN ar a ON (a.id = ac.trans_id)
538                  JOIN parts p ON (ac.parts_id = p.id)
539                  JOIN chart c on (p.income_accno_id = c.id)
540                  JOIN gifi g ON (g.accno = c.gifi_accno)
541                  $dpt_join
542         -- use transdate from subwhere
543                  WHERE 1 = 1 $subwhere
544                  AND c.category = 'I'
545                  $dpt_where
546                  AND ac.trans_id IN
547                    (
548                      SELECT trans_id
549                      FROM acc_trans
550                      JOIN chart ON (chart_id = id)
551                      WHERE link LIKE '%AR_paid%'
552                      $subwhere
553                    )
554                  $project
555                  GROUP BY g.accno, g.description, c.category
556
557        UNION ALL
558
559                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount,
560                  g.description AS description, c.category
561                  FROM invoice ac
562                  JOIN ap a ON (a.id = ac.trans_id)
563                  JOIN parts p ON (ac.parts_id = p.id)
564                  JOIN chart c on (p.expense_accno_id = c.id)
565                  JOIN gifi g ON (g.accno = c.gifi_accno)
566                  $dpt_join
567                  WHERE 1 = 1 $subwhere
568                  AND c.category = 'E'
569                  $dpt_where
570                  AND ac.trans_id IN
571                    (
572                      SELECT trans_id
573                      FROM acc_trans
574                      JOIN chart ON (chart_id = id)
575                      WHERE link LIKE '%AP_paid%'
576                      $subwhere
577                    )
578                  $project
579                  GROUP BY g.accno, g.description, c.category
580                  |;
581       }
582
583     } else {
584
585       if ($department_id) {
586         $dpt_join = qq|
587               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
588               |;
589         $dpt_where = qq|
590                AND t.department_id = $department_id
591               |;
592
593       }
594
595       $query = qq|
596
597               SELECT g.accno, SUM(ac.amount) AS amount,
598               g.description, c.category
599               FROM acc_trans ac
600               JOIN chart c ON (c.id = ac.chart_id)
601               JOIN gifi g ON (c.gifi_accno = g.accno)
602               $dpt_join
603               WHERE $where
604               $dpt_from
605               $category
606               $project
607               GROUP BY g.accno, g.description, c.category
608
609            UNION ALL
610
611               SELECT '' AS accno, SUM(ac.amount) AS amount,
612               '' AS description, c.category
613               FROM acc_trans ac
614               JOIN chart c ON (c.id = ac.chart_id)
615               $dpt_join
616               WHERE $where
617               $dpt_from
618               $category
619               AND c.gifi_accno = ''
620               $project
621               GROUP BY c.category
622               |;
623
624       if ($form->{project_id}) {
625
626         $query .= qq|
627
628          UNION ALL
629
630                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
631                  g.description AS description, c.category
632                  FROM invoice ac
633                  JOIN ar a ON (a.id = ac.trans_id)
634                  JOIN parts p ON (ac.parts_id = p.id)
635                  JOIN chart c on (p.income_accno_id = c.id)
636                  JOIN gifi g ON (c.gifi_accno = g.accno)
637                  $dpt_join
638         -- use transdate from subwhere
639                  WHERE 1 = 1 $subwhere
640                  AND c.category = 'I'
641                  $dpt_where
642                  $project
643                  GROUP BY g.accno, g.description, c.category
644
645        UNION ALL
646
647                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount,
648                  g.description AS description, c.category
649                  FROM invoice ac
650                  JOIN ap a ON (a.id = ac.trans_id)
651                  JOIN parts p ON (ac.parts_id = p.id)
652                  JOIN chart c on (p.expense_accno_id = c.id)
653                  JOIN gifi g ON (c.gifi_accno = g.accno)
654                  $dpt_join
655                  WHERE 1 = 1 $subwhere
656                  AND c.category = 'E'
657                  $dpt_where
658                  $project
659                  GROUP BY g.accno, g.description, c.category
660                  |;
661       }
662
663     }
664
665   } else {    # standard account
666
667     if ($form->{method} eq 'cash') {
668
669       $query = qq|
670
671                  SELECT c.accno, sum(ac.amount) AS amount,
672                  c.description, c.category
673                  FROM acc_trans ac
674                  JOIN chart c ON (c.id = ac.chart_id)
675                  JOIN ar a ON (a.id = ac.trans_id)
676                  $dpt_join
677                  WHERE $where
678                  $dpt_where
679                  $category
680                  AND ac.trans_id IN
681                    (
682                      SELECT trans_id
683                      FROM acc_trans
684                      JOIN chart ON (chart_id = id)
685                      WHERE link LIKE '%AR_paid%'
686                      $subwhere
687                    )
688
689                  $project
690                  GROUP BY c.accno, c.description, c.category
691
692         UNION ALL
693
694                  SELECT c.accno, sum(ac.amount) AS amount,
695                  c.description, c.category
696                  FROM acc_trans ac
697                  JOIN chart c ON (c.id = ac.chart_id)
698                  JOIN ap a ON (a.id = ac.trans_id)
699                  $dpt_join
700                  WHERE $where
701                  $dpt_where
702                  $category
703                  AND ac.trans_id IN
704                    (
705                      SELECT trans_id
706                      FROM acc_trans
707                      JOIN chart ON (chart_id = id)
708                      WHERE link LIKE '%AP_paid%'
709                      $subwhere
710                    )
711
712                  $project
713                  GROUP BY c.accno, c.description, c.category
714
715         UNION ALL
716
717                  SELECT c.accno, sum(ac.amount) AS amount,
718                  c.description, c.category
719                  FROM acc_trans ac
720                  JOIN chart c ON (c.id = ac.chart_id)
721                  JOIN gl a ON (a.id = ac.trans_id)
722                  $dpt_join
723                  WHERE $where
724                  $glwhere
725                  $dpt_from
726                  $category
727                  AND NOT (c.link = 'AR' OR c.link = 'AP')
728                  $project
729                  GROUP BY c.accno, c.description, c.category
730                  |;
731
732       if ($form->{project_id}) {
733
734         $query .= qq|
735
736          UNION ALL
737
738                  SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
739                  c.description AS description, c.category
740                  FROM invoice ac
741                  JOIN ar a ON (a.id = ac.trans_id)
742                  JOIN parts p ON (ac.parts_id = p.id)
743                  JOIN chart c on (p.income_accno_id = c.id)
744                  $dpt_join
745         -- use transdate from subwhere
746                  WHERE 1 = 1 $subwhere
747                  AND c.category = 'I'
748                  $dpt_where
749                  AND ac.trans_id IN
750                    (
751                      SELECT trans_id
752                      FROM acc_trans
753                      JOIN chart ON (chart_id = id)
754                      WHERE link LIKE '%AR_paid%'
755                      $subwhere
756                    )
757
758                  $project
759                  GROUP BY c.accno, c.description, c.category
760
761          UNION ALL
762
763                  SELECT c.accno AS accno, SUM(ac.sellprice) AS amount,
764                  c.description AS description, c.category
765                  FROM invoice ac
766                  JOIN ap a ON (a.id = ac.trans_id)
767                  JOIN parts p ON (ac.parts_id = p.id)
768                  JOIN chart c on (p.expense_accno_id = c.id)
769                  $dpt_join
770                  WHERE 1 = 1 $subwhere
771                  AND c.category = 'E'
772                  $dpt_where
773                  AND ac.trans_id IN
774                    (
775                      SELECT trans_id
776                      FROM acc_trans
777                      JOIN chart ON (chart_id = id)
778                      WHERE link LIKE '%AP_paid%'
779                      $subwhere
780                    )
781
782                  $project
783                  GROUP BY c.accno, c.description, c.category
784                  |;
785       }
786
787     } else {
788
789       if ($department_id) {
790         $dpt_join = qq|
791               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
792               |;
793         $dpt_where = qq|
794                AND t.department_id = $department_id
795               |;
796       }
797
798       $query = qq|
799
800                  SELECT c.accno, sum(ac.amount) AS amount,
801                  c.description, c.category
802                  FROM acc_trans ac
803                  JOIN chart c ON (c.id = ac.chart_id)
804                  $dpt_join
805                  WHERE $where
806                  $dpt_where
807                  $category
808                  $project
809                  GROUP BY c.accno, c.description, c.category
810                  |;
811
812       if ($form->{project_id}) {
813
814         $query .= qq|
815
816         UNION ALL
817
818                  SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
819                  c.description AS description, c.category
820                  FROM invoice ac
821                  JOIN ar a ON (a.id = ac.trans_id)
822                  JOIN parts p ON (ac.parts_id = p.id)
823                  JOIN chart c on (p.income_accno_id = c.id)
824                  $dpt_join
825         -- use transdate from subwhere
826                  WHERE 1 = 1 $subwhere
827                  AND c.category = 'I'
828                  $dpt_where
829                  $project
830                  GROUP BY c.accno, c.description, c.category
831
832         UNION ALL
833
834                  SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount,
835                  c.description AS description, c.category
836                  FROM invoice ac
837                  JOIN ap a ON (a.id = ac.trans_id)
838                  JOIN parts p ON (ac.parts_id = p.id)
839                  JOIN chart c on (p.expense_accno_id = c.id)
840                  $dpt_join
841                  WHERE 1 = 1 $subwhere
842                  AND c.category = 'E'
843                  $dpt_where
844                  $project
845                  GROUP BY c.accno, c.description, c.category
846                  |;
847
848       }
849     }
850   }
851
852   my @accno;
853   my $accno;
854   my $ref;
855
856   my $sth = $dbh->prepare($query);
857   $sth->execute || $form->dberror($query);
858
859   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
860
861     if ($ref->{category} eq 'C') {
862       $ref->{category} = 'A';
863     }
864
865     # get last heading account
866     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
867     $accno = pop @accno;
868     if ($accno) {
869       if ($last_period) {
870         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
871       } else {
872         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
873       }
874     }
875
876     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
877     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
878       $ref->{description};
879     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
880
881     if ($last_period) {
882       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
883     } else {
884       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
885     }
886   }
887   $sth->finish;
888
889   # remove accounts with zero balance
890   foreach $category (@{$categories}) {
891     foreach $accno (keys %{ $form->{$category} }) {
892       $form->{$category}{$accno}{last} =
893         $form->round_amount($form->{$category}{$accno}{last},
894                             $form->{decimalplaces});
895       $form->{$category}{$accno}{this} =
896         $form->round_amount($form->{$category}{$accno}{this},
897                             $form->{decimalplaces});
898
899       delete $form->{$category}{$accno}
900         if (   $form->{$category}{$accno}{this} == 0
901             && $form->{$category}{$accno}{last} == 0);
902     }
903   }
904
905   $main::lxdebug->leave_sub();
906 }
907
908 sub get_accounts_g {
909   $main::lxdebug->enter_sub();
910
911   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
912
913   my ($null, $department_id) = split /--/, $form->{department};
914
915   my $query;
916   my $dpt_where;
917   my $dpt_join;
918   my $project;
919   my $where    = "1 = 1";
920   my $glwhere  = "";
921   my $prwhere  = "";
922   my $subwhere = "";
923   my $item;
924
925   if ($fromdate) {
926     if ($form->{method} eq 'cash') {
927       $subwhere .= " AND transdate >= '$fromdate'";
928       $glwhere = " AND ac.transdate >= '$fromdate'";
929       $prwhere = " AND ar.transdate >= '$fromdate'";
930     } else {
931       $where .= " AND ac.transdate >= '$fromdate'";
932     }
933   }
934
935   if ($todate) {
936     $where    .= " AND ac.transdate <= '$todate'";
937     $subwhere .= " AND transdate <= '$todate'";
938     $prwhere  .= " AND ar.transdate <= '$todate'";
939   }
940
941   if ($department_id) {
942     $dpt_join = qq|
943                JOIN department t ON (a.department_id = t.id)
944                   |;
945     $dpt_where = qq|
946                AND t.id = $department_id
947                    |;
948   }
949
950   if ($form->{project_id}) {
951     $project = qq|
952                  AND ac.project_id = $form->{project_id}
953                  |;
954   }
955
956   if ($form->{method} eq 'cash') {
957
958     $query = qq|
959
960                  SELECT sum(ac.amount) AS amount,
961                  c.$category
962                  FROM acc_trans ac
963                  JOIN chart c ON (c.id = ac.chart_id)
964                  JOIN ar a ON (a.id = ac.trans_id)
965                  $dpt_join
966                  WHERE $where
967                  $dpt_where
968                  AND ac.trans_id IN
969                    (
970                      SELECT trans_id
971                      FROM acc_trans
972                      JOIN chart ON (chart_id = id)
973                      WHERE link LIKE '%AR_paid%'
974                      $subwhere
975                    )
976
977                  $project
978                  GROUP BY c.$category
979
980         UNION
981
982                  SELECT sum(ac.amount) AS amount,
983                  c.$category
984                  FROM acc_trans ac
985                  JOIN chart c ON (c.id = ac.chart_id)
986                  JOIN ap a ON (a.id = ac.trans_id)
987                  $dpt_join
988                  WHERE $where
989                  $dpt_where
990                  AND ac.trans_id IN
991                    (
992                      SELECT trans_id
993                      FROM acc_trans
994                      JOIN chart ON (chart_id = id)
995                      WHERE link LIKE '%AP_paid%'
996                      $subwhere
997                    )
998
999                  $project
1000                  GROUP BY c.$category
1001
1002         UNION
1003
1004                  SELECT sum(ac.amount) AS amount,
1005                  c.$category
1006                  FROM acc_trans ac
1007                  JOIN chart c ON (c.id = ac.chart_id)
1008                  JOIN gl a ON (a.id = ac.trans_id)
1009                  $dpt_join
1010                  WHERE $where
1011                  $glwhere
1012                  $dpt_from
1013                  AND NOT (c.link = 'AR' OR c.link = 'AP')
1014                  $project
1015                  GROUP BY c.$category
1016                  |;
1017
1018     if ($form->{project_id}) {
1019
1020       $query .= qq|
1021
1022          UNION
1023
1024                  SELECT SUM(ac.sellprice * ac.qty) AS amount,
1025                  c.$category
1026                  FROM invoice ac
1027                  JOIN ar a ON (a.id = ac.trans_id)
1028                  JOIN parts p ON (ac.parts_id = p.id)
1029                  JOIN chart c on (p.income_accno_id = c.id)
1030                  $dpt_join
1031                  WHERE 1 = 1 $prwhere
1032                  AND c.category = 'I'
1033                  $dpt_where
1034                  AND ac.trans_id IN
1035                    (
1036                      SELECT trans_id
1037                      FROM acc_trans
1038                      JOIN chart ON (chart_id = id)
1039                      WHERE link LIKE '%AR_paid%'
1040                      $subwhere
1041                    )
1042
1043                  $project
1044                  GROUP BY c.$category
1045
1046          UNION
1047
1048                  SELECT SUM(ac.sellprice) AS amount,
1049                  c.$category
1050                  FROM invoice ac
1051                  JOIN ap a ON (a.id = ac.trans_id)
1052                  JOIN parts p ON (ac.parts_id = p.id)
1053                  JOIN chart c on (p.expense_accno_id = c.id)
1054                  $dpt_join
1055                  WHERE 1 = 1 $prwhere
1056                  AND c.category = 'E'
1057                  $dpt_where
1058                  AND ac.trans_id IN
1059                    (
1060                      SELECT trans_id
1061                      FROM acc_trans
1062                      JOIN chart ON (chart_id = id)
1063                      WHERE link LIKE '%AP_paid%'
1064                      $subwhere
1065                    )
1066
1067                  $project
1068                  GROUP BY c.$category
1069                  |;
1070     }
1071
1072   } else {
1073
1074     if ($department_id) {
1075       $dpt_join = qq|
1076               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
1077               |;
1078       $dpt_where = qq|
1079                AND t.department_id = $department_id
1080               |;
1081     }
1082
1083     $query = qq|
1084
1085                  SELECT sum(ac.amount) AS amount,
1086                  c.$category
1087                  FROM acc_trans ac
1088                  JOIN chart c ON (c.id = ac.chart_id)
1089                  $dpt_join
1090                  WHERE $where
1091                  $dpt_where
1092                  $project
1093                  GROUP BY c.$category
1094                  |;
1095
1096     if ($form->{project_id}) {
1097
1098       $query .= qq|
1099
1100         UNION
1101
1102                  SELECT SUM(ac.sellprice * ac.qty) AS amount,
1103                  c.$category
1104                  FROM invoice ac
1105                  JOIN ar a ON (a.id = ac.trans_id)
1106                  JOIN parts p ON (ac.parts_id = p.id)
1107                  JOIN chart c on (p.income_accno_id = c.id)
1108                  $dpt_join
1109                  WHERE 1 = 1 $prwhere
1110                  AND c.category = 'I'
1111                  $dpt_where
1112                  $project
1113                  GROUP BY c.$category
1114
1115         UNION
1116
1117                  SELECT SUM(ac.sellprice * ac.qty) * -1 AS amount,
1118                  c.$category
1119                  FROM invoice ac
1120                  JOIN ap a ON (a.id = ac.trans_id)
1121                  JOIN parts p ON (ac.parts_id = p.id)
1122                  JOIN chart c on (p.expense_accno_id = c.id)
1123                  $dpt_join
1124                  WHERE 1 = 1 $prwhere
1125                  AND c.category = 'E'
1126                  $dpt_where
1127                  $project
1128                  GROUP BY c.$category
1129                  |;
1130
1131     }
1132   }
1133
1134   my @accno;
1135   my $accno;
1136   my $ref;
1137
1138   #print $query;
1139   my $sth = $dbh->prepare($query);
1140   $sth->execute || $form->dberror($query);
1141
1142   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1143     if ($ref->{amount} < 0) {
1144       $ref->{amount} *= -1;
1145     }
1146     if ($category eq "pos_bwa") {
1147       if ($last_period) {
1148         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
1149       } else {
1150         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
1151       }
1152     } else {
1153       $form->{ $ref->{$category} } += $ref->{amount};
1154     }
1155   }
1156   $sth->finish;
1157
1158   $main::lxdebug->leave_sub();
1159 }
1160
1161 sub trial_balance {
1162   $main::lxdebug->enter_sub();
1163
1164   my ($self, $myconfig, $form) = @_;
1165
1166   my $dbh = $form->dbconnect($myconfig);
1167
1168   my ($query, $sth, $ref);
1169   my %balance = ();
1170   my %trb     = ();
1171   my ($null, $department_id) = split /--/, $form->{department};
1172   my @headingaccounts = ();
1173   my $dpt_where;
1174   my $dpt_join;
1175   my $project;
1176
1177   my $where    = "1 = 1";
1178   my $invwhere = $where;
1179
1180   if ($department_id) {
1181     $dpt_join = qq|
1182                 JOIN dpt_trans t ON (ac.trans_id = t.trans_id)
1183                   |;
1184     $dpt_where = qq|
1185                 AND t.department_id = $department_id
1186                 |;
1187   }
1188
1189   # project_id only applies to getting transactions
1190   # it has nothing to do with a trial balance
1191   # but we use the same function to collect information
1192
1193   if ($form->{project_id}) {
1194     $project = qq|
1195                 AND ac.project_id = $form->{project_id}
1196                 |;
1197   }
1198
1199   # get beginning balances
1200   if ($form->{fromdate}) {
1201
1202     if ($form->{accounttype} eq 'gifi') {
1203
1204       $query = qq|SELECT g.accno, c.category, SUM(ac.amount) AS amount,
1205                   g.description
1206                   FROM acc_trans ac
1207                   JOIN chart c ON (ac.chart_id = c.id)
1208                   JOIN gifi g ON (c.gifi_accno = g.accno)
1209                   $dpt_join
1210                   WHERE ac.transdate < '$form->{fromdate}'
1211                   $dpt_where
1212                   $project
1213                   GROUP BY g.accno, c.category, g.description
1214                   |;
1215
1216     } else {
1217
1218       $query = qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount,
1219                   c.description
1220                   FROM acc_trans ac
1221                   JOIN chart c ON (ac.chart_id = c.id)
1222                   $dpt_join
1223                   WHERE ac.transdate < '$form->{fromdate}'
1224                   $dpt_where
1225                   $project
1226                   GROUP BY c.accno, c.category, c.description
1227                   |;
1228
1229     }
1230
1231     $sth = $dbh->prepare($query);
1232     $sth->execute || $form->dberror($query);
1233
1234     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1235       $balance{ $ref->{accno} } = $ref->{amount};
1236
1237       if ($ref->{amount} != 0 && $form->{all_accounts}) {
1238         $trb{ $ref->{accno} }{description} = $ref->{description};
1239         $trb{ $ref->{accno} }{charttype}   = 'A';
1240         $trb{ $ref->{accno} }{category}    = $ref->{category};
1241       }
1242
1243     }
1244     $sth->finish;
1245
1246   }
1247
1248   # get headings
1249   $query = qq|SELECT c.accno, c.description, c.category
1250               FROM chart c
1251               WHERE c.charttype = 'H'
1252               ORDER by c.accno|;
1253
1254   if ($form->{accounttype} eq 'gifi') {
1255     $query = qq|SELECT g.accno, g.description, c.category
1256                 FROM gifi g
1257                 JOIN chart c ON (c.gifi_accno = g.accno)
1258                 WHERE c.charttype = 'H'
1259                 ORDER BY g.accno|;
1260   }
1261
1262   $sth = $dbh->prepare($query);
1263   $sth->execute || $form->dberror($query);
1264
1265   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1266     $trb{ $ref->{accno} }{description} = $ref->{description};
1267     $trb{ $ref->{accno} }{charttype}   = 'H';
1268     $trb{ $ref->{accno} }{category}    = $ref->{category};
1269
1270     push @headingaccounts, $ref->{accno};
1271   }
1272
1273   $sth->finish;
1274
1275   $where = " 1 = 1 ";
1276
1277   if ($form->{fromdate} || $form->{todate}) {
1278     if ($form->{fromdate}) {
1279       $tofrom   .= " AND ac.transdate >= '$form->{fromdate}'";
1280       $subwhere .= " AND transdate >= '$form->{fromdate}'";
1281       $invwhere .= " AND a.transdate >= '$form->{fromdate}'";
1282       $glwhere = " AND ac.transdate >= '$form->{fromdate}'";
1283     }
1284     if ($form->{todate}) {
1285       $tofrom   .= " AND ac.transdate <= '$form->{todate}'";
1286       $invwhere .= " AND a.transdate <= '$form->{todate}'";
1287       $subwhere .= " AND transdate <= '$form->{todate}'";
1288       $glwhere  .= " AND ac.transdate <= '$form->{todate}'";
1289     }
1290   }
1291   if ($form->{eur}) {
1292     $where .= qq| AND ((ac.trans_id in (SELECT id from ar)
1293                   AND ac.trans_id IN
1294                    (
1295                      SELECT trans_id
1296                      FROM acc_trans
1297                      JOIN chart ON (chart_id = id)
1298                      WHERE link LIKE '%AR_paid%'
1299                      $subwhere
1300                    )) OR (ac.trans_id in (SELECT id from ap)
1301                    AND ac.trans_id IN
1302                    (
1303                      SELECT trans_id
1304                      FROM acc_trans
1305                      JOIN chart ON (chart_id = id)
1306                      WHERE link LIKE '%AP_paid%'
1307                      $subwhere
1308                    )) OR (ac.trans_id in (SELECT id from gl)
1309                    $glwhere))|;
1310   } else {
1311     $where .= $tofrom;
1312   }
1313
1314   if ($form->{accounttype} eq 'gifi') {
1315
1316     $query = qq|SELECT g.accno, g.description, c.category,
1317                 SUM(ac.amount) AS amount
1318                 FROM acc_trans ac
1319                 JOIN chart c ON (c.id = ac.chart_id)
1320                 JOIN gifi g ON (c.gifi_accno = g.accno)
1321                 $dpt_join
1322                 WHERE $where
1323                 $dpt_where
1324                 $project
1325                 GROUP BY g.accno, g.description, c.category
1326                 |;
1327
1328     if ($form->{project_id}) {
1329
1330       $query .= qq|
1331
1332         -- add project transactions from invoice
1333
1334         UNION ALL
1335
1336                 SELECT g.accno, g.description, c.category,
1337                 SUM(ac.sellprice * ac.qty) AS amount
1338                 FROM invoice ac
1339                 JOIN ar a ON (ac.trans_id = a.id)
1340                 JOIN parts p ON (ac.parts_id = p.id)
1341                 JOIN chart c ON (p.income_accno_id = c.id)
1342                 JOIN gifi g ON (c.gifi_accno = g.accno)
1343                 $dpt_join
1344                 WHERE $invwhere
1345                 $dpt_where
1346                 $project
1347                 GROUP BY g.accno, g.description, c.category
1348
1349         UNION ALL
1350
1351                 SELECT g.accno, g.description, c.category,
1352                 SUM(ac.sellprice * ac.qty) * -1 AS amount
1353                 FROM invoice ac
1354                 JOIN ap a ON (ac.trans_id = a.id)
1355                 JOIN parts p ON (ac.parts_id = p.id)
1356                 JOIN chart c ON (p.expense_accno_id = c.id)
1357                 JOIN gifi g ON (c.gifi_accno = g.accno)
1358                 $dpt_join
1359                 WHERE $invwhere
1360                 $dpt_where
1361                 $project
1362                 GROUP BY g.accno, g.description, c.category
1363                 |;
1364     }
1365
1366     $query .= qq|
1367                 ORDER BY accno|;
1368
1369   } else {
1370
1371     $query = qq|SELECT c.accno, c.description, c.category,
1372                 SUM(ac.amount) AS amount
1373                 FROM acc_trans ac
1374                 JOIN chart c ON (c.id = ac.chart_id)
1375                 $dpt_join
1376                 WHERE $where
1377                 $dpt_where
1378                 $project
1379                 GROUP BY c.accno, c.description, c.category
1380                 |;
1381
1382     if ($form->{project_id}) {
1383
1384       $query .= qq|
1385
1386         -- add project transactions from invoice
1387
1388         UNION ALL
1389
1390                 SELECT c.accno, c.description, c.category,
1391                 SUM(ac.sellprice * ac.qty) AS amount
1392                 FROM invoice ac
1393                 JOIN ar a ON (ac.trans_id = a.id)
1394                 JOIN parts p ON (ac.parts_id = p.id)
1395                 JOIN chart c ON (p.income_accno_id = c.id)
1396                 $dpt_join
1397                 WHERE $invwhere
1398                 $dpt_where
1399                 $project
1400                 GROUP BY c.accno, c.description, c.category
1401
1402         UNION ALL
1403
1404                 SELECT c.accno, c.description, c.category,
1405                 SUM(ac.sellprice * ac.qty) * -1 AS amount
1406                 FROM invoice ac
1407                 JOIN ap a ON (ac.trans_id = a.id)
1408                 JOIN parts p ON (ac.parts_id = p.id)
1409                 JOIN chart c ON (p.expense_accno_id = c.id)
1410                 $dpt_join
1411                 WHERE $invwhere
1412                 $dpt_where
1413                 $project
1414                 GROUP BY c.accno, c.description, c.category
1415                 |;
1416     }
1417
1418     $query .= qq|
1419                 ORDER BY accno|;
1420
1421   }
1422
1423   $sth = $dbh->prepare($query);
1424   $sth->execute || $form->dberror($query);
1425
1426   # prepare query for each account
1427   $query = qq|SELECT (SELECT SUM(ac.amount) * -1
1428               FROM acc_trans ac
1429               JOIN chart c ON (c.id = ac.chart_id)
1430               $dpt_join
1431               WHERE $where
1432               $dpt_where
1433               $project
1434               AND ac.amount < 0
1435               AND c.accno = ?) AS debit,
1436
1437              (SELECT SUM(ac.amount)
1438               FROM acc_trans ac
1439               JOIN chart c ON (c.id = ac.chart_id)
1440               $dpt_join
1441               WHERE $where
1442               $dpt_where
1443               $project
1444               AND ac.amount > 0
1445               AND c.accno = ?) AS credit
1446               |;
1447
1448   if ($form->{accounttype} eq 'gifi') {
1449
1450     $query = qq|SELECT (SELECT SUM(ac.amount) * -1
1451                 FROM acc_trans ac
1452                 JOIN chart c ON (c.id = ac.chart_id)
1453                 $dpt_join
1454                 WHERE $where
1455                 $dpt_where
1456                 $project
1457                 AND ac.amount < 0
1458                 AND c.gifi_accno = ?) AS debit,
1459
1460                (SELECT SUM(ac.amount)
1461                 FROM acc_trans ac
1462                 JOIN chart c ON (c.id = ac.chart_id)
1463                 $dpt_join
1464                 WHERE $where
1465                 $dpt_where
1466                 $project
1467                 AND ac.amount > 0
1468                 AND c.gifi_accno = ?) AS credit|;
1469
1470   }
1471
1472   $drcr = $dbh->prepare($query);
1473
1474   if ($form->{project_id}) {
1475
1476     # prepare query for each account
1477     $query = qq|SELECT (SELECT SUM(ac.sellprice * ac.qty) * -1
1478               FROM invoice ac
1479               JOIN parts p ON (ac.parts_id = p.id)
1480               JOIN ap a ON (ac.trans_id = a.id)
1481               JOIN chart c ON (p.expense_accno_id = c.id)
1482               $dpt_join
1483               WHERE $invwhere
1484               $dpt_where
1485               $project
1486               AND c.accno = ?) AS debit,
1487
1488              (SELECT SUM(ac.sellprice * ac.qty)
1489               FROM invoice ac
1490               JOIN parts p ON (ac.parts_id = p.id)
1491               JOIN ar a ON (ac.trans_id = a.id)
1492               JOIN chart c ON (p.income_accno_id = c.id)
1493               $dpt_join
1494               WHERE $invwhere
1495               $dpt_where
1496               $project
1497               AND c.accno = ?) AS credit
1498               |;
1499
1500     $project_drcr = $dbh->prepare($query);
1501
1502   }
1503
1504   # calculate the debit and credit in the period
1505   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1506     $trb{ $ref->{accno} }{description} = $ref->{description};
1507     $trb{ $ref->{accno} }{charttype}   = 'A';
1508     $trb{ $ref->{accno} }{category}    = $ref->{category};
1509     $trb{ $ref->{accno} }{amount} += $ref->{amount};
1510   }
1511   $sth->finish;
1512
1513   my ($debit, $credit);
1514
1515   foreach my $accno (sort keys %trb) {
1516     $ref = ();
1517
1518     $ref->{accno} = $accno;
1519     map { $ref->{$_} = $trb{$accno}{$_} }
1520       qw(description category charttype amount);
1521
1522     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
1523
1524     if ($trb{$accno}{charttype} eq 'A') {
1525
1526       # get DR/CR
1527       $drcr->execute($ref->{accno}, $ref->{accno}) || $form->dberror($query);
1528
1529       ($debit, $credit) = (0, 0);
1530       while (($debit, $credit) = $drcr->fetchrow_array) {
1531         $ref->{debit}  += $debit;
1532         $ref->{credit} += $credit;
1533       }
1534       $drcr->finish;
1535
1536       if ($form->{project_id}) {
1537
1538         # get DR/CR
1539         $project_drcr->execute($ref->{accno}, $ref->{accno})
1540           || $form->dberror($query);
1541
1542         ($debit, $credit) = (0, 0);
1543         while (($debit, $credit) = $project_drcr->fetchrow_array) {
1544           $ref->{debit}  += $debit;
1545           $ref->{credit} += $credit;
1546         }
1547         $project_drcr->finish;
1548       }
1549
1550       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
1551       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
1552
1553     }
1554
1555     # add subtotal
1556     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
1557     $accno = pop @accno;
1558     if ($accno) {
1559       $trb{$accno}{debit}  += $ref->{debit};
1560       $trb{$accno}{credit} += $ref->{credit};
1561     }
1562
1563     push @{ $form->{TB} }, $ref;
1564
1565   }
1566
1567   $dbh->disconnect;
1568
1569   # debits and credits for headings
1570   foreach $accno (@headingaccounts) {
1571     foreach $ref (@{ $form->{TB} }) {
1572       if ($accno eq $ref->{accno}) {
1573         $ref->{debit}  = $trb{$accno}{debit};
1574         $ref->{credit} = $trb{$accno}{credit};
1575       }
1576     }
1577   }
1578
1579   $main::lxdebug->leave_sub();
1580 }
1581
1582 sub aging {
1583   $main::lxdebug->enter_sub();
1584
1585   my ($self, $myconfig, $form) = @_;
1586
1587   # connect to database
1588   my $dbh     = $form->dbconnect($myconfig);
1589   my $invoice = ($form->{arap} eq 'ar') ? 'is' : 'ir';
1590
1591   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
1592
1593   my $where = "1 = 1";
1594   my ($name, $null);
1595
1596   if ($form->{"$form->{ct}_id"}) {
1597     $where .= qq| AND ct.id = $form->{"$form->{ct}_id"}|;
1598   } else {
1599     if ($form->{ $form->{ct} }) {
1600       $name = $form->like(lc $form->{ $form->{ct} });
1601       $where .= qq| AND lower(ct.name) LIKE '$name'| if $form->{ $form->{ct} };
1602     }
1603   }
1604
1605   my $dpt_join;
1606   if ($form->{department}) {
1607     ($null, $department_id) = split /--/, $form->{department};
1608     $dpt_join = qq|
1609                JOIN department d ON (a.department_id = d.id)
1610                   |;
1611
1612     $where .= qq| AND a.department_id = $department_id|;
1613   }
1614
1615   # select outstanding vendors or customers, depends on $ct
1616   my $query = qq|SELECT DISTINCT ct.id, ct.name
1617                  FROM $form->{ct} ct, $form->{arap} a
1618                  $dpt_join
1619                  WHERE $where
1620                  AND a.$form->{ct}_id = ct.id
1621                  AND a.paid != a.amount
1622                  AND (a.transdate <= '$form->{todate}')
1623                  ORDER BY ct.name|;
1624
1625   my $sth = $dbh->prepare($query);
1626   $sth->execute || $form->dberror;
1627
1628   my $buysell = ($form->{arap} eq 'ar') ? 'buy' : 'sell';
1629
1630   # for each company that has some stuff outstanding
1631   while (my ($id) = $sth->fetchrow_array) {
1632
1633     $query = qq|
1634
1635 -- between 0-30 days
1636
1637         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1638         street, zipcode, city, country, contact, email,
1639         phone as customerphone, fax as customerfax, $form->{ct}number,
1640         "invnumber", "transdate",
1641         (amount - paid) as "c0", 0.00 as "c30", 0.00 as "c60", 0.00 as "c90",
1642         "duedate", invoice, $form->{arap}.id,
1643           (SELECT $buysell FROM exchangerate
1644            WHERE $form->{arap}.curr = exchangerate.curr
1645            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1646   FROM $form->{arap}, $form->{ct}
1647         WHERE paid != amount
1648         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1649         AND $form->{ct}.id = $id
1650         AND (
1651                 transdate <= (date '$form->{todate}' - interval '0 days')
1652                 AND transdate >= (date '$form->{todate}' - interval '30 days')
1653             )
1654
1655         UNION
1656
1657 -- between 31-60 days
1658
1659         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1660         street, zipcode, city, country, contact, email,
1661         phone as customerphone, fax as customerfax, $form->{ct}number,
1662         "invnumber", "transdate",
1663         0.00 as "c0", (amount - paid) as "c30", 0.00 as "c60", 0.00 as "c90",
1664         "duedate", invoice, $form->{arap}.id,
1665           (SELECT $buysell FROM exchangerate
1666            WHERE $form->{arap}.curr = exchangerate.curr
1667            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1668   FROM $form->{arap}, $form->{ct}
1669         WHERE paid != amount
1670         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1671         AND $form->{ct}.id = $id
1672         AND (
1673                 transdate < (date '$form->{todate}' - interval '30 days')
1674                 AND transdate >= (date '$form->{todate}' - interval '60 days')
1675                 )
1676
1677         UNION
1678
1679 -- between 61-90 days
1680
1681         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1682         street, zipcode, city, country, contact, email,
1683         phone as customerphone, fax as customerfax, $form->{ct}number,
1684         "invnumber", "transdate",
1685         0.00 as "c0", 0.00 as "c30", (amount - paid) as "c60", 0.00 as "c90",
1686         "duedate", invoice, $form->{arap}.id,
1687           (SELECT $buysell FROM exchangerate
1688            WHERE $form->{arap}.curr = exchangerate.curr
1689            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1690         FROM $form->{arap}, $form->{ct}
1691         WHERE paid != amount
1692         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1693         AND $form->{ct}.id = $id
1694         AND (
1695                 transdate < (date '$form->{todate}' - interval '60 days')
1696                 AND transdate >= (date '$form->{todate}' - interval '90 days')
1697                 )
1698
1699         UNION
1700
1701 -- over 90 days
1702
1703         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1704         street, zipcode, city, country, contact, email,
1705         phone as customerphone, fax as customerfax, $form->{ct}number,
1706         "invnumber", "transdate",
1707         0.00 as "c0", 0.00 as "c30", 0.00 as "c60", (amount - paid) as "c90",
1708         "duedate", invoice, $form->{arap}.id,
1709           (SELECT $buysell FROM exchangerate
1710            WHERE $form->{arap}.curr = exchangerate.curr
1711            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1712         FROM $form->{arap}, $form->{ct}
1713         WHERE paid != amount
1714         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1715         AND $form->{ct}.id = $id
1716         AND transdate < (date '$form->{todate}' - interval '90 days')
1717
1718         ORDER BY
1719
1720   ctid, transdate, invnumber
1721
1722                 |;
1723
1724     my $sth = $dbh->prepare($query);
1725     $sth->execute || $form->dberror;
1726
1727     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1728       $ref->{module} = ($ref->{invoice}) ? $invoice : $form->{arap};
1729       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
1730       push @{ $form->{AG} }, $ref;
1731     }
1732
1733     $sth->finish;
1734
1735   }
1736
1737   $sth->finish;
1738
1739   # disconnect
1740   $dbh->disconnect;
1741
1742   $main::lxdebug->leave_sub();
1743 }
1744
1745 sub get_customer {
1746   $main::lxdebug->enter_sub();
1747
1748   my ($self, $myconfig, $form) = @_;
1749
1750   # connect to database
1751   my $dbh = $form->dbconnect($myconfig);
1752
1753   my $query = qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
1754                  FROM $form->{ct} ct
1755                  WHERE ct.id = $form->{"$form->{ct}_id"}|;
1756   my $sth = $dbh->prepare($query);
1757   $sth->execute || $form->dberror;
1758
1759   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
1760     $sth->fetchrow_array;
1761   $sth->finish;
1762   $dbh->disconnect;
1763
1764   $main::lxdebug->leave_sub();
1765 }
1766
1767 sub get_taxaccounts {
1768   $main::lxdebug->enter_sub();
1769
1770   my ($self, $myconfig, $form) = @_;
1771
1772   # connect to database
1773   my $dbh = $form->dbconnect($myconfig);
1774
1775   # get tax accounts
1776   my $query = qq|SELECT c.accno, c.description, t.rate
1777                  FROM chart c, tax t
1778                  WHERE c.link LIKE '%CT_tax%'
1779                  AND c.id = t.chart_id
1780                  ORDER BY c.accno|;
1781   my $sth = $dbh->prepare($query);
1782   $sth->execute || $form->dberror;
1783
1784   my $ref = ();
1785   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1786     push @{ $form->{taxaccounts} }, $ref;
1787   }
1788   $sth->finish;
1789
1790   # get gifi tax accounts
1791   $query = qq|SELECT DISTINCT ON (g.accno) g.accno, g.description,
1792                  sum(t.rate) AS rate
1793                  FROM gifi g, chart c, tax t
1794                  WHERE g.accno = c.gifi_accno
1795                  AND c.id = t.chart_id
1796                  AND c.link LIKE '%CT_tax%'
1797                  GROUP BY g.accno, g.description
1798                  ORDER BY accno|;
1799   $sth = $dbh->prepare($query);
1800   $sth->execute || $form->dberror;
1801
1802   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1803     push @{ $form->{gifi_taxaccounts} }, $ref;
1804   }
1805   $sth->finish;
1806
1807   $dbh->disconnect;
1808
1809   $main::lxdebug->leave_sub();
1810 }
1811
1812 sub tax_report {
1813   $main::lxdebug->enter_sub();
1814
1815   my ($self, $myconfig, $form) = @_;
1816
1817   # connect to database
1818   my $dbh = $form->dbconnect($myconfig);
1819
1820   my ($null, $department_id) = split /--/, $form->{department};
1821
1822   # build WHERE
1823   my $where = "1 = 1";
1824
1825   if ($department_id) {
1826     $where .= qq|
1827                  AND a.department_id = $department_id
1828                 |;
1829   }
1830
1831   my ($accno, $rate);
1832
1833   if ($form->{accno}) {
1834     if ($form->{accno} =~ /^gifi_/) {
1835       ($null, $accno) = split /_/, $form->{accno};
1836       $rate  = $form->{"$form->{accno}_rate"};
1837       $accno = qq| AND ch.gifi_accno = '$accno'|;
1838     } else {
1839       $accno = $form->{accno};
1840       $rate  = $form->{"$form->{accno}_rate"};
1841       $accno = qq| AND ch.accno = '$accno'|;
1842     }
1843   }
1844   $rate *= 1;
1845
1846   my ($table, $ARAP);
1847
1848   if ($form->{db} eq 'ar') {
1849     $table = "customer";
1850     $ARAP  = "AR";
1851   }
1852   if ($form->{db} eq 'ap') {
1853     $table = "vendor";
1854     $ARAP  = "AP";
1855   }
1856
1857   my $transdate = "a.transdate";
1858
1859   if ($form->{method} eq 'cash') {
1860     $transdate = "a.datepaid";
1861
1862     my $todate =
1863       ($form->{todate}) ? $form->{todate} : $form->current_date($myconfig);
1864
1865     $where .= qq|
1866                  AND ac.trans_id IN
1867                    (
1868                      SELECT trans_id
1869                      FROM acc_trans
1870                      JOIN chart ON (chart_id = id)
1871                      WHERE link LIKE '%${ARAP}_paid%'
1872                      AND transdate <= '$todate'
1873                    )
1874                   |;
1875   }
1876
1877   # if there are any dates construct a where
1878   if ($form->{fromdate} || $form->{todate}) {
1879     if ($form->{fromdate}) {
1880       $where .= " AND $transdate >= '$form->{fromdate}'";
1881     }
1882     if ($form->{todate}) {
1883       $where .= " AND $transdate <= '$form->{todate}'";
1884     }
1885   }
1886
1887   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
1888
1889   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
1890   $sortorder = $form->{sort} if $form->{sort};
1891
1892   $query = qq|SELECT a.id, '0' AS invoice, $transdate AS transdate,
1893               a.invnumber, n.name, a.netamount,
1894               ac.amount * $ml AS tax
1895               FROM acc_trans ac
1896             JOIN $form->{db} a ON (a.id = ac.trans_id)
1897             JOIN chart ch ON (ch.id = ac.chart_id)
1898             JOIN $table n ON (n.id = a.${table}_id)
1899               WHERE $where
1900               $accno
1901               AND a.invoice = '0'
1902             UNION
1903               SELECT a.id, '1' AS invoice, $transdate AS transdate,
1904               a.invnumber, n.name, i.sellprice * i.qty AS netamount,
1905               i.sellprice * i.qty * $rate * $ml AS tax
1906               FROM acc_trans ac
1907             JOIN $form->{db} a ON (a.id = ac.trans_id)
1908             JOIN chart ch ON (ch.id = ac.chart_id)
1909             JOIN $table n ON (n.id = a.${table}_id)
1910             JOIN ${table}tax t ON (t.${table}_id = n.id)
1911             JOIN invoice i ON (i.trans_id = a.id)
1912             JOIN partstax p ON (p.parts_id = i.parts_id)
1913               WHERE $where
1914               $accno
1915               AND a.invoice = '1'
1916               ORDER by $sortorder|;
1917
1918   if ($form->{report} =~ /nontaxable/) {
1919
1920     # only gather up non-taxable transactions
1921     $query = qq|SELECT a.id, '0' AS invoice, $transdate AS transdate,
1922                 a.invnumber, n.name, a.netamount
1923                 FROM acc_trans ac
1924               JOIN $form->{db} a ON (a.id = ac.trans_id)
1925               JOIN $table n ON (n.id = a.${table}_id)
1926                 WHERE $where
1927                 AND a.invoice = '0'
1928                 AND a.netamount = a.amount
1929               UNION
1930                 SELECT a.id, '1' AS invoice, $transdate AS transdate,
1931                 a.invnumber, n.name, i.sellprice * i.qty AS netamount
1932                 FROM acc_trans ac
1933               JOIN $form->{db} a ON (a.id = ac.trans_id)
1934               JOIN $table n ON (n.id = a.${table}_id)
1935               JOIN invoice i ON (i.trans_id = a.id)
1936                 WHERE $where
1937                 AND a.invoice = '1'
1938                 AND (
1939                   a.${table}_id NOT IN (
1940                         SELECT ${table}_id FROM ${table}tax t (${table}_id)
1941                                        ) OR
1942                   i.parts_id NOT IN (
1943                         SELECT parts_id FROM partstax p (parts_id)
1944                                     )
1945                     )
1946                 GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
1947                 ORDER by $sortorder|;
1948   }
1949
1950   my $sth = $dbh->prepare($query);
1951   $sth->execute || $form->dberror($query);
1952
1953   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1954     push @{ $form->{TR} }, $ref;
1955   }
1956
1957   $sth->finish;
1958   $dbh->disconnect;
1959
1960   $main::lxdebug->leave_sub();
1961 }
1962
1963 sub paymentaccounts {
1964   $main::lxdebug->enter_sub();
1965
1966   my ($self, $myconfig, $form) = @_;
1967
1968   # connect to database, turn AutoCommit off
1969   my $dbh = $form->dbconnect_noauto($myconfig);
1970
1971   my $ARAP = uc $form->{db};
1972
1973   # get A(R|P)_paid accounts
1974   my $query = qq|SELECT c.accno, c.description
1975                  FROM chart c
1976                  WHERE c.link LIKE '%${ARAP}_paid%'|;
1977   my $sth = $dbh->prepare($query);
1978   $sth->execute || $form->dberror($query);
1979
1980   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1981     push @{ $form->{PR} }, $ref;
1982   }
1983
1984   $sth->finish;
1985   $dbh->disconnect;
1986
1987   $main::lxdebug->leave_sub();
1988 }
1989
1990 sub payments {
1991   $main::lxdebug->enter_sub();
1992
1993   my ($self, $myconfig, $form) = @_;
1994
1995   # connect to database, turn AutoCommit off
1996   my $dbh = $form->dbconnect_noauto($myconfig);
1997
1998   my $ml = 1;
1999   if ($form->{db} eq 'ar') {
2000     $table = 'customer';
2001     $ml    = -1;
2002   }
2003   if ($form->{db} eq 'ap') {
2004     $table = 'vendor';
2005   }
2006
2007   my ($query, $sth);
2008   my $dpt_join;
2009   my $where;
2010
2011   if ($form->{department_id}) {
2012     $dpt_join = qq|
2013                  JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
2014                  |;
2015
2016     $where = qq|
2017                  AND t.department_id = $form->{department_id}
2018                 |;
2019   }
2020
2021   if ($form->{fromdate}) {
2022     $where .= " AND ac.transdate >= '$form->{fromdate}'";
2023   }
2024   if ($form->{todate}) {
2025     $where .= " AND ac.transdate <= '$form->{todate}'";
2026   }
2027   if (!$form->{fx_transaction}) {
2028     $where .= " AND ac.fx_transaction = '0'";
2029   }
2030
2031   my $invnumber;
2032   my $reference;
2033   if ($form->{reference}) {
2034     $reference = $form->like(lc $form->{reference});
2035     $invnumber = " AND lower(a.invnumber) LIKE '$reference'";
2036     $reference = " AND lower(g.reference) LIKE '$reference'";
2037   }
2038   if ($form->{source}) {
2039     my $source = $form->like(lc $form->{source});
2040     $where .= " AND lower(ac.source) LIKE '$source'";
2041   }
2042   if ($form->{memo}) {
2043     my $memo = $form->like(lc $form->{memo});
2044     $where .= " AND lower(ac.memo) LIKE '$memo'";
2045   }
2046
2047   my $sortorder = join ', ',
2048     $form->sort_columns(qw(name invnumber ordnumber transdate source));
2049   $sortorder = $form->{sort} if $form->{sort};
2050
2051   # cycle through each id
2052   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
2053
2054     $query = qq|SELECT c.id, c.accno, c.description
2055                 FROM chart c
2056                 WHERE c.accno = '$accno'|;
2057     $sth = $dbh->prepare($query);
2058     $sth->execute || $form->dberror($query);
2059
2060     my $ref = $sth->fetchrow_hashref(NAME_lc);
2061     push @{ $form->{PR} }, $ref;
2062     $sth->finish;
2063
2064     $query = qq|SELECT c.name, a.invnumber, a.ordnumber,
2065                 ac.transdate, ac.amount * $ml AS paid, ac.source,
2066                 a.invoice, a.id, ac.memo, '$form->{db}' AS module
2067                 FROM acc_trans ac
2068                 JOIN $form->{db} a ON (ac.trans_id = a.id)
2069                 JOIN $table c ON (c.id = a.${table}_id)
2070                 $dpt_join
2071                 WHERE ac.chart_id = $ref->{id}
2072                 $where
2073                 $invnumber
2074
2075         UNION
2076                 SELECT g.description, g.reference, NULL AS ordnumber,
2077                 ac.transdate, ac.amount * $ml AS paid, ac.source,
2078                 '0' as invoice, g.id, ac.memo, 'gl' AS module
2079                 FROM acc_trans ac
2080                 JOIN gl g ON (g.id = ac.trans_id)
2081                 $dpt_join
2082                 WHERE ac.chart_id = $ref->{id}
2083                 $where
2084                 $reference
2085                 AND (ac.amount * $ml) > 0
2086                 ORDER BY $sortorder|;
2087
2088     $sth = $dbh->prepare($query);
2089     $sth->execute || $form->dberror($query);
2090
2091     while (my $pr = $sth->fetchrow_hashref(NAME_lc)) {
2092       push @{ $form->{ $ref->{id} } }, $pr;
2093     }
2094     $sth->finish;
2095
2096   }
2097
2098   $dbh->disconnect;
2099
2100   $main::lxdebug->leave_sub();
2101 }
2102
2103 sub bwa {
2104   $main::lxdebug->enter_sub();
2105
2106   my ($self, $myconfig, $form) = @_;
2107
2108   # connect to database
2109   my $dbh = $form->dbconnect($myconfig);
2110
2111   my $last_period = 0;
2112   my $category    = "pos_bwa";
2113   my @categories  =
2114     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);
2115
2116   $form->{decimalplaces} *= 1;
2117
2118   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2119                   $form, $category);
2120
2121   # if there are any compare dates
2122   if ($form->{fromdate} || $form->{todate}) {
2123     $last_period = 1;
2124     if ($form->{fromdate}) {
2125       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
2126       $year = $1;
2127     } else {
2128       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
2129       $year = $1;
2130     }
2131     $kummfromdate = $form->{comparefromdate};
2132     $kummtodate   = $form->{comparetodate};
2133     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form,
2134                     $category);
2135   }
2136
2137   @periods        = qw(jetzt kumm);
2138   @gesamtleistung = qw(1 2 3);
2139   @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
2140   @ergebnisse     =
2141     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
2142
2143   foreach $key (@periods) {
2144     $form->{ "$key" . "gesamtleistung" } = 0;
2145     $form->{ "$key" . "gesamtkosten" }   = 0;
2146
2147     foreach $category (@categories) {
2148
2149       if (defined($form->{$category}{$key})) {
2150         $form->{"$key$category"} =
2151           $form->format_amount($myconfig,
2152                                $form->round_amount($form->{$category}{$key}, 2
2153                                ),
2154                                $form->{decimalplaces},
2155                                '0');
2156       }
2157     }
2158     foreach $item (@gesamtleistung) {
2159       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
2160     }
2161     foreach $item (@gesamtkosten) {
2162       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
2163     }
2164     $form->{ "$key" . "rohertrag" } =
2165       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
2166     $form->{ "$key" . "betriebrohertrag" } =
2167       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
2168     $form->{ "$key" . "betriebsergebnis" } =
2169       $form->{ "$key" . "betriebrohertrag" } -
2170       $form->{ "$key" . "gesamtkosten" };
2171     $form->{ "$key" . "neutraleraufwand" } =
2172       $form->{30}{$key} + $form->{31}{$key};
2173     $form->{ "$key" . "neutralertrag" } =
2174       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
2175     $form->{ "$key" . "ergebnisvorsteuern" } =
2176       $form->{ "$key" . "betriebsergebnis" } -
2177       $form->{ "$key" . "neutraleraufwand" } +
2178       $form->{ "$key" . "neutralertrag" };
2179     $form->{ "$key" . "ergebnis" } =
2180       $form->{ "$key" . "ergebnisvorsteuern" } + $form->{35}{$key};
2181
2182     if ($form->{ "$key" . "gesamtleistung" } > 0) {
2183       foreach $category (@categories) {
2184         if (defined($form->{$category}{$key})) {
2185           $form->{ "$key" . "gl" . "$category" } =
2186             $form->format_amount(
2187                                $myconfig,
2188                                $form->round_amount(
2189                                  ($form->{$category}{$key} /
2190                                     $form->{ "$key" . "gesamtleistung" } * 100
2191                                  ),
2192                                  $form->{decimalplaces}
2193                                ),
2194                                $form->{decimalplaces},
2195                                '0');
2196         }
2197       }
2198       foreach $item (@ergebnisse) {
2199         $form->{ "$key" . "gl" . "$item" } =
2200           $form->format_amount($myconfig,
2201                                $form->round_amount(
2202                                  ( $form->{ "$key" . "$item" } /
2203                                      $form->{ "$key" . "gesamtleistung" } * 100
2204                                  ),
2205                                  $form->{decimalplaces}
2206                                ),
2207                                $form->{decimalplaces},
2208                                '0');
2209       }
2210     }
2211
2212     if ($form->{ "$key" . "gesamtkosten" } > 0) {
2213       foreach $category (@categories) {
2214         if (defined($form->{$category}{$key})) {
2215           $form->{ "$key" . "gk" . "$category" } =
2216             $form->format_amount($myconfig,
2217                                  $form->round_amount(
2218                                    ($form->{$category}{$key} /
2219                                       $form->{ "$key" . "gesamtkosten" } * 100
2220                                    ),
2221                                    $form->{decimalplaces}
2222                                  ),
2223                                  $form->{decimalplaces},
2224                                  '0');
2225         }
2226       }
2227       foreach $item (@ergebnisse) {
2228         $form->{ "$key" . "gk" . "$item" } =
2229           $form->format_amount($myconfig,
2230                                $form->round_amount(
2231                                    ($form->{ "$key" . "$item" } /
2232                                       $form->{ "$key" . "gesamtkosten" } * 100
2233                                    ),
2234                                    $form->{decimalplaces}
2235                                ),
2236                                $form->{decimalplaces},
2237                                '0');
2238       }
2239     }
2240
2241     if ($form->{10}{$key} > 0) {
2242       foreach $category (@categories) {
2243         if (defined($form->{$category}{$key})) {
2244           $form->{ "$key" . "pk" . "$category" } =
2245             $form->format_amount(
2246                         $myconfig,
2247                         $form->round_amount(
2248                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
2249                           $form->{decimalplaces}
2250                         ),
2251                         $form->{decimalplaces},
2252                         '0');
2253         }
2254       }
2255       foreach $item (@ergebnisse) {
2256         $form->{ "$key" . "pk" . "$item" } =
2257           $form->format_amount($myconfig,
2258                                $form->round_amount(
2259                                                 ($form->{ "$key" . "$item" } /
2260                                                    $form->{10}{$key} * 100
2261                                                 ),
2262                                                 $form->{decimalplaces}
2263                                ),
2264                                $form->{decimalplaces},
2265                                '0');
2266       }
2267     }
2268
2269     if ($form->{4}{$key} > 0) {
2270       foreach $category (@categories) {
2271         if (defined($form->{$category}{$key})) {
2272           $form->{ "$key" . "auf" . "$category" } =
2273             $form->format_amount(
2274                          $myconfig,
2275                          $form->round_amount(
2276                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
2277                            $form->{decimalplaces}
2278                          ),
2279                          $form->{decimalplaces},
2280                          '0');
2281         }
2282       }
2283       foreach $item (@ergebnisse) {
2284         $form->{ "$key" . "auf" . "$item" } =
2285           $form->format_amount($myconfig,
2286                                $form->round_amount(
2287                                                 ($form->{ "$key" . "$item" } /
2288                                                    $form->{4}{$key} * 100
2289                                                 ),
2290                                                 $form->{decimalplaces}
2291                                ),
2292                                $form->{decimalplaces},
2293                                '0');
2294       }
2295     }
2296
2297     foreach $item (@ergebnisse) {
2298       $form->{ "$key" . "$item" } =
2299         $form->format_amount($myconfig,
2300                              $form->round_amount($form->{ "$key" . "$item" },
2301                                                  $form->{decimalplaces}
2302                              ),
2303                              $form->{decimalplaces},
2304                              '0');
2305     }
2306
2307   }
2308   $dbh->disconnect;
2309
2310   $main::lxdebug->leave_sub();
2311 }
2312
2313 sub ustva {
2314   $main::lxdebug->enter_sub();
2315
2316   my ($self, $myconfig, $form) = @_;
2317
2318   # connect to database
2319   my $dbh = $form->dbconnect($myconfig);
2320
2321   my $last_period     = 0;
2322   my $category        = "pos_ustva";
2323   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
2324     96 66 43 45 53 62 65 67);
2325   my @categories_euro = qw(48 51 86 91 97 93 94);
2326   $form->{decimalplaces} *= 1;
2327
2328   foreach $item (@categories_cent) {
2329     $form->{"$item"} = 0;
2330   }
2331   foreach $item (@categories_euro) {
2332     $form->{"$item"} = 0;
2333   }
2334
2335   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2336                   $form, $category);
2337
2338   #   foreach $item (@categories_cent) {
2339   #     if ($form->{$item}{"jetzt"} > 0) {
2340   #             $form->{$item} = $form->{$item}{"jetzt"};
2341   #             delete $form->{$item}{"jetzt"};
2342   #     }
2343   #   }
2344   #   foreach $item (@categories_euro) {
2345   #     if ($form->{$item}{"jetzt"} > 0) {
2346   #             $form->{$item} = $form->{$item}{"jetzt"};
2347   #             delete $form->{$item}{"jetzt"};
2348   #     }  foreach $item (@categories_cent) {
2349   #     if ($form->{$item}{"jetzt"} > 0) {
2350   #             $form->{$item} = $form->{$item}{"jetzt"};
2351   #             delete $form->{$item}{"jetzt"};
2352   #     }
2353   #   }
2354   #   foreach $item (@categories_euro) {
2355   #     if ($form->{$item}{"jetzt"} > 0) {
2356   #             $form->{$item} = $form->{$item}{"jetzt"};
2357   #             delete $form->{$item}{"jetzt"};
2358   #     }
2359   #   }
2360   #
2361   #    }
2362
2363   #
2364   # Berechnung der USTVA Formularfelder
2365   #
2366   $form->{"51r"} = $form->{"511"};
2367   $form->{"86r"} = $form->{"861"};
2368   $form->{"97r"} = $form->{"971"};
2369   $form->{"93r"} = $form->{"931"};
2370
2371   #$form->{"96"}  = $form->{"94"} * 0.16;
2372   $form->{"43"} =
2373     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
2374     $form->{"96"};
2375   $form->{"45"} = $form->{"43"};
2376   $form->{"53"} = $form->{"43"};
2377   $form->{"62"} = $form->{"43"} - $form->{"66"};
2378   $form->{"65"} = $form->{"43"} - $form->{"66"};
2379   $form->{"67"} = $form->{"43"} - $form->{"66"};
2380
2381   foreach $item (@categories_cent) {
2382     $form->{$item} =
2383       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
2384                            2, '0');
2385   }
2386
2387   foreach $item (@categories_euro) {
2388     $form->{$item} =
2389       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
2390                            0, '0');
2391   }
2392
2393   $dbh->disconnect;
2394
2395   $main::lxdebug->leave_sub();
2396 }
2397
2398 sub income_statement {
2399   $main::lxdebug->enter_sub();
2400
2401   my ($self, $myconfig, $form) = @_;
2402
2403   # connect to database
2404   my $dbh = $form->dbconnect($myconfig);
2405
2406   my $last_period          = 0;
2407   my $category             = "pos_eur";
2408   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
2409   my @categories_ausgaben  =
2410     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);
2411
2412   my @ergebnisse = qw(sumeura sumeurb guvsumme);
2413
2414   $form->{decimalplaces} *= 1;
2415
2416   foreach $item (@categories_einnahmen) {
2417     $form->{$item} = 0;
2418   }
2419   foreach $item (@categories_ausgaben) {
2420     $form->{$item} = 0;
2421   }
2422
2423   foreach $item (@ergebnisse) {
2424     $form->{$item} = 0;
2425   }
2426
2427   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2428                   $form, $category);
2429
2430   foreach $item (@categories_einnahmen) {
2431     $form->{"eur${item}"} =
2432       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2433     $form->{"sumeura"} += $form->{$item};
2434   }
2435   foreach $item (@categories_ausgaben) {
2436     $form->{"eur${item}"} =
2437       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2438     $form->{"sumeurb"} += $form->{$item};
2439   }
2440
2441   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
2442
2443   foreach $item (@ergebnisse) {
2444     $form->{$item} =
2445       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2446   }
2447   $main::lxdebug->leave_sub();
2448 }
2449 1;