4ccabce4eeba340f8569d04a85c4a72a87ae2b35
[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
38 sub balance_sheet {
39   $main::lxdebug->enter_sub();
40
41   my ($self, $myconfig, $form) = @_;
42
43   # connect to database
44   my $dbh = $form->dbconnect($myconfig);
45
46   my $last_period = 0;
47   my @categories  = qw(A C L Q);
48
49   # if there are any dates construct a where
50   if ($form->{asofdate}) {
51
52     $form->{this_period} = "$form->{asofdate}";
53     $form->{period}      = "$form->{asofdate}";
54
55   }
56
57   $form->{decimalplaces} *= 1;
58
59   &get_accounts($dbh, $last_period, "", $form->{asofdate}, $form,
60                 \@categories);
61
62   # if there are any compare dates
63   if ($form->{compareasofdate}) {
64
65     $last_period = 1;
66     &get_accounts($dbh, $last_period, "", $form->{compareasofdate},
67                   $form, \@categories);
68
69     $form->{last_period} = "$form->{compareasofdate}";
70
71   }
72
73   # disconnect
74   $dbh->disconnect;
75
76   # now we got $form->{A}{accno}{ }    assets
77   # and $form->{L}{accno}{ }           liabilities
78   # and $form->{Q}{accno}{ }           equity
79   # build asset accounts
80
81   my $str;
82   my $key;
83
84   my %account = (
85                  'A' => { 'label'  => 'asset',
86                           'labels' => 'assets',
87                           'ml'     => -1
88                  },
89                  'L' => { 'label'  => 'liability',
90                           'labels' => 'liabilities',
91                           'ml'     => 1
92                  },
93                  'Q' => { 'label'  => 'equity',
94                           'labels' => 'equity',
95                           'ml'     => 1
96                  });
97
98   foreach $category (grep { !/C/ } @categories) {
99
100     foreach $key (sort keys %{ $form->{$category} }) {
101
102       $str = ($form->{l_heading}) ? $form->{padding} : "";
103
104       if ($form->{$category}{$key}{charttype} eq "A") {
105         $str .=
106           ($form->{l_accno})
107           ? "$form->{$category}{$key}{accno} - $form->{$category}{$key}{description}"
108           : "$form->{$category}{$key}{description}";
109       }
110       if ($form->{$category}{$key}{charttype} eq "H") {
111         if ($account{$category}{subtotal} && $form->{l_subtotal}) {
112           $dash = "- ";
113           push(@{ $form->{"$account{$category}{label}_account"} },
114                "$str$form->{bold}$account{$category}{subdescription}$form->{endbold}"
115           );
116           push(@{ $form->{"$account{$category}{label}_this_period"} },
117                $form->format_amount(
118                         $myconfig,
119                         $account{$category}{subthis} * $account{$category}{ml},
120                         $form->{decimalplaces}, $dash
121                ));
122
123           if ($last_period) {
124             push(@{ $form->{"$account{$category}{label}_last_period"} },
125                  $form->format_amount(
126                         $myconfig,
127                         $account{$category}{sublast} * $account{$category}{ml},
128                         $form->{decimalplaces}, $dash
129                  ));
130           }
131         }
132
133         $str =
134           "$form->{bold}$form->{$category}{$key}{description}$form->{endbold}";
135
136         $account{$category}{subthis}        = $form->{$category}{$key}{this};
137         $account{$category}{sublast}        = $form->{$category}{$key}{last};
138         $account{$category}{subdescription} =
139           $form->{$category}{$key}{description};
140         $account{$category}{subtotal} = 1;
141
142         $form->{$category}{$key}{this} = 0;
143         $form->{$category}{$key}{last} = 0;
144
145         next unless $form->{l_heading};
146
147         $dash = " ";
148       }
149
150       # push description onto array
151       push(@{ $form->{"$account{$category}{label}_account"} }, $str);
152
153       if ($form->{$category}{$key}{charttype} eq 'A') {
154         $form->{"total_$account{$category}{labels}_this_period"} +=
155           $form->{$category}{$key}{this} * $account{$category}{ml};
156         $dash = "- ";
157       }
158
159       push(@{ $form->{"$account{$category}{label}_this_period"} },
160            $form->format_amount(
161                       $myconfig,
162                       $form->{$category}{$key}{this} * $account{$category}{ml},
163                       $form->{decimalplaces}, $dash
164            ));
165
166       if ($last_period) {
167         $form->{"total_$account{$category}{labels}_last_period"} +=
168           $form->{$category}{$key}{last} * $account{$category}{ml};
169
170         push(@{ $form->{"$account{$category}{label}_last_period"} },
171              $form->format_amount(
172                       $myconfig,
173                       $form->{$category}{$key}{last} * $account{$category}{ml},
174                       $form->{decimalplaces}, $dash
175              ));
176       }
177     }
178
179     $str = ($form->{l_heading}) ? $form->{padding} : "";
180     if ($account{$category}{subtotal} && $form->{l_subtotal}) {
181       push(@{ $form->{"$account{$category}{label}_account"} },
182            "$str$form->{bold}$account{$category}{subdescription}$form->{endbold}"
183       );
184       push(@{ $form->{"$account{$category}{label}_this_period"} },
185            $form->format_amount(
186                         $myconfig,
187                         $account{$category}{subthis} * $account{$category}{ml},
188                         $form->{decimalplaces}, $dash
189            ));
190
191       if ($last_period) {
192         push(@{ $form->{"$account{$category}{label}_last_period"} },
193              $form->format_amount(
194                         $myconfig,
195                         $account{$category}{sublast} * $account{$category}{ml},
196                         $form->{decimalplaces}, $dash
197              ));
198       }
199     }
200
201   }
202
203   # totals for assets, liabilities
204   $form->{total_assets_this_period} =
205     $form->round_amount($form->{total_assets_this_period},
206                         $form->{decimalplaces});
207   $form->{total_liabilities_this_period} =
208     $form->round_amount($form->{total_liabilities_this_period},
209                         $form->{decimalplaces});
210   $form->{total_equity_this_period} =
211     $form->round_amount($form->{total_equity_this_period},
212                         $form->{decimalplaces});
213
214   # calculate earnings
215   $form->{earnings_this_period} =
216     $form->{total_assets_this_period} -
217     $form->{total_liabilities_this_period} - $form->{total_equity_this_period};
218
219   push(@{ $form->{equity_this_period} },
220        $form->format_amount($myconfig,
221                             $form->{earnings_this_period},
222                             $form->{decimalplaces}, "- "
223        ));
224
225   $form->{total_equity_this_period} =
226     $form->round_amount(
227              $form->{total_equity_this_period} + $form->{earnings_this_period},
228              $form->{decimalplaces});
229
230   # add liability + equity
231   $form->{total_this_period} =
232     $form->format_amount(
233     $myconfig,
234     $form->{total_liabilities_this_period} + $form->{total_equity_this_period},
235     $form->{decimalplaces},
236     "- ");
237
238   if ($last_period) {
239
240     # totals for assets, liabilities
241     $form->{total_assets_last_period} =
242       $form->round_amount($form->{total_assets_last_period},
243                           $form->{decimalplaces});
244     $form->{total_liabilities_last_period} =
245       $form->round_amount($form->{total_liabilities_last_period},
246                           $form->{decimalplaces});
247     $form->{total_equity_last_period} =
248       $form->round_amount($form->{total_equity_last_period},
249                           $form->{decimalplaces});
250
251     # calculate retained earnings
252     $form->{earnings_last_period} =
253       $form->{total_assets_last_period} -
254       $form->{total_liabilities_last_period} -
255       $form->{total_equity_last_period};
256
257     push(@{ $form->{equity_last_period} },
258          $form->format_amount($myconfig,
259                               $form->{earnings_last_period},
260                               $form->{decimalplaces}, "- "
261          ));
262
263     $form->{total_equity_last_period} =
264       $form->round_amount(
265              $form->{total_equity_last_period} + $form->{earnings_last_period},
266              $form->{decimalplaces});
267
268     # add liability + equity
269     $form->{total_last_period} =
270       $form->format_amount($myconfig,
271                            $form->{total_liabilities_last_period} +
272                              $form->{total_equity_last_period},
273                            $form->{decimalplaces},
274                            "- ");
275
276   }
277
278   $form->{total_liabilities_last_period} =
279     $form->format_amount($myconfig,
280                          $form->{total_liabilities_last_period},
281                          $form->{decimalplaces}, "- ")
282     if ($form->{total_liabilities_last_period} != 0);
283
284   $form->{total_equity_last_period} =
285     $form->format_amount($myconfig,
286                          $form->{total_equity_last_period},
287                          $form->{decimalplaces}, "- ")
288     if ($form->{total_equity_last_period} != 0);
289
290   $form->{total_assets_last_period} =
291     $form->format_amount($myconfig,
292                          $form->{total_assets_last_period},
293                          $form->{decimalplaces}, "- ")
294     if ($form->{total_assets_last_period} != 0);
295
296   $form->{total_assets_this_period} =
297     $form->format_amount($myconfig,
298                          $form->{total_assets_this_period},
299                          $form->{decimalplaces}, "- ");
300
301   $form->{total_liabilities_this_period} =
302     $form->format_amount($myconfig,
303                          $form->{total_liabilities_this_period},
304                          $form->{decimalplaces}, "- ");
305
306   $form->{total_equity_this_period} =
307     $form->format_amount($myconfig,
308                          $form->{total_equity_this_period},
309                          $form->{decimalplaces}, "- ");
310
311   $main::lxdebug->leave_sub();
312 }
313
314 sub get_accounts {
315   $main::lxdebug->enter_sub();
316
317   my ($dbh, $last_period, $fromdate, $todate, $form, $categories) = @_;
318
319   my ($null, $department_id) = split /--/, $form->{department};
320
321   my $query;
322   my $dpt_where;
323   my $dpt_join;
324   my $project;
325   my $where    = "1 = 1";
326   my $glwhere  = "";
327   my $subwhere = "";
328   my $item;
329
330   my $category = "AND (";
331   foreach $item (@{$categories}) {
332     $category .= qq|c.category = '$item' OR |;
333   }
334   $category =~ s/OR $/\)/;
335
336   # get headings
337   $query = qq|SELECT c.accno, c.description, c.category
338               FROM chart c
339               WHERE c.charttype = 'H'
340               $category
341               ORDER by c.accno|;
342
343   if ($form->{accounttype} eq 'gifi') {
344     $query = qq|SELECT g.accno, g.description, c.category
345                 FROM gifi g
346                 JOIN chart c ON (c.gifi_accno = g.accno)
347                 WHERE c.charttype = 'H'
348                 $category
349                 ORDER BY g.accno|;
350   }
351
352   $sth = $dbh->prepare($query);
353   $sth->execute || $form->dberror($query);
354
355   my @headingaccounts = ();
356   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
357     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
358       "$ref->{description}";
359     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
360     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
361
362     push @headingaccounts, $ref->{accno};
363   }
364
365   $sth->finish;
366
367   if ($fromdate) {
368     if ($form->{method} eq 'cash') {
369       $subwhere .= " AND transdate >= '$fromdate'";
370       $glwhere = " AND ac.transdate >= '$fromdate'";
371     } else {
372       $where .= " AND ac.transdate >= '$fromdate'";
373     }
374   }
375
376   if ($todate) {
377     $where    .= " AND ac.transdate <= '$todate'";
378     $subwhere .= " AND transdate <= '$todate'";
379   }
380
381   if ($department_id) {
382     $dpt_join = qq|
383                JOIN department t ON (a.department_id = t.id)
384                   |;
385     $dpt_where = qq|
386                AND t.id = $department_id
387                    |;
388   }
389
390   if ($form->{project_id}) {
391     $project = qq|
392                  AND ac.project_id = $form->{project_id}
393                  |;
394   }
395
396   if ($form->{accounttype} eq 'gifi') {
397
398     if ($form->{method} eq 'cash') {
399
400       $query = qq|
401
402                  SELECT g.accno, sum(ac.amount) AS amount,
403                  g.description, c.category
404                  FROM acc_trans ac
405                  JOIN chart c ON (c.id = ac.chart_id)
406                  JOIN ar a ON (a.id = ac.trans_id)
407                  JOIN gifi g ON (g.accno = c.gifi_accno)
408                  $dpt_join
409                  WHERE $where
410                  $dpt_where
411                  $category
412                  AND ac.trans_id IN
413                    (
414                      SELECT trans_id
415                      FROM acc_trans
416                      JOIN chart ON (chart_id = id)
417                      WHERE link LIKE '%AR_paid%'
418                      $subwhere
419                    )
420                  $project
421                  GROUP BY g.accno, g.description, c.category
422
423        UNION ALL
424
425                  SELECT '' AS accno, SUM(ac.amount) AS amount,
426                  '' AS description, c.category
427                  FROM acc_trans ac
428                  JOIN chart c ON (c.id = ac.chart_id)
429                  JOIN ar a ON (a.id = ac.trans_id)
430                  $dpt_join
431                  WHERE $where
432                  $dpt_where
433                  $category
434                  AND c.gifi_accno = ''
435                  AND ac.trans_id IN
436                    (
437                      SELECT trans_id
438                      FROM acc_trans
439                      JOIN chart ON (chart_id = id)
440                      WHERE link LIKE '%AR_paid%'
441                      $subwhere
442                    )
443                  $project
444                  GROUP BY c.category
445
446        UNION ALL
447
448                  SELECT g.accno, sum(ac.amount) AS amount,
449                  g.description, c.category
450                  FROM acc_trans ac
451                  JOIN chart c ON (c.id = ac.chart_id)
452                  JOIN ap a ON (a.id = ac.trans_id)
453                  JOIN gifi g ON (g.accno = c.gifi_accno)
454                  $dpt_join
455                  WHERE $where
456                  $dpt_where
457                  $category
458                  AND ac.trans_id IN
459                    (
460                      SELECT trans_id
461                      FROM acc_trans
462                      JOIN chart ON (chart_id = id)
463                      WHERE link LIKE '%AP_paid%'
464                      $subwhere
465                    )
466                  $project
467                  GROUP BY g.accno, g.description, c.category
468
469        UNION ALL
470
471                  SELECT '' AS accno, SUM(ac.amount) AS amount,
472                  '' AS description, c.category
473                  FROM acc_trans ac
474                  JOIN chart c ON (c.id = ac.chart_id)
475                  JOIN ap a ON (a.id = ac.trans_id)
476                  $dpt_join
477                  WHERE $where
478                  $dpt_where
479                  $category
480                  AND c.gifi_accno = ''
481                  AND ac.trans_id IN
482                    (
483                      SELECT trans_id
484                      FROM acc_trans
485                      JOIN chart ON (chart_id = id)
486                      WHERE link LIKE '%AP_paid%'
487                      $subwhere
488                    )
489                  $project
490                  GROUP BY c.category
491
492        UNION ALL
493
494 -- add gl
495
496                  SELECT g.accno, sum(ac.amount) AS amount,
497                  g.description, c.category
498                  FROM acc_trans ac
499                  JOIN chart c ON (c.id = ac.chart_id)
500                  JOIN gifi g ON (g.accno = c.gifi_accno)
501                  JOIN gl a ON (a.id = ac.trans_id)
502                  $dpt_join
503                  WHERE $where
504                  $glwhere
505                  $dpt_where
506                  $category
507                  AND NOT (c.link = 'AR' OR c.link = 'AP')
508                  $project
509                  GROUP BY g.accno, g.description, c.category
510
511        UNION ALL
512
513                  SELECT '' AS accno, SUM(ac.amount) AS amount,
514                  '' AS description, c.category
515                  FROM acc_trans ac
516                  JOIN chart c ON (c.id = ac.chart_id)
517                  JOIN gl a ON (a.id = ac.trans_id)
518                  $dpt_join
519                  WHERE $where
520                  $glwhere
521                  $dpt_where
522                  $category
523                  AND c.gifi_accno = ''
524                  AND NOT (c.link = 'AR' OR c.link = 'AP')
525                  $project
526                  GROUP BY c.category
527                  |;
528
529       if ($form->{project_id}) {
530
531         $query .= qq|
532
533        UNION ALL
534
535                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
536                  g.description AS description, c.category
537                  FROM invoice ac
538                  JOIN ar a ON (a.id = ac.trans_id)
539                  JOIN parts p ON (ac.parts_id = p.id)
540                  JOIN chart c on (p.income_accno_id = c.id)
541                  JOIN gifi g ON (g.accno = c.gifi_accno)
542                  $dpt_join
543         -- use transdate from subwhere
544                  WHERE 1 = 1 $subwhere
545                  AND c.category = 'I'
546                  $dpt_where
547                  AND ac.trans_id IN
548                    (
549                      SELECT trans_id
550                      FROM acc_trans
551                      JOIN chart ON (chart_id = id)
552                      WHERE link LIKE '%AR_paid%'
553                      $subwhere
554                    )
555                  $project
556                  GROUP BY g.accno, g.description, c.category
557
558        UNION ALL
559
560                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount,
561                  g.description AS description, c.category
562                  FROM invoice ac
563                  JOIN ap a ON (a.id = ac.trans_id)
564                  JOIN parts p ON (ac.parts_id = p.id)
565                  JOIN chart c on (p.expense_accno_id = c.id)
566                  JOIN gifi g ON (g.accno = c.gifi_accno)
567                  $dpt_join
568                  WHERE 1 = 1 $subwhere
569                  AND c.category = 'E'
570                  $dpt_where
571                  AND ac.trans_id IN
572                    (
573                      SELECT trans_id
574                      FROM acc_trans
575                      JOIN chart ON (chart_id = id)
576                      WHERE link LIKE '%AP_paid%'
577                      $subwhere
578                    )
579                  $project
580                  GROUP BY g.accno, g.description, c.category
581                  |;
582       }
583
584     } else {
585
586       if ($department_id) {
587         $dpt_join = qq|
588               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
589               |;
590         $dpt_where = qq|
591                AND t.department_id = $department_id
592               |;
593
594       }
595
596       $query = qq|
597
598               SELECT g.accno, SUM(ac.amount) AS amount,
599               g.description, c.category
600               FROM acc_trans ac
601               JOIN chart c ON (c.id = ac.chart_id)
602               JOIN gifi g ON (c.gifi_accno = g.accno)
603               $dpt_join
604               WHERE $where
605               $dpt_from
606               $category
607               $project
608               GROUP BY g.accno, g.description, c.category
609
610            UNION ALL
611
612               SELECT '' AS accno, SUM(ac.amount) AS amount,
613               '' AS description, c.category
614               FROM acc_trans ac
615               JOIN chart c ON (c.id = ac.chart_id)
616               $dpt_join
617               WHERE $where
618               $dpt_from
619               $category
620               AND c.gifi_accno = ''
621               $project
622               GROUP BY c.category
623               |;
624
625       if ($form->{project_id}) {
626
627         $query .= qq|
628
629          UNION ALL
630
631                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
632                  g.description AS description, c.category
633                  FROM invoice ac
634                  JOIN ar a ON (a.id = ac.trans_id)
635                  JOIN parts p ON (ac.parts_id = p.id)
636                  JOIN chart c on (p.income_accno_id = c.id)
637                  JOIN gifi g ON (c.gifi_accno = g.accno)
638                  $dpt_join
639         -- use transdate from subwhere
640                  WHERE 1 = 1 $subwhere
641                  AND c.category = 'I'
642                  $dpt_where
643                  $project
644                  GROUP BY g.accno, g.description, c.category
645
646        UNION ALL
647
648                  SELECT g.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount,
649                  g.description AS description, c.category
650                  FROM invoice ac
651                  JOIN ap a ON (a.id = ac.trans_id)
652                  JOIN parts p ON (ac.parts_id = p.id)
653                  JOIN chart c on (p.expense_accno_id = c.id)
654                  JOIN gifi g ON (c.gifi_accno = g.accno)
655                  $dpt_join
656                  WHERE 1 = 1 $subwhere
657                  AND c.category = 'E'
658                  $dpt_where
659                  $project
660                  GROUP BY g.accno, g.description, c.category
661                  |;
662       }
663
664     }
665
666   } else {    # standard account
667
668     if ($form->{method} eq 'cash') {
669
670       $query = qq|
671
672                  SELECT c.accno, sum(ac.amount) AS amount,
673                  c.description, c.category
674                  FROM acc_trans ac
675                  JOIN chart c ON (c.id = ac.chart_id)
676                  JOIN ar a ON (a.id = ac.trans_id)
677                  $dpt_join
678                  WHERE $where
679                  $dpt_where
680                  $category
681                  AND ac.trans_id IN
682                    (
683                      SELECT trans_id
684                      FROM acc_trans
685                      JOIN chart ON (chart_id = id)
686                      WHERE link LIKE '%AR_paid%'
687                      $subwhere
688                    )
689
690                  $project
691                  GROUP BY c.accno, c.description, c.category
692
693         UNION ALL
694
695                  SELECT c.accno, sum(ac.amount) AS amount,
696                  c.description, c.category
697                  FROM acc_trans ac
698                  JOIN chart c ON (c.id = ac.chart_id)
699                  JOIN ap a ON (a.id = ac.trans_id)
700                  $dpt_join
701                  WHERE $where
702                  $dpt_where
703                  $category
704                  AND ac.trans_id IN
705                    (
706                      SELECT trans_id
707                      FROM acc_trans
708                      JOIN chart ON (chart_id = id)
709                      WHERE link LIKE '%AP_paid%'
710                      $subwhere
711                    )
712
713                  $project
714                  GROUP BY c.accno, c.description, c.category
715
716         UNION ALL
717
718                  SELECT c.accno, sum(ac.amount) AS amount,
719                  c.description, c.category
720                  FROM acc_trans ac
721                  JOIN chart c ON (c.id = ac.chart_id)
722                  JOIN gl a ON (a.id = ac.trans_id)
723                  $dpt_join
724                  WHERE $where
725                  $glwhere
726                  $dpt_from
727                  $category
728                  AND NOT (c.link = 'AR' OR c.link = 'AP')
729                  $project
730                  GROUP BY c.accno, c.description, c.category
731                  |;
732
733       if ($form->{project_id}) {
734
735         $query .= qq|
736
737          UNION ALL
738
739                  SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
740                  c.description AS description, c.category
741                  FROM invoice ac
742                  JOIN ar a ON (a.id = ac.trans_id)
743                  JOIN parts p ON (ac.parts_id = p.id)
744                  JOIN chart c on (p.income_accno_id = c.id)
745                  $dpt_join
746         -- use transdate from subwhere
747                  WHERE 1 = 1 $subwhere
748                  AND c.category = 'I'
749                  $dpt_where
750                  AND ac.trans_id IN
751                    (
752                      SELECT trans_id
753                      FROM acc_trans
754                      JOIN chart ON (chart_id = id)
755                      WHERE link LIKE '%AR_paid%'
756                      $subwhere
757                    )
758
759                  $project
760                  GROUP BY c.accno, c.description, c.category
761
762          UNION ALL
763
764                  SELECT c.accno AS accno, SUM(ac.sellprice) AS amount,
765                  c.description AS description, c.category
766                  FROM invoice ac
767                  JOIN ap a ON (a.id = ac.trans_id)
768                  JOIN parts p ON (ac.parts_id = p.id)
769                  JOIN chart c on (p.expense_accno_id = c.id)
770                  $dpt_join
771                  WHERE 1 = 1 $subwhere
772                  AND c.category = 'E'
773                  $dpt_where
774                  AND ac.trans_id IN
775                    (
776                      SELECT trans_id
777                      FROM acc_trans
778                      JOIN chart ON (chart_id = id)
779                      WHERE link LIKE '%AP_paid%'
780                      $subwhere
781                    )
782
783                  $project
784                  GROUP BY c.accno, c.description, c.category
785                  |;
786       }
787
788     } else {
789
790       if ($department_id) {
791         $dpt_join = qq|
792               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
793               |;
794         $dpt_where = qq|
795                AND t.department_id = $department_id
796               |;
797       }
798
799       $query = qq|
800
801                  SELECT c.accno, sum(ac.amount) AS amount,
802                  c.description, c.category
803                  FROM acc_trans ac
804                  JOIN chart c ON (c.id = ac.chart_id)
805                  $dpt_join
806                  WHERE $where
807                  $dpt_where
808                  $category
809                  $project
810                  GROUP BY c.accno, c.description, c.category
811                  |;
812
813       if ($form->{project_id}) {
814
815         $query .= qq|
816
817         UNION ALL
818
819                  SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount,
820                  c.description AS description, c.category
821                  FROM invoice ac
822                  JOIN ar a ON (a.id = ac.trans_id)
823                  JOIN parts p ON (ac.parts_id = p.id)
824                  JOIN chart c on (p.income_accno_id = c.id)
825                  $dpt_join
826         -- use transdate from subwhere
827                  WHERE 1 = 1 $subwhere
828                  AND c.category = 'I'
829                  $dpt_where
830                  $project
831                  GROUP BY c.accno, c.description, c.category
832
833         UNION ALL
834
835                  SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount,
836                  c.description AS description, c.category
837                  FROM invoice ac
838                  JOIN ap a ON (a.id = ac.trans_id)
839                  JOIN parts p ON (ac.parts_id = p.id)
840                  JOIN chart c on (p.expense_accno_id = c.id)
841                  $dpt_join
842                  WHERE 1 = 1 $subwhere
843                  AND c.category = 'E'
844                  $dpt_where
845                  $project
846                  GROUP BY c.accno, c.description, c.category
847                  |;
848
849       }
850     }
851   }
852
853   my @accno;
854   my $accno;
855   my $ref;
856
857   my $sth = $dbh->prepare($query);
858   $sth->execute || $form->dberror($query);
859
860   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
861
862     if ($ref->{category} eq 'C') {
863       $ref->{category} = 'A';
864     }
865
866     # get last heading account
867     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
868     $accno = pop @accno;
869     if ($accno) {
870       if ($last_period) {
871         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
872       } else {
873         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
874       }
875     }
876
877     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
878     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
879       $ref->{description};
880     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
881
882     if ($last_period) {
883       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
884     } else {
885       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
886     }
887   }
888   $sth->finish;
889
890   # remove accounts with zero balance
891   foreach $category (@{$categories}) {
892     foreach $accno (keys %{ $form->{$category} }) {
893       $form->{$category}{$accno}{last} =
894         $form->round_amount($form->{$category}{$accno}{last},
895                             $form->{decimalplaces});
896       $form->{$category}{$accno}{this} =
897         $form->round_amount($form->{$category}{$accno}{this},
898                             $form->{decimalplaces});
899
900       delete $form->{$category}{$accno}
901         if (   $form->{$category}{$accno}{this} == 0
902             && $form->{$category}{$accno}{last} == 0);
903     }
904   }
905
906   $main::lxdebug->leave_sub();
907 }
908
909 sub get_accounts_g {
910   $main::lxdebug->enter_sub();
911
912   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
913
914   my ($null, $department_id) = split /--/, $form->{department};
915
916   my $query;
917   my $dpt_where;
918   my $dpt_join;
919   my $project;
920   my $where    = "1 = 1";
921   my $glwhere  = "";
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     } else {
930       $where .= " AND ac.transdate >= '$fromdate'";
931     }
932   }
933
934   if ($todate) {
935     $where    .= " AND ac.transdate <= '$todate'";
936     $subwhere .= " AND transdate <= '$todate'";
937   }
938
939   if ($department_id) {
940     $dpt_join = qq|
941                JOIN department t ON (a.department_id = t.id)
942                   |;
943     $dpt_where = qq|
944                AND t.id = $department_id
945                    |;
946   }
947
948   if ($form->{project_id}) {
949     $project = qq|
950                  AND ac.project_id = $form->{project_id}
951                  |;
952   }
953
954   if ($form->{method} eq 'cash') {
955
956     $query = qq|
957
958                  SELECT sum(ac.amount) AS amount,
959                  c.$category
960                  FROM acc_trans ac
961                  JOIN chart c ON (c.id = ac.chart_id)
962                  JOIN ar a ON (a.id = ac.trans_id)
963                  $dpt_join
964                  WHERE $where
965                  $dpt_where
966                  AND ac.trans_id IN
967                    (
968                      SELECT trans_id
969                      FROM acc_trans
970                      JOIN chart ON (chart_id = id)
971                      WHERE link LIKE '%AR_paid%'
972                      $subwhere
973                    )
974
975                  $project
976                  GROUP BY c.$category
977
978         UNION
979
980                  SELECT sum(ac.amount) AS amount,
981                  c.$category
982                  FROM acc_trans ac
983                  JOIN chart c ON (c.id = ac.chart_id)
984                  JOIN ap a ON (a.id = ac.trans_id)
985                  $dpt_join
986                  WHERE $where
987                  $dpt_where
988                  AND ac.trans_id IN
989                    (
990                      SELECT trans_id
991                      FROM acc_trans
992                      JOIN chart ON (chart_id = id)
993                      WHERE link LIKE '%AP_paid%'
994                      $subwhere
995                    )
996
997                  $project
998                  GROUP BY c.$category
999
1000         UNION
1001
1002                  SELECT sum(ac.amount) AS amount,
1003                  c.$category
1004                  FROM acc_trans ac
1005                  JOIN chart c ON (c.id = ac.chart_id)
1006                  JOIN gl a ON (a.id = ac.trans_id)
1007                  $dpt_join
1008                  WHERE $where
1009                  $glwhere
1010                  $dpt_from
1011                  AND NOT (c.link = 'AR' OR c.link = 'AP')
1012                  $project
1013                  GROUP BY c.$category
1014                  |;
1015
1016     if ($form->{project_id}) {
1017
1018       $query .= qq|
1019
1020          UNION
1021
1022                  SELECT SUM(ac.sellprice * ac.qty) AS amount,
1023                  c.$category
1024                  FROM invoice ac
1025                  JOIN ar a ON (a.id = ac.trans_id)
1026                  JOIN parts p ON (ac.parts_id = p.id)
1027                  JOIN chart c on (p.income_accno_id = c.id)
1028                  $dpt_join
1029         -- use transdate from subwhere
1030                  WHERE 1 = 1 $subwhere
1031                  AND c.category = 'I'
1032                  $dpt_where
1033                  AND ac.trans_id IN
1034                    (
1035                      SELECT trans_id
1036                      FROM acc_trans
1037                      JOIN chart ON (chart_id = id)
1038                      WHERE link LIKE '%AR_paid%'
1039                      $subwhere
1040                    )
1041
1042                  $project
1043                  GROUP BY c.$category
1044
1045          UNION
1046
1047                  SELECT SUM(ac.sellprice) AS amount,
1048                  c.$category
1049                  FROM invoice ac
1050                  JOIN ap a ON (a.id = ac.trans_id)
1051                  JOIN parts p ON (ac.parts_id = p.id)
1052                  JOIN chart c on (p.expense_accno_id = c.id)
1053                  $dpt_join
1054                  WHERE 1 = 1 $subwhere
1055                  AND c.category = 'E'
1056                  $dpt_where
1057                  AND ac.trans_id IN
1058                    (
1059                      SELECT trans_id
1060                      FROM acc_trans
1061                      JOIN chart ON (chart_id = id)
1062                      WHERE link LIKE '%AP_paid%'
1063                      $subwhere
1064                    )
1065
1066                  $project
1067                  GROUP BY c.$category
1068                  |;
1069     }
1070
1071   } else {
1072
1073     if ($department_id) {
1074       $dpt_join = qq|
1075               JOIN dpt_trans t ON (t.trans_id = ac.trans_id)
1076               |;
1077       $dpt_where = qq|
1078                AND t.department_id = $department_id
1079               |;
1080     }
1081
1082     $query = qq|
1083
1084                  SELECT sum(ac.amount) AS amount,
1085                  c.$category
1086                  FROM acc_trans ac
1087                  JOIN chart c ON (c.id = ac.chart_id)
1088                  $dpt_join
1089                  WHERE $where
1090                  $dpt_where
1091                  $project
1092                  GROUP BY c.$category
1093                  |;
1094
1095     if ($form->{project_id}) {
1096
1097       $query .= qq|
1098
1099         UNION
1100
1101                  SELECT SUM(ac.sellprice * ac.qty) AS amount,
1102                  c.$category
1103                  FROM invoice ac
1104                  JOIN ar a ON (a.id = ac.trans_id)
1105                  JOIN parts p ON (ac.parts_id = p.id)
1106                  JOIN chart c on (p.income_accno_id = c.id)
1107                  $dpt_join
1108         -- use transdate from subwhere
1109                  WHERE 1 = 1 $subwhere
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 $subwhere
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   #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
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                                ), $form->{decimalplaces}, '0');
2154       }
2155     }
2156     foreach $item (@gesamtleistung) {
2157       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
2158     }
2159     foreach $item (@gesamtkosten) {
2160       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
2161     }
2162     $form->{ "$key" . "rohertrag" } =
2163       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
2164     $form->{ "$key" . "betriebrohertrag" } =
2165       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
2166     $form->{ "$key" . "betriebsergebnis" } =
2167       $form->{ "$key" . "betriebrohertrag" } -
2168       $form->{ "$key" . "gesamtkosten" };
2169     $form->{ "$key" . "neutraleraufwand" } =
2170       $form->{30}{$key} + $form->{31}{$key};
2171     $form->{ "$key" . "neutralertrag" } =
2172       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
2173     $form->{ "$key" . "ergebnisvorsteuern" } =
2174       $form->{ "$key" . "betriebsergebnis" } -
2175       $form->{ "$key" . "neutraleraufwand" } +
2176        $form->{ "$key" . "neutralertrag" };
2177     $form->{ "$key" . "ergebnis" } =
2178       $form->{ "$key" . "ergebnisvorsteuern" } + $form->{35}{$key};
2179
2180     if ($form->{ "$key" . "gesamtleistung" } > 0) {
2181       foreach $category (@categories) {
2182         if (defined($form->{$category}{$key})) {
2183           $form->{ "$key" . "gl" . "$category" } =
2184             $form->format_amount(
2185                                $myconfig,
2186                                $form->round_amount(
2187                                  ($form->{$category}{$key} /
2188                                     $form->{ "$key" . "gesamtleistung" } * 100
2189                                  ),
2190                                  $form->{decimalplaces}
2191                                ), $form->{decimalplaces}, '0');
2192         }
2193       }
2194       foreach $item (@ergebnisse) {
2195         $form->{ "$key" . "gl" . "$item" } =
2196           $form->format_amount($myconfig,
2197                                $form->round_amount(
2198                                  ( $form->{ "$key" . "$item" } /
2199                                      $form->{ "$key" . "gesamtleistung" } * 100
2200                                  ),
2201                                  $form->{decimalplaces}
2202                                ), $form->{decimalplaces}, '0');
2203       }
2204     }
2205
2206     if ($form->{ "$key" . "gesamtkosten" } > 0) {
2207       foreach $category (@categories) {
2208         if (defined($form->{$category}{$key})) {
2209           $form->{ "$key" . "gk" . "$category" } =
2210             $form->format_amount($myconfig,
2211                                  $form->round_amount(
2212                                    ($form->{$category}{$key} /
2213                                       $form->{ "$key" . "gesamtkosten" } * 100
2214                                    ),
2215                                    $form->{decimalplaces}
2216                                  ), $form->{decimalplaces}, '0');
2217         }
2218       }
2219       foreach $item (@ergebnisse) {
2220         $form->{ "$key" . "gk" . "$item" } =
2221           $form->format_amount($myconfig,
2222                                $form->round_amount(
2223                                    ($form->{ "$key" . "$item" } /
2224                                       $form->{ "$key" . "gesamtkosten" } * 100
2225                                    ),
2226                                    $form->{decimalplaces}
2227                                ), $form->{decimalplaces}, '0');
2228       }
2229     }
2230
2231     if ($form->{10}{$key} > 0) {
2232       foreach $category (@categories) {
2233         if (defined($form->{$category}{$key})) {
2234           $form->{ "$key" . "pk" . "$category" } =
2235             $form->format_amount(
2236                       $myconfig,
2237                       $form->round_amount(
2238                         ($form->{$category}{$key} / $form->{10}{$key} * 100), 
2239                         $form->{decimalplaces}
2240                       ), $form->{decimalplaces}, '0');
2241         }
2242       }
2243       foreach $item (@ergebnisse) {
2244         $form->{ "$key" . "pk" . "$item" } =
2245           $form->format_amount($myconfig,
2246                                $form->round_amount(
2247                                                 ($form->{ "$key" . "$item" } /
2248                                                    $form->{10}{$key} * 100
2249                                                 ),
2250                                                 $form->{decimalplaces}
2251                                ), $form->{decimalplaces}, '0');
2252       }
2253     }
2254
2255     if ($form->{4}{$key} > 0) {
2256       foreach $category (@categories) {
2257         if (defined($form->{$category}{$key})) {
2258           $form->{ "$key" . "auf" . "$category" } =
2259             $form->format_amount(
2260                        $myconfig,
2261                        $form->round_amount(
2262                          ($form->{$category}{$key} / $form->{4}{$key} * 100), 
2263                          $form->{decimalplaces}
2264                        ), $form->{decimalplaces}, '0');
2265         }
2266       }
2267       foreach $item (@ergebnisse) {
2268         $form->{ "$key" . "auf" . "$item" } =
2269           $form->format_amount($myconfig,
2270                                $form->round_amount(
2271                                                 ($form->{ "$key" . "$item" } /
2272                                                    $form->{4}{$key} * 100
2273                                                 ),
2274                                                 $form->{decimalplaces}
2275                                ), $form->{decimalplaces}, '0');
2276       }
2277     }
2278
2279     foreach $item (@ergebnisse) {
2280       $form->{ "$key" . "$item" } =
2281         $form->format_amount($myconfig,
2282                              $form->round_amount($form->{ "$key" . "$item" }, 
2283                              $form->{decimalplaces}
2284                              ), $form->{decimalplaces}, '0');
2285     }
2286
2287   }
2288   $dbh->disconnect;
2289
2290   $main::lxdebug->leave_sub();
2291 }
2292
2293 sub ustva {
2294   $main::lxdebug->enter_sub();
2295
2296   my ($self, $myconfig, $form) = @_;
2297
2298   # connect to database
2299   my $dbh = $form->dbconnect($myconfig);
2300
2301   my $last_period     = 0;
2302   my $category        = "pos_ustva";
2303   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
2304                            96 66 43 45 53 62 65 67);
2305   my @categories_euro = qw(48 51 86 91 97 93 94);
2306   $form->{decimalplaces} *= 1;
2307
2308   foreach $item (@categories_cent) {
2309     $form->{"$item"} = 0;
2310   }
2311   foreach $item (@categories_euro) {
2312     $form->{"$item"} = 0;
2313   }
2314
2315   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2316                   $form, $category);
2317
2318   #   foreach $item (@categories_cent) {
2319   #     if ($form->{$item}{"jetzt"} > 0) {
2320   #             $form->{$item} = $form->{$item}{"jetzt"};
2321   #             delete $form->{$item}{"jetzt"};
2322   #     }
2323   #   }
2324   #   foreach $item (@categories_euro) {
2325   #     if ($form->{$item}{"jetzt"} > 0) {
2326   #             $form->{$item} = $form->{$item}{"jetzt"};
2327   #             delete $form->{$item}{"jetzt"};
2328   #     }  foreach $item (@categories_cent) {
2329   #     if ($form->{$item}{"jetzt"} > 0) {
2330   #             $form->{$item} = $form->{$item}{"jetzt"};
2331   #             delete $form->{$item}{"jetzt"};
2332   #     }
2333   #   }
2334   #   foreach $item (@categories_euro) {
2335   #     if ($form->{$item}{"jetzt"} > 0) {
2336   #             $form->{$item} = $form->{$item}{"jetzt"};
2337   #             delete $form->{$item}{"jetzt"};
2338   #     }
2339   #   }
2340   #
2341   #    }
2342   
2343   #
2344   # Berechnung der USTVA Formularfelder
2345   #
2346   $form->{"51r"} = $form->{"511"};
2347   $form->{"86r"} = $form->{"861"};
2348   $form->{"97r"} = $form->{"971"};
2349   $form->{"93r"} = $form->{"931"};
2350   #$form->{"96"}  = $form->{"94"} * 0.16;
2351   $form->{"43"}  =
2352     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
2353     $form->{"96"};
2354   $form->{"45"} = $form->{"43"};
2355   $form->{"53"} = $form->{"43"};
2356   $form->{"62"} = $form->{"43"} - $form->{"66"};
2357   $form->{"65"} = $form->{"43"} - $form->{"66"};
2358   $form->{"67"} = $form->{"43"} - $form->{"66"};
2359
2360   foreach $item (@categories_cent) {
2361     $form->{$item} =
2362       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2), 2, '0');
2363   }
2364
2365   foreach $item (@categories_euro) {
2366     $form->{$item} =
2367       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0), 0, '0');
2368   }
2369
2370   $dbh->disconnect;
2371
2372   $main::lxdebug->leave_sub();
2373 }
2374
2375 sub income_statement {
2376   $main::lxdebug->enter_sub();
2377
2378   my ($self, $myconfig, $form) = @_;
2379
2380   # connect to database
2381   my $dbh = $form->dbconnect($myconfig);
2382
2383   my $last_period          = 0;
2384   my $category             = "pos_eur";
2385   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
2386   my @categories_ausgaben  =
2387     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);
2388
2389   my @ergebnisse = qw(sumeura sumeurb guvsumme);
2390
2391   $form->{decimalplaces} *= 1;
2392
2393   foreach $item (@categories_einnahmen) {
2394     $form->{$item} = 0;
2395   }
2396   foreach $item (@categories_ausgaben) {
2397     $form->{$item} = 0;
2398   }
2399
2400   foreach $item (@ergebnisse) {
2401     $form->{$item} = 0;
2402   }
2403
2404   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2405                   $form, $category);
2406
2407   foreach $item (@categories_einnahmen) {
2408     $form->{"eur${item}"} =
2409       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2410     $form->{"sumeura"} += $form->{$item};
2411   }
2412   foreach $item (@categories_ausgaben) {
2413     $form->{"eur${item}"} =
2414       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2415     $form->{"sumeurb"} += $form->{$item};
2416   }
2417
2418   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
2419
2420   foreach $item (@ergebnisse) {
2421     $form->{$item} =
2422       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2423   }
2424   $main::lxdebug->leave_sub();
2425 }
2426 1;