Kosmetik: Perltidy-Lauf nach den Einstellungen in doc/programmierrichtlinien.txt...
[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 $subwhere = "";
922   my $item;
923
924   if ($fromdate) {
925     if ($form->{method} eq 'cash') {
926       $subwhere .= " AND transdate >= '$fromdate'";
927       $glwhere = " AND ac.transdate >= '$fromdate'";
928     } else {
929       $where .= " AND ac.transdate >= '$fromdate'";
930     }
931   }
932
933   if ($todate) {
934     $where    .= " AND ac.transdate <= '$todate'";
935     $subwhere .= " AND transdate <= '$todate'";
936   }
937
938   if ($department_id) {
939     $dpt_join = qq|
940                JOIN department t ON (a.department_id = t.id)
941                   |;
942     $dpt_where = qq|
943                AND t.id = $department_id
944                    |;
945   }
946
947   if ($form->{project_id}) {
948     $project = qq|
949                  AND ac.project_id = $form->{project_id}
950                  |;
951   }
952
953   if ($form->{method} eq 'cash') {
954
955     $query = qq|
956
957                  SELECT sum(ac.amount) AS amount,
958                  c.$category
959                  FROM acc_trans ac
960                  JOIN chart c ON (c.id = ac.chart_id)
961                  JOIN ar a ON (a.id = ac.trans_id)
962                  $dpt_join
963                  WHERE $where
964                  $dpt_where
965                  AND ac.trans_id IN
966                    (
967                      SELECT trans_id
968                      FROM acc_trans
969                      JOIN chart ON (chart_id = id)
970                      WHERE link LIKE '%AR_paid%'
971                      $subwhere
972                    )
973
974                  $project
975                  GROUP BY c.$category
976
977         UNION
978
979                  SELECT sum(ac.amount) AS amount,
980                  c.$category
981                  FROM acc_trans ac
982                  JOIN chart c ON (c.id = ac.chart_id)
983                  JOIN ap a ON (a.id = ac.trans_id)
984                  $dpt_join
985                  WHERE $where
986                  $dpt_where
987                  AND ac.trans_id IN
988                    (
989                      SELECT trans_id
990                      FROM acc_trans
991                      JOIN chart ON (chart_id = id)
992                      WHERE link LIKE '%AP_paid%'
993                      $subwhere
994                    )
995
996                  $project
997                  GROUP BY c.$category
998
999         UNION
1000
1001                  SELECT sum(ac.amount) AS amount,
1002                  c.$category
1003                  FROM acc_trans ac
1004                  JOIN chart c ON (c.id = ac.chart_id)
1005                  JOIN gl a ON (a.id = ac.trans_id)
1006                  $dpt_join
1007                  WHERE $where
1008                  $glwhere
1009                  $dpt_from
1010                  AND NOT (c.link = 'AR' OR c.link = 'AP')
1011                  $project
1012                  GROUP BY c.$category
1013                  |;
1014
1015     if ($form->{project_id}) {
1016
1017       $query .= qq|
1018
1019          UNION
1020
1021                  SELECT SUM(ac.sellprice * ac.qty) AS amount,
1022                  c.$category
1023                  FROM invoice ac
1024                  JOIN ar a ON (a.id = ac.trans_id)
1025                  JOIN parts p ON (ac.parts_id = p.id)
1026                  JOIN chart c on (p.income_accno_id = c.id)
1027                  $dpt_join
1028         -- use transdate from subwhere
1029                  WHERE 1 = 1 $subwhere
1030                  AND c.category = 'I'
1031                  $dpt_where
1032                  AND ac.trans_id IN
1033                    (
1034                      SELECT trans_id
1035                      FROM acc_trans
1036                      JOIN chart ON (chart_id = id)
1037                      WHERE link LIKE '%AR_paid%'
1038                      $subwhere
1039                    )
1040
1041                  $project
1042                  GROUP BY c.$category
1043
1044          UNION
1045
1046                  SELECT SUM(ac.sellprice) AS amount,
1047                  c.$category
1048                  FROM invoice ac
1049                  JOIN ap a ON (a.id = ac.trans_id)
1050                  JOIN parts p ON (ac.parts_id = p.id)
1051                  JOIN chart c on (p.expense_accno_id = c.id)
1052                  $dpt_join
1053                  WHERE 1 = 1 $subwhere
1054                  AND c.category = 'E'
1055                  $dpt_where
1056                  AND ac.trans_id IN
1057                    (
1058                      SELECT trans_id
1059                      FROM acc_trans
1060                      JOIN chart ON (chart_id = id)
1061                      WHERE link LIKE '%AP_paid%'
1062                      $subwhere
1063                    )
1064
1065                  $project
1066                  GROUP BY c.$category
1067                  |;
1068     }
1069
1070   } else {
1071
1072     if ($department_id) {
1073       $dpt_join = qq|
1074               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
1075               |;
1076       $dpt_where = qq|
1077                AND t.department_id = $department_id
1078               |;
1079     }
1080
1081     $query = qq|
1082
1083                  SELECT sum(ac.amount) AS amount,
1084                  c.$category
1085                  FROM acc_trans ac
1086                  JOIN chart c ON (c.id = ac.chart_id)
1087                  $dpt_join
1088                  WHERE $where
1089                  $dpt_where
1090                  $project
1091                  GROUP BY c.$category
1092                  |;
1093
1094     if ($form->{project_id}) {
1095
1096       $query .= qq|
1097
1098         UNION
1099
1100                  SELECT SUM(ac.sellprice * ac.qty) AS amount,
1101                  c.$category
1102                  FROM invoice ac
1103                  JOIN ar a ON (a.id = ac.trans_id)
1104                  JOIN parts p ON (ac.parts_id = p.id)
1105                  JOIN chart c on (p.income_accno_id = c.id)
1106                  $dpt_join
1107         -- use transdate from subwhere
1108                  WHERE 1 = 1 $subwhere
1109                  AND c.category = 'I'
1110                  $dpt_where
1111                  $project
1112                  GROUP BY c.$category
1113
1114         UNION
1115
1116                  SELECT SUM(ac.sellprice * ac.qty) * -1 AS amount,
1117                  c.$category
1118                  FROM invoice ac
1119                  JOIN ap a ON (a.id = ac.trans_id)
1120                  JOIN parts p ON (ac.parts_id = p.id)
1121                  JOIN chart c on (p.expense_accno_id = c.id)
1122                  $dpt_join
1123                  WHERE 1 = 1 $subwhere
1124                  AND c.category = 'E'
1125                  $dpt_where
1126                  $project
1127                  GROUP BY c.$category
1128                  |;
1129
1130     }
1131   }
1132
1133   my @accno;
1134   my $accno;
1135   my $ref;
1136
1137   #print $query;
1138   my $sth = $dbh->prepare($query);
1139   $sth->execute || $form->dberror($query);
1140
1141   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1142     if ($ref->{amount} < 0) {
1143       $ref->{amount} *= -1;
1144     }
1145     if ($category eq "pos_bwa") {
1146       if ($last_period) {
1147         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
1148       } else {
1149         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
1150       }
1151     } else {
1152       $form->{ $ref->{$category} } += $ref->{amount};
1153     }
1154   }
1155   $sth->finish;
1156
1157   $main::lxdebug->leave_sub();
1158 }
1159
1160 sub trial_balance {
1161   $main::lxdebug->enter_sub();
1162
1163   my ($self, $myconfig, $form) = @_;
1164
1165   my $dbh = $form->dbconnect($myconfig);
1166
1167   my ($query, $sth, $ref);
1168   my %balance = ();
1169   my %trb     = ();
1170   my ($null, $department_id) = split /--/, $form->{department};
1171   my @headingaccounts = ();
1172   my $dpt_where;
1173   my $dpt_join;
1174   my $project;
1175
1176   my $where    = "1 = 1";
1177   my $invwhere = $where;
1178
1179   if ($department_id) {
1180     $dpt_join = qq|
1181                 JOIN dpt_trans t ON (ac.trans_id = t.trans_id)
1182                   |;
1183     $dpt_where = qq|
1184                 AND t.department_id = $department_id
1185                 |;
1186   }
1187
1188   # project_id only applies to getting transactions
1189   # it has nothing to do with a trial balance
1190   # but we use the same function to collect information
1191
1192   if ($form->{project_id}) {
1193     $project = qq|
1194                 AND ac.project_id = $form->{project_id}
1195                 |;
1196   }
1197
1198   # get beginning balances
1199   if ($form->{fromdate}) {
1200
1201     if ($form->{accounttype} eq 'gifi') {
1202
1203       $query = qq|SELECT g.accno, c.category, SUM(ac.amount) AS amount,
1204                   g.description
1205                   FROM acc_trans ac
1206                   JOIN chart c ON (ac.chart_id = c.id)
1207                   JOIN gifi g ON (c.gifi_accno = g.accno)
1208                   $dpt_join
1209                   WHERE ac.transdate < '$form->{fromdate}'
1210                   $dpt_where
1211                   $project
1212                   GROUP BY g.accno, c.category, g.description
1213                   |;
1214
1215     } else {
1216
1217       $query = qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount,
1218                   c.description
1219                   FROM acc_trans ac
1220                   JOIN chart c ON (ac.chart_id = c.id)
1221                   $dpt_join
1222                   WHERE ac.transdate < '$form->{fromdate}'
1223                   $dpt_where
1224                   $project
1225                   GROUP BY c.accno, c.category, c.description
1226                   |;
1227
1228     }
1229
1230     $sth = $dbh->prepare($query);
1231     $sth->execute || $form->dberror($query);
1232
1233     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1234       $balance{ $ref->{accno} } = $ref->{amount};
1235
1236       if ($ref->{amount} != 0 && $form->{all_accounts}) {
1237         $trb{ $ref->{accno} }{description} = $ref->{description};
1238         $trb{ $ref->{accno} }{charttype}   = 'A';
1239         $trb{ $ref->{accno} }{category}    = $ref->{category};
1240       }
1241
1242     }
1243     $sth->finish;
1244
1245   }
1246
1247   # get headings
1248   $query = qq|SELECT c.accno, c.description, c.category
1249               FROM chart c
1250               WHERE c.charttype = 'H'
1251               ORDER by c.accno|;
1252
1253   if ($form->{accounttype} eq 'gifi') {
1254     $query = qq|SELECT g.accno, g.description, c.category
1255                 FROM gifi g
1256                 JOIN chart c ON (c.gifi_accno = g.accno)
1257                 WHERE c.charttype = 'H'
1258                 ORDER BY g.accno|;
1259   }
1260
1261   $sth = $dbh->prepare($query);
1262   $sth->execute || $form->dberror($query);
1263
1264   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1265     $trb{ $ref->{accno} }{description} = $ref->{description};
1266     $trb{ $ref->{accno} }{charttype}   = 'H';
1267     $trb{ $ref->{accno} }{category}    = $ref->{category};
1268
1269     push @headingaccounts, $ref->{accno};
1270   }
1271
1272   $sth->finish;
1273
1274   $where = " 1 = 1 ";
1275
1276   if ($form->{fromdate} || $form->{todate}) {
1277     if ($form->{fromdate}) {
1278       $tofrom   .= " AND ac.transdate >= '$form->{fromdate}'";
1279       $subwhere .= " AND transdate >= '$form->{fromdate}'";
1280       $invwhere .= " AND a.transdate >= '$form->{fromdate}'";
1281       $glwhere = " AND ac.transdate >= '$form->{fromdate}'";
1282     }
1283     if ($form->{todate}) {
1284       $tofrom   .= " AND ac.transdate <= '$form->{todate}'";
1285       $invwhere .= " AND a.transdate <= '$form->{todate}'";
1286       $subwhere .= " AND transdate <= '$form->{todate}'";
1287       $glwhere  .= " AND ac.transdate <= '$form->{todate}'";
1288     }
1289   }
1290   if ($form->{eur}) {
1291     $where .= qq| AND ((ac.trans_id in (SELECT id from ar)
1292                   AND ac.trans_id IN
1293                    (
1294                      SELECT trans_id
1295                      FROM acc_trans
1296                      JOIN chart ON (chart_id = id)
1297                      WHERE link LIKE '%AR_paid%'
1298                      $subwhere
1299                    )) OR (ac.trans_id in (SELECT id from ap)
1300                    AND ac.trans_id IN
1301                    (
1302                      SELECT trans_id
1303                      FROM acc_trans
1304                      JOIN chart ON (chart_id = id)
1305                      WHERE link LIKE '%AP_paid%'
1306                      $subwhere
1307                    )) OR (ac.trans_id in (SELECT id from gl)
1308                    $glwhere))|;
1309   } else {
1310     $where .= $tofrom;
1311   }
1312
1313   if ($form->{accounttype} eq 'gifi') {
1314
1315     $query = qq|SELECT g.accno, g.description, c.category,
1316                 SUM(ac.amount) AS amount
1317                 FROM acc_trans ac
1318                 JOIN chart c ON (c.id = ac.chart_id)
1319                 JOIN gifi g ON (c.gifi_accno = g.accno)
1320                 $dpt_join
1321                 WHERE $where
1322                 $dpt_where
1323                 $project
1324                 GROUP BY g.accno, g.description, c.category
1325                 |;
1326
1327     if ($form->{project_id}) {
1328
1329       $query .= qq|
1330
1331         -- add project transactions from invoice
1332
1333         UNION ALL
1334
1335                 SELECT g.accno, g.description, c.category,
1336                 SUM(ac.sellprice * ac.qty) AS amount
1337                 FROM invoice ac
1338                 JOIN ar a ON (ac.trans_id = a.id)
1339                 JOIN parts p ON (ac.parts_id = p.id)
1340                 JOIN chart c ON (p.income_accno_id = c.id)
1341                 JOIN gifi g ON (c.gifi_accno = g.accno)
1342                 $dpt_join
1343                 WHERE $invwhere
1344                 $dpt_where
1345                 $project
1346                 GROUP BY g.accno, g.description, c.category
1347
1348         UNION ALL
1349
1350                 SELECT g.accno, g.description, c.category,
1351                 SUM(ac.sellprice * ac.qty) * -1 AS amount
1352                 FROM invoice ac
1353                 JOIN ap a ON (ac.trans_id = a.id)
1354                 JOIN parts p ON (ac.parts_id = p.id)
1355                 JOIN chart c ON (p.expense_accno_id = c.id)
1356                 JOIN gifi g ON (c.gifi_accno = g.accno)
1357                 $dpt_join
1358                 WHERE $invwhere
1359                 $dpt_where
1360                 $project
1361                 GROUP BY g.accno, g.description, c.category
1362                 |;
1363     }
1364
1365     $query .= qq|
1366                 ORDER BY accno|;
1367
1368   } else {
1369
1370     $query = qq|SELECT c.accno, c.description, c.category,
1371                 SUM(ac.amount) AS amount
1372                 FROM acc_trans ac
1373                 JOIN chart c ON (c.id = ac.chart_id)
1374                 $dpt_join
1375                 WHERE $where
1376                 $dpt_where
1377                 $project
1378                 GROUP BY c.accno, c.description, c.category
1379                 |;
1380
1381     if ($form->{project_id}) {
1382
1383       $query .= qq|
1384
1385         -- add project transactions from invoice
1386
1387         UNION ALL
1388
1389                 SELECT c.accno, c.description, c.category,
1390                 SUM(ac.sellprice * ac.qty) AS amount
1391                 FROM invoice ac
1392                 JOIN ar a ON (ac.trans_id = a.id)
1393                 JOIN parts p ON (ac.parts_id = p.id)
1394                 JOIN chart c ON (p.income_accno_id = c.id)
1395                 $dpt_join
1396                 WHERE $invwhere
1397                 $dpt_where
1398                 $project
1399                 GROUP BY c.accno, c.description, c.category
1400
1401         UNION ALL
1402
1403                 SELECT c.accno, c.description, c.category,
1404                 SUM(ac.sellprice * ac.qty) * -1 AS amount
1405                 FROM invoice ac
1406                 JOIN ap a ON (ac.trans_id = a.id)
1407                 JOIN parts p ON (ac.parts_id = p.id)
1408                 JOIN chart c ON (p.expense_accno_id = c.id)
1409                 $dpt_join
1410                 WHERE $invwhere
1411                 $dpt_where
1412                 $project
1413                 GROUP BY c.accno, c.description, c.category
1414                 |;
1415     }
1416
1417     $query .= qq|
1418                 ORDER BY accno|;
1419
1420   }
1421
1422   $sth = $dbh->prepare($query);
1423   $sth->execute || $form->dberror($query);
1424
1425   # prepare query for each account
1426   $query = qq|SELECT (SELECT SUM(ac.amount) * -1
1427               FROM acc_trans ac
1428               JOIN chart c ON (c.id = ac.chart_id)
1429               $dpt_join
1430               WHERE $where
1431               $dpt_where
1432               $project
1433               AND ac.amount < 0
1434               AND c.accno = ?) AS debit,
1435
1436              (SELECT SUM(ac.amount)
1437               FROM acc_trans ac
1438               JOIN chart c ON (c.id = ac.chart_id)
1439               $dpt_join
1440               WHERE $where
1441               $dpt_where
1442               $project
1443               AND ac.amount > 0
1444               AND c.accno = ?) AS credit
1445               |;
1446
1447   if ($form->{accounttype} eq 'gifi') {
1448
1449     $query = qq|SELECT (SELECT SUM(ac.amount) * -1
1450                 FROM acc_trans ac
1451                 JOIN chart c ON (c.id = ac.chart_id)
1452                 $dpt_join
1453                 WHERE $where
1454                 $dpt_where
1455                 $project
1456                 AND ac.amount < 0
1457                 AND c.gifi_accno = ?) AS debit,
1458
1459                (SELECT SUM(ac.amount)
1460                 FROM acc_trans ac
1461                 JOIN chart c ON (c.id = ac.chart_id)
1462                 $dpt_join
1463                 WHERE $where
1464                 $dpt_where
1465                 $project
1466                 AND ac.amount > 0
1467                 AND c.gifi_accno = ?) AS credit|;
1468
1469   }
1470
1471   $drcr = $dbh->prepare($query);
1472
1473   if ($form->{project_id}) {
1474
1475     # prepare query for each account
1476     $query = qq|SELECT (SELECT SUM(ac.sellprice * ac.qty) * -1
1477               FROM invoice ac
1478               JOIN parts p ON (ac.parts_id = p.id)
1479               JOIN ap a ON (ac.trans_id = a.id)
1480               JOIN chart c ON (p.expense_accno_id = c.id)
1481               $dpt_join
1482               WHERE $invwhere
1483               $dpt_where
1484               $project
1485               AND c.accno = ?) AS debit,
1486
1487              (SELECT SUM(ac.sellprice * ac.qty)
1488               FROM invoice ac
1489               JOIN parts p ON (ac.parts_id = p.id)
1490               JOIN ar a ON (ac.trans_id = a.id)
1491               JOIN chart c ON (p.income_accno_id = c.id)
1492               $dpt_join
1493               WHERE $invwhere
1494               $dpt_where
1495               $project
1496               AND c.accno = ?) AS credit
1497               |;
1498
1499     $project_drcr = $dbh->prepare($query);
1500
1501   }
1502
1503   # calculate the debit and credit in the period
1504   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1505     $trb{ $ref->{accno} }{description} = $ref->{description};
1506     $trb{ $ref->{accno} }{charttype}   = 'A';
1507     $trb{ $ref->{accno} }{category}    = $ref->{category};
1508     $trb{ $ref->{accno} }{amount} += $ref->{amount};
1509   }
1510   $sth->finish;
1511
1512   my ($debit, $credit);
1513
1514   foreach my $accno (sort keys %trb) {
1515     $ref = ();
1516
1517     $ref->{accno} = $accno;
1518     map { $ref->{$_} = $trb{$accno}{$_} }
1519       qw(description category charttype amount);
1520
1521     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
1522
1523     if ($trb{$accno}{charttype} eq 'A') {
1524
1525       # get DR/CR
1526       $drcr->execute($ref->{accno}, $ref->{accno}) || $form->dberror($query);
1527
1528       ($debit, $credit) = (0, 0);
1529       while (($debit, $credit) = $drcr->fetchrow_array) {
1530         $ref->{debit}  += $debit;
1531         $ref->{credit} += $credit;
1532       }
1533       $drcr->finish;
1534
1535       if ($form->{project_id}) {
1536
1537         # get DR/CR
1538         $project_drcr->execute($ref->{accno}, $ref->{accno})
1539           || $form->dberror($query);
1540
1541         ($debit, $credit) = (0, 0);
1542         while (($debit, $credit) = $project_drcr->fetchrow_array) {
1543           $ref->{debit}  += $debit;
1544           $ref->{credit} += $credit;
1545         }
1546         $project_drcr->finish;
1547       }
1548
1549       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
1550       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
1551
1552     }
1553
1554     # add subtotal
1555     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
1556     $accno = pop @accno;
1557     if ($accno) {
1558       $trb{$accno}{debit}  += $ref->{debit};
1559       $trb{$accno}{credit} += $ref->{credit};
1560     }
1561
1562     push @{ $form->{TB} }, $ref;
1563
1564   }
1565
1566   $dbh->disconnect;
1567
1568   # debits and credits for headings
1569   foreach $accno (@headingaccounts) {
1570     foreach $ref (@{ $form->{TB} }) {
1571       if ($accno eq $ref->{accno}) {
1572         $ref->{debit}  = $trb{$accno}{debit};
1573         $ref->{credit} = $trb{$accno}{credit};
1574       }
1575     }
1576   }
1577
1578   $main::lxdebug->leave_sub();
1579 }
1580
1581 sub aging {
1582   $main::lxdebug->enter_sub();
1583
1584   my ($self, $myconfig, $form) = @_;
1585
1586   # connect to database
1587   my $dbh     = $form->dbconnect($myconfig);
1588   my $invoice = ($form->{arap} eq 'ar') ? 'is' : 'ir';
1589
1590   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
1591
1592   my $where = "1 = 1";
1593   my ($name, $null);
1594
1595   if ($form->{"$form->{ct}_id"}) {
1596     $where .= qq| AND ct.id = $form->{"$form->{ct}_id"}|;
1597   } else {
1598     if ($form->{ $form->{ct} }) {
1599       $name = $form->like(lc $form->{ $form->{ct} });
1600       $where .= qq| AND lower(ct.name) LIKE '$name'| if $form->{ $form->{ct} };
1601     }
1602   }
1603
1604   my $dpt_join;
1605   if ($form->{department}) {
1606     ($null, $department_id) = split /--/, $form->{department};
1607     $dpt_join = qq|
1608                JOIN department d ON (a.department_id = d.id)
1609                   |;
1610
1611     $where .= qq| AND a.department_id = $department_id|;
1612   }
1613
1614   # select outstanding vendors or customers, depends on $ct
1615   my $query = qq|SELECT DISTINCT ct.id, ct.name
1616                  FROM $form->{ct} ct, $form->{arap} a
1617                  $dpt_join
1618                  WHERE $where
1619                  AND a.$form->{ct}_id = ct.id
1620                  AND a.paid != a.amount
1621                  AND (a.transdate <= '$form->{todate}')
1622                  ORDER BY ct.name|;
1623
1624   my $sth = $dbh->prepare($query);
1625   $sth->execute || $form->dberror;
1626
1627   my $buysell = ($form->{arap} eq 'ar') ? 'buy' : 'sell';
1628
1629   # for each company that has some stuff outstanding
1630   while (my ($id) = $sth->fetchrow_array) {
1631
1632     $query = qq|
1633
1634 -- between 0-30 days
1635
1636         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1637         street, zipcode, city, country, contact, email,
1638         phone as customerphone, fax as customerfax, $form->{ct}number,
1639         "invnumber", "transdate",
1640         (amount - paid) as "c0", 0.00 as "c30", 0.00 as "c60", 0.00 as "c90",
1641         "duedate", invoice, $form->{arap}.id,
1642           (SELECT $buysell FROM exchangerate
1643            WHERE $form->{arap}.curr = exchangerate.curr
1644            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1645   FROM $form->{arap}, $form->{ct}
1646         WHERE paid != amount
1647         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1648         AND $form->{ct}.id = $id
1649         AND (
1650                 transdate <= (date '$form->{todate}' - interval '0 days')
1651                 AND transdate >= (date '$form->{todate}' - interval '30 days')
1652             )
1653
1654         UNION
1655
1656 -- between 31-60 days
1657
1658         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1659         street, zipcode, city, country, contact, email,
1660         phone as customerphone, fax as customerfax, $form->{ct}number,
1661         "invnumber", "transdate",
1662         0.00 as "c0", (amount - paid) as "c30", 0.00 as "c60", 0.00 as "c90",
1663         "duedate", invoice, $form->{arap}.id,
1664           (SELECT $buysell FROM exchangerate
1665            WHERE $form->{arap}.curr = exchangerate.curr
1666            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1667   FROM $form->{arap}, $form->{ct}
1668         WHERE paid != amount
1669         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1670         AND $form->{ct}.id = $id
1671         AND (
1672                 transdate < (date '$form->{todate}' - interval '30 days')
1673                 AND transdate >= (date '$form->{todate}' - interval '60 days')
1674                 )
1675
1676         UNION
1677
1678 -- between 61-90 days
1679
1680         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1681         street, zipcode, city, country, contact, email,
1682         phone as customerphone, fax as customerfax, $form->{ct}number,
1683         "invnumber", "transdate",
1684         0.00 as "c0", 0.00 as "c30", (amount - paid) as "c60", 0.00 as "c90",
1685         "duedate", invoice, $form->{arap}.id,
1686           (SELECT $buysell FROM exchangerate
1687            WHERE $form->{arap}.curr = exchangerate.curr
1688            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1689         FROM $form->{arap}, $form->{ct}
1690         WHERE paid != amount
1691         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1692         AND $form->{ct}.id = $id
1693         AND (
1694                 transdate < (date '$form->{todate}' - interval '60 days')
1695                 AND transdate >= (date '$form->{todate}' - interval '90 days')
1696                 )
1697
1698         UNION
1699
1700 -- over 90 days
1701
1702         SELECT $form->{ct}.id AS ctid, $form->{ct}.name,
1703         street, zipcode, city, country, contact, email,
1704         phone as customerphone, fax as customerfax, $form->{ct}number,
1705         "invnumber", "transdate",
1706         0.00 as "c0", 0.00 as "c30", 0.00 as "c60", (amount - paid) as "c90",
1707         "duedate", invoice, $form->{arap}.id,
1708           (SELECT $buysell FROM exchangerate
1709            WHERE $form->{arap}.curr = exchangerate.curr
1710            AND exchangerate.transdate = $form->{arap}.transdate) AS exchangerate
1711         FROM $form->{arap}, $form->{ct}
1712         WHERE paid != amount
1713         AND $form->{arap}.$form->{ct}_id = $form->{ct}.id
1714         AND $form->{ct}.id = $id
1715         AND transdate < (date '$form->{todate}' - interval '90 days')
1716
1717         ORDER BY
1718
1719   ctid, transdate, invnumber
1720
1721                 |;
1722
1723     my $sth = $dbh->prepare($query);
1724     $sth->execute || $form->dberror;
1725
1726     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1727       $ref->{module} = ($ref->{invoice}) ? $invoice : $form->{arap};
1728       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
1729       push @{ $form->{AG} }, $ref;
1730     }
1731
1732     $sth->finish;
1733
1734   }
1735
1736   $sth->finish;
1737
1738   # disconnect
1739   $dbh->disconnect;
1740
1741   $main::lxdebug->leave_sub();
1742 }
1743
1744 sub get_customer {
1745   $main::lxdebug->enter_sub();
1746
1747   my ($self, $myconfig, $form) = @_;
1748
1749   # connect to database
1750   my $dbh = $form->dbconnect($myconfig);
1751
1752   my $query = qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
1753                  FROM $form->{ct} ct
1754                  WHERE ct.id = $form->{"$form->{ct}_id"}|;
1755   my $sth = $dbh->prepare($query);
1756   $sth->execute || $form->dberror;
1757
1758   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
1759     $sth->fetchrow_array;
1760   $sth->finish;
1761   $dbh->disconnect;
1762
1763   $main::lxdebug->leave_sub();
1764 }
1765
1766 sub get_taxaccounts {
1767   $main::lxdebug->enter_sub();
1768
1769   my ($self, $myconfig, $form) = @_;
1770
1771   # connect to database
1772   my $dbh = $form->dbconnect($myconfig);
1773
1774   # get tax accounts
1775   my $query = qq|SELECT c.accno, c.description, t.rate
1776                  FROM chart c, tax t
1777                  WHERE c.link LIKE '%CT_tax%'
1778                  AND c.id = t.chart_id
1779                  ORDER BY c.accno|;
1780   my $sth = $dbh->prepare($query);
1781   $sth->execute || $form->dberror;
1782
1783   my $ref = ();
1784   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1785     push @{ $form->{taxaccounts} }, $ref;
1786   }
1787   $sth->finish;
1788
1789   # get gifi tax accounts
1790   $query = qq|SELECT DISTINCT ON (g.accno) g.accno, g.description,
1791                  sum(t.rate) AS rate
1792                  FROM gifi g, chart c, tax t
1793                  WHERE g.accno = c.gifi_accno
1794                  AND c.id = t.chart_id
1795                  AND c.link LIKE '%CT_tax%'
1796                  GROUP BY g.accno, g.description
1797                  ORDER BY accno|;
1798   $sth = $dbh->prepare($query);
1799   $sth->execute || $form->dberror;
1800
1801   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1802     push @{ $form->{gifi_taxaccounts} }, $ref;
1803   }
1804   $sth->finish;
1805
1806   $dbh->disconnect;
1807
1808   $main::lxdebug->leave_sub();
1809 }
1810
1811 sub tax_report {
1812   $main::lxdebug->enter_sub();
1813
1814   my ($self, $myconfig, $form) = @_;
1815
1816   # connect to database
1817   my $dbh = $form->dbconnect($myconfig);
1818
1819   my ($null, $department_id) = split /--/, $form->{department};
1820
1821   # build WHERE
1822   my $where = "1 = 1";
1823
1824   if ($department_id) {
1825     $where .= qq|
1826                  AND a.department_id = $department_id
1827                 |;
1828   }
1829
1830   my ($accno, $rate);
1831
1832   if ($form->{accno}) {
1833     if ($form->{accno} =~ /^gifi_/) {
1834       ($null, $accno) = split /_/, $form->{accno};
1835       $rate  = $form->{"$form->{accno}_rate"};
1836       $accno = qq| AND ch.gifi_accno = '$accno'|;
1837     } else {
1838       $accno = $form->{accno};
1839       $rate  = $form->{"$form->{accno}_rate"};
1840       $accno = qq| AND ch.accno = '$accno'|;
1841     }
1842   }
1843   $rate *= 1;
1844
1845   my ($table, $ARAP);
1846
1847   if ($form->{db} eq 'ar') {
1848     $table = "customer";
1849     $ARAP  = "AR";
1850   }
1851   if ($form->{db} eq 'ap') {
1852     $table = "vendor";
1853     $ARAP  = "AP";
1854   }
1855
1856   my $transdate = "a.transdate";
1857
1858   if ($form->{method} eq 'cash') {
1859     $transdate = "a.datepaid";
1860
1861     my $todate =
1862       ($form->{todate}) ? $form->{todate} : $form->current_date($myconfig);
1863
1864     $where .= qq|
1865                  AND ac.trans_id IN
1866                    (
1867                      SELECT trans_id
1868                      FROM acc_trans
1869                      JOIN chart ON (chart_id = id)
1870                      WHERE link LIKE '%${ARAP}_paid%'
1871                      AND transdate <= '$todate'
1872                    )
1873                   |;
1874   }
1875
1876   # if there are any dates construct a where
1877   if ($form->{fromdate} || $form->{todate}) {
1878     if ($form->{fromdate}) {
1879       $where .= " AND $transdate >= '$form->{fromdate}'";
1880     }
1881     if ($form->{todate}) {
1882       $where .= " AND $transdate <= '$form->{todate}'";
1883     }
1884   }
1885
1886   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
1887
1888   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
1889   $sortorder = $form->{sort} if $form->{sort};
1890
1891   $query = qq|SELECT a.id, '0' AS invoice, $transdate AS transdate,
1892               a.invnumber, n.name, a.netamount,
1893               ac.amount * $ml AS tax
1894               FROM acc_trans ac
1895             JOIN $form->{db} a ON (a.id = ac.trans_id)
1896             JOIN chart ch ON (ch.id = ac.chart_id)
1897             JOIN $table n ON (n.id = a.${table}_id)
1898               WHERE $where
1899               $accno
1900               AND a.invoice = '0'
1901             UNION
1902               SELECT a.id, '1' AS invoice, $transdate AS transdate,
1903               a.invnumber, n.name, i.sellprice * i.qty AS netamount,
1904               i.sellprice * i.qty * $rate * $ml AS tax
1905               FROM acc_trans ac
1906             JOIN $form->{db} a ON (a.id = ac.trans_id)
1907             JOIN chart ch ON (ch.id = ac.chart_id)
1908             JOIN $table n ON (n.id = a.${table}_id)
1909             JOIN ${table}tax t ON (t.${table}_id = n.id)
1910             JOIN invoice i ON (i.trans_id = a.id)
1911             JOIN partstax p ON (p.parts_id = i.parts_id)
1912               WHERE $where
1913               $accno
1914               AND a.invoice = '1'
1915               ORDER by $sortorder|;
1916
1917   if ($form->{report} =~ /nontaxable/) {
1918
1919     # only gather up non-taxable transactions
1920     $query = qq|SELECT a.id, '0' AS invoice, $transdate AS transdate,
1921                 a.invnumber, n.name, a.netamount
1922                 FROM acc_trans ac
1923               JOIN $form->{db} a ON (a.id = ac.trans_id)
1924               JOIN $table n ON (n.id = a.${table}_id)
1925                 WHERE $where
1926                 AND a.invoice = '0'
1927                 AND a.netamount = a.amount
1928               UNION
1929                 SELECT a.id, '1' AS invoice, $transdate AS transdate,
1930                 a.invnumber, n.name, i.sellprice * i.qty AS netamount
1931                 FROM acc_trans ac
1932               JOIN $form->{db} a ON (a.id = ac.trans_id)
1933               JOIN $table n ON (n.id = a.${table}_id)
1934               JOIN invoice i ON (i.trans_id = a.id)
1935                 WHERE $where
1936                 AND a.invoice = '1'
1937                 AND (
1938                   a.${table}_id NOT IN (
1939                         SELECT ${table}_id FROM ${table}tax t (${table}_id)
1940                                        ) OR
1941                   i.parts_id NOT IN (
1942                         SELECT parts_id FROM partstax p (parts_id)
1943                                     )
1944                     )
1945                 GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
1946                 ORDER by $sortorder|;
1947   }
1948
1949   my $sth = $dbh->prepare($query);
1950   $sth->execute || $form->dberror($query);
1951
1952   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1953     push @{ $form->{TR} }, $ref;
1954   }
1955
1956   $sth->finish;
1957   $dbh->disconnect;
1958
1959   $main::lxdebug->leave_sub();
1960 }
1961
1962 sub paymentaccounts {
1963   $main::lxdebug->enter_sub();
1964
1965   my ($self, $myconfig, $form) = @_;
1966
1967   # connect to database, turn AutoCommit off
1968   my $dbh = $form->dbconnect_noauto($myconfig);
1969
1970   my $ARAP = uc $form->{db};
1971
1972   # get A(R|P)_paid accounts
1973   my $query = qq|SELECT c.accno, c.description
1974                  FROM chart c
1975                  WHERE c.link LIKE '%${ARAP}_paid%'|;
1976   my $sth = $dbh->prepare($query);
1977   $sth->execute || $form->dberror($query);
1978
1979   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1980     push @{ $form->{PR} }, $ref;
1981   }
1982
1983   $sth->finish;
1984   $dbh->disconnect;
1985
1986   $main::lxdebug->leave_sub();
1987 }
1988
1989 sub payments {
1990   $main::lxdebug->enter_sub();
1991
1992   my ($self, $myconfig, $form) = @_;
1993
1994   # connect to database, turn AutoCommit off
1995   my $dbh = $form->dbconnect_noauto($myconfig);
1996
1997   my $ml = 1;
1998   if ($form->{db} eq 'ar') {
1999     $table = 'customer';
2000     $ml    = -1;
2001   }
2002   if ($form->{db} eq 'ap') {
2003     $table = 'vendor';
2004   }
2005
2006   my ($query, $sth);
2007   my $dpt_join;
2008   my $where;
2009
2010   if ($form->{department_id}) {
2011     $dpt_join = qq|
2012                  JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
2013                  |;
2014
2015     $where = qq|
2016                  AND t.department_id = $form->{department_id}
2017                 |;
2018   }
2019
2020   if ($form->{fromdate}) {
2021     $where .= " AND ac.transdate >= '$form->{fromdate}'";
2022   }
2023   if ($form->{todate}) {
2024     $where .= " AND ac.transdate <= '$form->{todate}'";
2025   }
2026   if (!$form->{fx_transaction}) {
2027     $where .= " AND ac.fx_transaction = '0'";
2028   }
2029
2030   my $invnumber;
2031   my $reference;
2032   if ($form->{reference}) {
2033     $reference = $form->like(lc $form->{reference});
2034     $invnumber = " AND lower(a.invnumber) LIKE '$reference'";
2035     $reference = " AND lower(g.reference) LIKE '$reference'";
2036   }
2037   if ($form->{source}) {
2038     my $source = $form->like(lc $form->{source});
2039     $where .= " AND lower(ac.source) LIKE '$source'";
2040   }
2041   if ($form->{memo}) {
2042     my $memo = $form->like(lc $form->{memo});
2043     $where .= " AND lower(ac.memo) LIKE '$memo'";
2044   }
2045
2046   my $sortorder = join ', ',
2047     $form->sort_columns(qw(name invnumber ordnumber transdate source));
2048   $sortorder = $form->{sort} if $form->{sort};
2049
2050   # cycle through each id
2051   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
2052
2053     $query = qq|SELECT c.id, c.accno, c.description
2054                 FROM chart c
2055                 WHERE c.accno = '$accno'|;
2056     $sth = $dbh->prepare($query);
2057     $sth->execute || $form->dberror($query);
2058
2059     my $ref = $sth->fetchrow_hashref(NAME_lc);
2060     push @{ $form->{PR} }, $ref;
2061     $sth->finish;
2062
2063     $query = qq|SELECT c.name, a.invnumber, a.ordnumber,
2064                 ac.transdate, ac.amount * $ml AS paid, ac.source,
2065                 a.invoice, a.id, ac.memo, '$form->{db}' AS module
2066                 FROM acc_trans ac
2067                 JOIN $form->{db} a ON (ac.trans_id = a.id)
2068                 JOIN $table c ON (c.id = a.${table}_id)
2069                 $dpt_join
2070                 WHERE ac.chart_id = $ref->{id}
2071                 $where
2072                 $invnumber
2073
2074         UNION
2075                 SELECT g.description, g.reference, NULL AS ordnumber,
2076                 ac.transdate, ac.amount * $ml AS paid, ac.source,
2077                 '0' as invoice, g.id, ac.memo, 'gl' AS module
2078                 FROM acc_trans ac
2079                 JOIN gl g ON (g.id = ac.trans_id)
2080                 $dpt_join
2081                 WHERE ac.chart_id = $ref->{id}
2082                 $where
2083                 $reference
2084                 AND (ac.amount * $ml) > 0
2085                 ORDER BY $sortorder|;
2086
2087     $sth = $dbh->prepare($query);
2088     $sth->execute || $form->dberror($query);
2089
2090     while (my $pr = $sth->fetchrow_hashref(NAME_lc)) {
2091       push @{ $form->{ $ref->{id} } }, $pr;
2092     }
2093     $sth->finish;
2094
2095   }
2096
2097   $dbh->disconnect;
2098
2099   $main::lxdebug->leave_sub();
2100 }
2101
2102 sub bwa {
2103   $main::lxdebug->enter_sub();
2104
2105   my ($self, $myconfig, $form) = @_;
2106
2107   # connect to database
2108   my $dbh = $form->dbconnect($myconfig);
2109
2110   my $last_period = 0;
2111   my $category    = "pos_bwa";
2112   my @categories  =
2113     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);
2114
2115   $form->{decimalplaces} *= 1;
2116
2117   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2118                   $form, $category);
2119
2120   # if there are any compare dates
2121   if ($form->{fromdate} || $form->{todate}) {
2122     $last_period = 1;
2123     if ($form->{fromdate}) {
2124       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
2125       $year = $1;
2126     } else {
2127       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
2128       $year = $1;
2129     }
2130     $kummfromdate = $form->{comparefromdate};
2131     $kummtodate   = $form->{comparetodate};
2132     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form,
2133                     $category);
2134   }
2135
2136   @periods        = qw(jetzt kumm);
2137   @gesamtleistung = qw(1 2 3);
2138   @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
2139   @ergebnisse     =
2140     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
2141
2142   foreach $key (@periods) {
2143     $form->{ "$key" . "gesamtleistung" } = 0;
2144     $form->{ "$key" . "gesamtkosten" }   = 0;
2145
2146     foreach $category (@categories) {
2147
2148       if (defined($form->{$category}{$key})) {
2149         $form->{"$key$category"} =
2150           $form->format_amount($myconfig,
2151                                $form->round_amount($form->{$category}{$key}, 2
2152                                ),
2153                                $form->{decimalplaces},
2154                                '0');
2155       }
2156     }
2157     foreach $item (@gesamtleistung) {
2158       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
2159     }
2160     foreach $item (@gesamtkosten) {
2161       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
2162     }
2163     $form->{ "$key" . "rohertrag" } =
2164       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
2165     $form->{ "$key" . "betriebrohertrag" } =
2166       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
2167     $form->{ "$key" . "betriebsergebnis" } =
2168       $form->{ "$key" . "betriebrohertrag" } -
2169       $form->{ "$key" . "gesamtkosten" };
2170     $form->{ "$key" . "neutraleraufwand" } =
2171       $form->{30}{$key} + $form->{31}{$key};
2172     $form->{ "$key" . "neutralertrag" } =
2173       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
2174     $form->{ "$key" . "ergebnisvorsteuern" } =
2175       $form->{ "$key" . "betriebsergebnis" } -
2176       $form->{ "$key" . "neutraleraufwand" } +
2177       $form->{ "$key" . "neutralertrag" };
2178     $form->{ "$key" . "ergebnis" } =
2179       $form->{ "$key" . "ergebnisvorsteuern" } + $form->{35}{$key};
2180
2181     if ($form->{ "$key" . "gesamtleistung" } > 0) {
2182       foreach $category (@categories) {
2183         if (defined($form->{$category}{$key})) {
2184           $form->{ "$key" . "gl" . "$category" } =
2185             $form->format_amount(
2186                                $myconfig,
2187                                $form->round_amount(
2188                                  ($form->{$category}{$key} /
2189                                     $form->{ "$key" . "gesamtleistung" } * 100
2190                                  ),
2191                                  $form->{decimalplaces}
2192                                ),
2193                                $form->{decimalplaces},
2194                                '0');
2195         }
2196       }
2197       foreach $item (@ergebnisse) {
2198         $form->{ "$key" . "gl" . "$item" } =
2199           $form->format_amount($myconfig,
2200                                $form->round_amount(
2201                                  ( $form->{ "$key" . "$item" } /
2202                                      $form->{ "$key" . "gesamtleistung" } * 100
2203                                  ),
2204                                  $form->{decimalplaces}
2205                                ),
2206                                $form->{decimalplaces},
2207                                '0');
2208       }
2209     }
2210
2211     if ($form->{ "$key" . "gesamtkosten" } > 0) {
2212       foreach $category (@categories) {
2213         if (defined($form->{$category}{$key})) {
2214           $form->{ "$key" . "gk" . "$category" } =
2215             $form->format_amount($myconfig,
2216                                  $form->round_amount(
2217                                    ($form->{$category}{$key} /
2218                                       $form->{ "$key" . "gesamtkosten" } * 100
2219                                    ),
2220                                    $form->{decimalplaces}
2221                                  ),
2222                                  $form->{decimalplaces},
2223                                  '0');
2224         }
2225       }
2226       foreach $item (@ergebnisse) {
2227         $form->{ "$key" . "gk" . "$item" } =
2228           $form->format_amount($myconfig,
2229                                $form->round_amount(
2230                                    ($form->{ "$key" . "$item" } /
2231                                       $form->{ "$key" . "gesamtkosten" } * 100
2232                                    ),
2233                                    $form->{decimalplaces}
2234                                ),
2235                                $form->{decimalplaces},
2236                                '0');
2237       }
2238     }
2239
2240     if ($form->{10}{$key} > 0) {
2241       foreach $category (@categories) {
2242         if (defined($form->{$category}{$key})) {
2243           $form->{ "$key" . "pk" . "$category" } =
2244             $form->format_amount(
2245                         $myconfig,
2246                         $form->round_amount(
2247                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
2248                           $form->{decimalplaces}
2249                         ),
2250                         $form->{decimalplaces},
2251                         '0');
2252         }
2253       }
2254       foreach $item (@ergebnisse) {
2255         $form->{ "$key" . "pk" . "$item" } =
2256           $form->format_amount($myconfig,
2257                                $form->round_amount(
2258                                                 ($form->{ "$key" . "$item" } /
2259                                                    $form->{10}{$key} * 100
2260                                                 ),
2261                                                 $form->{decimalplaces}
2262                                ),
2263                                $form->{decimalplaces},
2264                                '0');
2265       }
2266     }
2267
2268     if ($form->{4}{$key} > 0) {
2269       foreach $category (@categories) {
2270         if (defined($form->{$category}{$key})) {
2271           $form->{ "$key" . "auf" . "$category" } =
2272             $form->format_amount(
2273                          $myconfig,
2274                          $form->round_amount(
2275                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
2276                            $form->{decimalplaces}
2277                          ),
2278                          $form->{decimalplaces},
2279                          '0');
2280         }
2281       }
2282       foreach $item (@ergebnisse) {
2283         $form->{ "$key" . "auf" . "$item" } =
2284           $form->format_amount($myconfig,
2285                                $form->round_amount(
2286                                                 ($form->{ "$key" . "$item" } /
2287                                                    $form->{4}{$key} * 100
2288                                                 ),
2289                                                 $form->{decimalplaces}
2290                                ),
2291                                $form->{decimalplaces},
2292                                '0');
2293       }
2294     }
2295
2296     foreach $item (@ergebnisse) {
2297       $form->{ "$key" . "$item" } =
2298         $form->format_amount($myconfig,
2299                              $form->round_amount($form->{ "$key" . "$item" },
2300                                                  $form->{decimalplaces}
2301                              ),
2302                              $form->{decimalplaces},
2303                              '0');
2304     }
2305
2306   }
2307   $dbh->disconnect;
2308
2309   $main::lxdebug->leave_sub();
2310 }
2311
2312 sub ustva {
2313   $main::lxdebug->enter_sub();
2314
2315   my ($self, $myconfig, $form) = @_;
2316
2317   # connect to database
2318   my $dbh = $form->dbconnect($myconfig);
2319
2320   my $last_period     = 0;
2321   my $category        = "pos_ustva";
2322   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
2323     96 66 43 45 53 62 65 67);
2324   my @categories_euro = qw(48 51 86 91 97 93 94);
2325   $form->{decimalplaces} *= 1;
2326
2327   foreach $item (@categories_cent) {
2328     $form->{"$item"} = 0;
2329   }
2330   foreach $item (@categories_euro) {
2331     $form->{"$item"} = 0;
2332   }
2333
2334   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2335                   $form, $category);
2336
2337   #   foreach $item (@categories_cent) {
2338   #     if ($form->{$item}{"jetzt"} > 0) {
2339   #             $form->{$item} = $form->{$item}{"jetzt"};
2340   #             delete $form->{$item}{"jetzt"};
2341   #     }
2342   #   }
2343   #   foreach $item (@categories_euro) {
2344   #     if ($form->{$item}{"jetzt"} > 0) {
2345   #             $form->{$item} = $form->{$item}{"jetzt"};
2346   #             delete $form->{$item}{"jetzt"};
2347   #     }  foreach $item (@categories_cent) {
2348   #     if ($form->{$item}{"jetzt"} > 0) {
2349   #             $form->{$item} = $form->{$item}{"jetzt"};
2350   #             delete $form->{$item}{"jetzt"};
2351   #     }
2352   #   }
2353   #   foreach $item (@categories_euro) {
2354   #     if ($form->{$item}{"jetzt"} > 0) {
2355   #             $form->{$item} = $form->{$item}{"jetzt"};
2356   #             delete $form->{$item}{"jetzt"};
2357   #     }
2358   #   }
2359   #
2360   #    }
2361
2362   #
2363   # Berechnung der USTVA Formularfelder
2364   #
2365   $form->{"51r"} = $form->{"511"};
2366   $form->{"86r"} = $form->{"861"};
2367   $form->{"97r"} = $form->{"971"};
2368   $form->{"93r"} = $form->{"931"};
2369
2370   #$form->{"96"}  = $form->{"94"} * 0.16;
2371   $form->{"43"} =
2372     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
2373     $form->{"96"};
2374   $form->{"45"} = $form->{"43"};
2375   $form->{"53"} = $form->{"43"};
2376   $form->{"62"} = $form->{"43"} - $form->{"66"};
2377   $form->{"65"} = $form->{"43"} - $form->{"66"};
2378   $form->{"67"} = $form->{"43"} - $form->{"66"};
2379
2380   foreach $item (@categories_cent) {
2381     $form->{$item} =
2382       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
2383                            2, '0');
2384   }
2385
2386   foreach $item (@categories_euro) {
2387     $form->{$item} =
2388       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
2389                            0, '0');
2390   }
2391
2392   $dbh->disconnect;
2393
2394   $main::lxdebug->leave_sub();
2395 }
2396
2397 sub income_statement {
2398   $main::lxdebug->enter_sub();
2399
2400   my ($self, $myconfig, $form) = @_;
2401
2402   # connect to database
2403   my $dbh = $form->dbconnect($myconfig);
2404
2405   my $last_period          = 0;
2406   my $category             = "pos_eur";
2407   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
2408   my @categories_ausgaben  =
2409     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);
2410
2411   my @ergebnisse = qw(sumeura sumeurb guvsumme);
2412
2413   $form->{decimalplaces} *= 1;
2414
2415   foreach $item (@categories_einnahmen) {
2416     $form->{$item} = 0;
2417   }
2418   foreach $item (@categories_ausgaben) {
2419     $form->{$item} = 0;
2420   }
2421
2422   foreach $item (@ergebnisse) {
2423     $form->{$item} = 0;
2424   }
2425
2426   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2427                   $form, $category);
2428
2429   foreach $item (@categories_einnahmen) {
2430     $form->{"eur${item}"} =
2431       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2432     $form->{"sumeura"} += $form->{$item};
2433   }
2434   foreach $item (@categories_ausgaben) {
2435     $form->{"eur${item}"} =
2436       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2437     $form->{"sumeurb"} += $form->{$item};
2438   }
2439
2440   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
2441
2442   foreach $item (@ergebnisse) {
2443     $form->{$item} =
2444       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2445   }
2446   $main::lxdebug->leave_sub();
2447 }
2448 1;