Umbau der bisherigen Saldenbilanz zu einer richtigen Summen- Saldenliste unter Benutz...
[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 use SL::DBUtils;
38 use Data::Dumper;
39
40 sub balance_sheet {
41   $main::lxdebug->enter_sub();
42
43   my ($self, $myconfig, $form) = @_;
44
45   # connect to database
46   my $dbh = $form->dbconnect($myconfig);
47
48   my $last_period = 0;
49   my @categories  = qw(A C L Q);
50
51   # if there are any dates construct a where
52   if ($form->{asofdate}) {
53     $form->{period} = $form->{this_period} = conv_dateq($form->{asofdate});
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} = conv_dateq($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 my $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   my $sth;
329
330   my $category = qq| AND (| . join(" OR ", map({ "(c.category = " . $dbh->quote($_) . ")" } @{$categories})) . qq|) |;
331
332   # get headings
333   $query =
334     qq|SELECT c.accno, c.description, c.category
335        FROM chart c
336        WHERE (c.charttype = 'H')
337          $category
338        ORDER by c.accno|;
339
340   $sth = prepare_execute_query($form, $dbh, $query);
341
342   my @headingaccounts = ();
343   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
344     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
345       "$ref->{description}";
346     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "H";
347     $form->{ $ref->{category} }{ $ref->{accno} }{accno}     = $ref->{accno};
348
349     push @headingaccounts, $ref->{accno};
350   }
351
352   $sth->finish;
353
354   if ($fromdate) {
355     $fromdate = conv_dateq($fromdate);
356     if ($form->{method} eq 'cash') {
357       $subwhere .= " AND (transdate >= $fromdate)";
358       $glwhere = " AND (ac.transdate >= $fromdate)";
359     } else {
360       $where .= " AND (ac.transdate >= $fromdate)";
361     }
362   }
363
364   if ($todate) {
365     $todate = conv_dateq($todate);
366     $where    .= " AND (ac.transdate <= $todate)";
367     $subwhere .= " AND (transdate <= $todate)";
368   }
369
370   if ($department_id) {
371     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
372     $dpt_where = qq| AND (t.id = | . conv_i($department_id, 'NULL') . qq|)|;
373   }
374
375   if ($form->{project_id}) {
376     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
377   }
378
379   if ($form->{method} eq 'cash') {
380     $query =
381       qq|SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
382          FROM acc_trans ac
383          JOIN chart c ON (c.id = ac.chart_id)
384          JOIN ar a ON (a.id = ac.trans_id)
385          $dpt_join
386          WHERE $where
387            $dpt_where
388            $category
389            AND ac.trans_id IN
390              (
391                SELECT trans_id
392                FROM acc_trans
393                JOIN chart ON (chart_id = id)
394                WHERE (link LIKE '%AR_paid%')
395                $subwhere
396              )
397            $project
398          GROUP BY c.accno, c.description, c.category
399
400          UNION ALL
401
402          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
403          FROM acc_trans ac
404          JOIN chart c ON (c.id = ac.chart_id)
405          JOIN ap a ON (a.id = ac.trans_id)
406          $dpt_join
407          WHERE $where
408            $dpt_where
409            $category
410            AND ac.trans_id IN
411              (
412                SELECT trans_id
413                FROM acc_trans
414                JOIN chart ON (chart_id = id)
415                WHERE (link LIKE '%AP_paid%')
416                $subwhere
417              )
418            $project
419          GROUP BY c.accno, c.description, c.category
420
421          UNION ALL
422
423          SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
424          FROM acc_trans ac
425          JOIN chart c ON (c.id = ac.chart_id)
426          JOIN gl a ON (a.id = ac.trans_id)
427          $dpt_join
428          WHERE $where
429            $glwhere
430            $dpt_where
431            $category
432              AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
433            $project
434          GROUP BY c.accno, c.description, c.category |;
435
436     if ($form->{project_id}) {
437       $query .=
438         qq|
439          UNION ALL
440
441          SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
442          FROM invoice ac
443          JOIN ar a ON (a.id = ac.trans_id)
444          JOIN parts p ON (ac.parts_id = p.id)
445          JOIN chart c on (p.income_accno_id = c.id)
446          $dpt_join
447          -- use transdate from subwhere
448          WHERE (c.category = 'I')
449            $subwhere
450            $dpt_where
451            AND ac.trans_id IN
452              (
453                SELECT trans_id
454                FROM acc_trans
455                JOIN chart ON (chart_id = id)
456                WHERE (link LIKE '%AR_paid%')
457                $subwhere
458              )
459            $project
460          GROUP BY c.accno, c.description, c.category
461
462          UNION ALL
463
464          SELECT c.accno AS accno, SUM(ac.sellprice) AS amount, c.description AS description, c.category
465          FROM invoice ac
466          JOIN ap a ON (a.id = ac.trans_id)
467          JOIN parts p ON (ac.parts_id = p.id)
468          JOIN chart c on (p.expense_accno_id = c.id)
469          $dpt_join
470          WHERE (c.category = 'E')
471            $subwhere
472            $dpt_where
473            AND ac.trans_id IN
474              (
475                SELECT trans_id
476                FROM acc_trans
477                JOIN chart ON (chart_id = id)
478                WHERE link LIKE '%AP_paid%'
479                $subwhere
480              )
481            $project
482          GROUP BY c.accno, c.description, c.category |;
483     }
484
485   } else {                      # if ($form->{method} eq 'cash')
486     if ($department_id) {
487       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
488       $dpt_where = qq| AND t.department_id = $department_id |;
489     }
490
491     $query = qq|
492       SELECT c.accno, sum(ac.amount) AS amount, c.description, c.category
493       FROM acc_trans ac
494       JOIN chart c ON (c.id = ac.chart_id)
495       $dpt_join
496       WHERE $where
497         $dpt_where
498         $category
499         $project
500       GROUP BY c.accno, c.description, c.category |;
501
502     if ($form->{project_id}) {
503       $query .= qq|
504       UNION ALL
505
506       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) AS amount, c.description AS description, c.category
507       FROM invoice ac
508       JOIN ar a ON (a.id = ac.trans_id)
509       JOIN parts p ON (ac.parts_id = p.id)
510       JOIN chart c on (p.income_accno_id = c.id)
511       $dpt_join
512       -- use transdate from subwhere
513       WHERE (c.category = 'I')
514         $subwhere
515         $dpt_where
516         $project
517       GROUP BY c.accno, c.description, c.category
518
519       UNION ALL
520
521       SELECT c.accno AS accno, SUM(ac.sellprice * ac.qty) * -1 AS amount, c.description AS description, c.category
522       FROM invoice ac
523       JOIN ap a ON (a.id = ac.trans_id)
524       JOIN parts p ON (ac.parts_id = p.id)
525       JOIN chart c on (p.expense_accno_id = c.id)
526       $dpt_join
527       WHERE (c.category = 'E')
528         $subwhere
529         $dpt_where
530         $project
531       GROUP BY c.accno, c.description, c.category |;
532     }
533   }
534
535   my @accno;
536   my $accno;
537   my $ref;
538
539   my $sth = prepare_execute_query($form, $dbh, $query);
540
541   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
542
543     if ($ref->{category} eq 'C') {
544       $ref->{category} = 'A';
545     }
546
547     # get last heading account
548     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
549     $accno = pop @accno;
550     if ($accno) {
551       if ($last_period) {
552         $form->{ $ref->{category} }{$accno}{last} += $ref->{amount};
553       } else {
554         $form->{ $ref->{category} }{$accno}{this} += $ref->{amount};
555       }
556     }
557
558     $form->{ $ref->{category} }{ $ref->{accno} }{accno}       = $ref->{accno};
559     $form->{ $ref->{category} }{ $ref->{accno} }{description} =
560       $ref->{description};
561     $form->{ $ref->{category} }{ $ref->{accno} }{charttype} = "A";
562
563     if ($last_period) {
564       $form->{ $ref->{category} }{ $ref->{accno} }{last} += $ref->{amount};
565     } else {
566       $form->{ $ref->{category} }{ $ref->{accno} }{this} += $ref->{amount};
567     }
568   }
569   $sth->finish;
570
571   # remove accounts with zero balance
572   foreach $category (@{$categories}) {
573     foreach $accno (keys %{ $form->{$category} }) {
574       $form->{$category}{$accno}{last} =
575         $form->round_amount($form->{$category}{$accno}{last},
576                             $form->{decimalplaces});
577       $form->{$category}{$accno}{this} =
578         $form->round_amount($form->{$category}{$accno}{this},
579                             $form->{decimalplaces});
580
581       delete $form->{$category}{$accno}
582         if (   $form->{$category}{$accno}{this} == 0
583             && $form->{$category}{$accno}{last} == 0);
584     }
585   }
586
587   $main::lxdebug->leave_sub();
588 }
589
590 sub get_accounts_g {
591   $main::lxdebug->enter_sub();
592
593   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
594
595   my ($null, $department_id) = split /--/, $form->{department};
596
597   my $query;
598   my $dpt_where;
599   my $dpt_join;
600   my $project;
601   my $where    = "1 = 1";
602   my $glwhere  = "";
603   my $prwhere  = "";
604   my $subwhere = "";
605   my $item;
606
607   if ($fromdate) {
608     $fromdate = conv_dateq($fromdate);
609     if ($form->{method} eq 'cash') {
610       $subwhere .= " AND (transdate    >= $fromdate)";
611       $glwhere   = " AND (ac.transdate >= $fromdate)";
612       $prwhere   = " AND (ar.transdate >= $fromdate)";
613     } else {
614       $where    .= " AND (ac.transdate >= $fromdate)";
615     }
616   }
617
618   if ($todate) {
619     $todate = conv_dateq($todate);
620     $subwhere   .= " AND (transdate    <= $todate)";
621     $where      .= " AND (ac.transdate <= $todate)";
622     $prwhere    .= " AND (ar.transdate <= $todate)";
623   }
624
625   if ($department_id) {
626     $dpt_join = qq| JOIN department t ON (a.department_id = t.id) |;
627     $dpt_where = qq| AND (t.id = | . conv_i($department_id, 'NULL') . qq|) |;
628   }
629
630   if ($form->{project_id}) {
631     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}) . qq|) |;
632   }
633
634   if ($form->{method} eq 'cash') {
635     $query =
636       qq|
637        SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
638          FROM acc_trans ac
639          JOIN chart c ON (c.id = ac.chart_id)
640          JOIN ar a ON (a.id = ac.trans_id)
641          $dpt_join
642          WHERE $where $dpt_where
643            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AR_paid%') $subwhere)
644            $project
645          GROUP BY c.$category 
646
647          UNION
648
649          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
650          FROM acc_trans ac
651          JOIN chart c ON (c.id = ac.chart_id)
652          JOIN ap a ON (a.id = ac.trans_id)
653          $dpt_join
654          WHERE $where $dpt_where
655            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AP_paid%') $subwhere)
656            $project
657          GROUP BY c.$category 
658
659          UNION
660
661          SELECT SUM(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
662          FROM acc_trans ac
663          JOIN chart c ON (c.id = ac.chart_id)
664          JOIN gl a ON (a.id = ac.trans_id)
665          $dpt_join
666          WHERE $where $dpt_where $glwhere 
667            AND NOT ((c.link = 'AR') OR (c.link = 'AP'))
668            $project
669
670          $project_union
671         GROUP BY c.$category 
672         |;
673
674     if ($form->{project_id}) {
675       $project_union = qq|
676          UNION
677
678          SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
679          FROM invoice ac
680          JOIN ar a ON (a.id = ac.trans_id)
681          JOIN parts p ON (ac.parts_id = p.id)
682          JOIN chart c on (p.income_accno_id = c.id)
683          $dpt_join
684          WHERE (c.category = 'I') $prwhere $dpt_where
685            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AR_paid%') $subwhere)
686            $project
687          GROUP BY c.$category 
688
689          UNION
690
691          SELECT SUM(ac.sellprice * chart_category_to_sgn(c.category)) AS amount, c.$category
692          FROM invoice ac
693          JOIN ap a ON (a.id = ac.trans_id)
694          JOIN parts p ON (ac.parts_id = p.id)
695          JOIN chart c on (p.expense_accno_id = c.id)
696          $dpt_join
697          WHERE (c.category = 'E') $prwhere $dpt_where
698            AND ac.trans_id IN ( SELECT trans_id FROM acc_trans JOIN chart ON (chart_id = id) WHERE (link LIKE '%AP_paid%') $subwhere)
699          $project
700          GROUP BY c.$category 
701          |;
702     }
703
704   } else {                      # if ($form->{method} eq 'cash')
705     if ($department_id) {
706       $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
707       $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
708     }
709
710     $query = qq|
711         SELECT sum(ac.amount * chart_category_to_sgn(c.category)) AS amount, c.$category
712         FROM acc_trans ac
713         JOIN chart c ON (c.id = ac.chart_id)
714         $dpt_join
715         WHERE $where
716           $dpt_where
717           $project
718         GROUP BY c.$category |;
719
720     if ($form->{project_id}) {
721       $query .= qq|
722         UNION
723
724         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
725         FROM invoice ac
726         JOIN ar a ON (a.id = ac.trans_id)
727         JOIN parts p ON (ac.parts_id = p.id)
728         JOIN chart c on (p.income_accno_id = c.id)
729         $dpt_join
730         WHERE (c.category = 'I')
731           $prwhere
732           $dpt_where
733           $project
734         GROUP BY c.$category
735
736         UNION
737
738         SELECT SUM(ac.sellprice * ac.qty * chart_category_to_sgn(c.category)) AS amount, c.$category
739         FROM invoice ac
740         JOIN ap a ON (a.id = ac.trans_id)
741         JOIN parts p ON (ac.parts_id = p.id)
742         JOIN chart c on (p.expense_accno_id = c.id)
743         $dpt_join
744         WHERE (c.category = 'E')
745           $prwhere
746           $dpt_where
747           $project
748         GROUP BY c.$category |;
749     }
750   }
751
752   my @accno;
753   my $accno;
754   my $ref;
755
756   my $sth = prepare_execute_query($form, $dbh, $query);
757
758   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
759     if ($category eq "pos_bwa") {
760       if ($last_period) {
761         $form->{ $ref->{$category} }{kumm} += $ref->{amount};
762       } else {
763         $form->{ $ref->{$category} }{jetzt} += $ref->{amount};
764       }
765     } else {
766       $form->{ $ref->{$category} } += $ref->{amount};
767     }
768   }
769   $sth->finish;
770
771   $main::lxdebug->leave_sub();
772 }
773
774 sub trial_balance {
775   $main::lxdebug->enter_sub();
776
777   my ($self, $myconfig, $form) = @_;
778
779   my $dbh = $form->dbconnect($myconfig);
780
781   my ($query, $sth, $ref);
782   my %balance = ();
783   my %trb     = ();
784   my ($null, $department_id) = split /--/, $form->{department};
785   my @headingaccounts = ();
786   my $dpt_where;
787   my $dpt_join;
788   my $project;
789
790   my $where    = "1 = 1";
791   my $invwhere = $where;
792
793   if ($department_id) {
794     $dpt_join = qq| JOIN dpt_trans t ON (ac.trans_id = t.trans_id) |;
795     $dpt_where = qq| AND (t.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
796   }
797
798   # project_id only applies to getting transactions
799   # it has nothing to do with a trial balance
800   # but we use the same function to collect information
801
802   if ($form->{project_id}) {
803     $project = qq| AND (ac.project_id = | . conv_i($form->{project_id}, 'NULL') . qq|) |;
804   }
805
806   # get beginning balances
807   $query =
808     qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
809         FROM acc_trans ac
810         JOIN chart c ON (ac.chart_id = c.id)
811         $dpt_join
812         WHERE (ac.transdate < (select date_trunc('year', date ?)))
813           $dpt_where
814           $project
815         GROUP BY c.accno, c.category, c.description |;
816
817   $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
818
819   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
820
821     if ($ref->{amount} != 0 || $form->{all_accounts}) {
822       $trb{ $ref->{accno} }{description} = $ref->{description};
823       $trb{ $ref->{accno} }{charttype}   = 'A';
824       if ($ref->{category} ne "I" &&  $ref->{category} ne "E") {
825         if ($ref->{amount} > 0) {
826           $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
827         } else {
828           $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
829         }
830       }
831       $trb{ $ref->{accno} }{category}    = $ref->{category};
832     }
833
834   }
835   $sth->finish;
836
837
838   # get headings
839   $query =
840     qq|SELECT c.accno, c.description, c.category
841        FROM chart c
842        WHERE c.charttype = 'H'
843        ORDER by c.accno|;
844
845   $sth = prepare_execute_query($form, $dbh, $query);
846
847   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
848     $trb{ $ref->{accno} }{description} = $ref->{description};
849     $trb{ $ref->{accno} }{charttype}   = 'H';
850     $trb{ $ref->{accno} }{category}    = $ref->{category};
851
852     push @headingaccounts, $ref->{accno};
853   }
854
855   $sth->finish;
856
857   $where = " 1 = 1 ";
858   $saldowhere = " 1 = 1 ";
859   $sumwhere = " 1 = 1 ";
860   my $tofrom;
861
862   if ($form->{fromdate} || $form->{todate}) {
863     if ($form->{fromdate}) {
864       my $fromdate = conv_dateq($form->{fromdate});
865       $tofrom   .= " AND (ac.transdate >= $fromdate)";
866       $subwhere .= " AND (transdate >= $fromdate)";
867       $sumsubwhere .= " AND (transdate >= (select date_trunc('year', date $fromdate))) ";
868       $saldosubwhere .= " AND (((c.category='I' OR c.category='E') AND transdate>=(select date_trunc('year', date $fromdate))) OR (c.category NOT IN ('I', 'E'))) ";
869       $invwhere .= " AND (a.transdate >= $fromdate)";
870       $glsaldowhere .= " AND (((c.category='I' OR c.category='E') AND ac.transdate>=(select date_trunc('year', date $fromdate))) OR (c.category NOT IN ('I', 'E'))) ";
871       $glwhere = " AND (ac.transdate >= $fromdate)";
872       $glsumwhere = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
873     }
874     if ($form->{todate}) {
875       my $todate = conv_dateq($form->{todate});
876       $tofrom   .= " AND (ac.transdate <= $todate)";
877       $invwhere .= " AND (a.transdate <= $todate)";
878       $saldosubwhere .= " AND (transdate <= $todate)";
879       $sumsubwhere .= " AND (transdate <= $todate)";
880       $subwhere .= " AND (transdate <= $todate)";
881       $glwhere  .= " AND (ac.transdate <= $todate)";
882       $glsumwhere .= " AND (ac.transdate <= $todate) ";
883       $glsaldowhere .= " AND (ac.transdate <= $todate) ";
884    }
885   }
886
887   if ($form->{method} eq "cash") {
888     $where .=
889       qq| AND ((ac.trans_id IN (SELECT id from ar) AND
890                 ac.trans_id IN
891                   (
892                     SELECT trans_id
893                     FROM acc_trans
894                     JOIN chart ON (chart_id = id)
895                     WHERE (link LIKE '%AR_paid%')
896                       $subwhere
897                   )
898                )
899                OR
900                (ac.trans_id in (SELECT id from ap) AND
901                 ac.trans_id IN
902                   (
903                     SELECT trans_id
904                     FROM acc_trans
905                     JOIN chart ON (chart_id = id)
906                     WHERE (link LIKE '%AP_paid%')
907                       $subwhere
908                   )
909                )
910                OR
911                (ac.trans_id in (SELECT id from gl)
912                 $glwhere)
913               )|;
914     $saldowhere .=       
915 qq| AND ((ac.trans_id IN (SELECT id from ar) AND
916                 ac.trans_id IN
917                   (
918                     SELECT trans_id
919                     FROM acc_trans
920                     JOIN chart ON (chart_id = id)
921                     WHERE (link LIKE '%AR_paid%')
922                       $saldosubwhere
923                   )
924                )
925                OR
926                (ac.trans_id in (SELECT id from ap) AND
927                 ac.trans_id IN
928                   (
929                     SELECT trans_id
930                     FROM acc_trans
931                     JOIN chart ON (chart_id = id)
932                     WHERE (link LIKE '%AP_paid%')
933                       $saldosubwhere
934                   )
935                )
936                OR
937                (ac.trans_id in (SELECT id from gl)
938                 $glsaldowhere)
939               )|;
940     $sumwhere .=       
941 qq| AND ((ac.trans_id IN (SELECT id from ar) AND
942                 ac.trans_id IN
943                   (
944                     SELECT trans_id
945                     FROM acc_trans
946                     JOIN chart ON (chart_id = id)
947                     WHERE (link LIKE '%AR_paid%')
948                       $sumsubwhere
949                   )
950                )
951                OR
952                (ac.trans_id in (SELECT id from ap) AND
953                 ac.trans_id IN
954                   (
955                     SELECT trans_id
956                     FROM acc_trans
957                     JOIN chart ON (chart_id = id)
958                     WHERE (link LIKE '%AP_paid%')
959                       $sumsubwhere
960                   )
961                )
962                OR
963                (ac.trans_id in (SELECT id from gl)
964                 $glsumwhere)
965               )|;
966
967   } else {
968     $where .= $tofrom;
969     $saldowhere .= $glsaldowhere;
970     $sumwhere .= $glsumwhere;
971   }
972
973   $query = qq|
974        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
975        FROM acc_trans ac
976        JOIN chart c ON (c.id = ac.chart_id)
977        $dpt_join
978        WHERE $where
979          $dpt_where
980          $project
981        GROUP BY c.accno, c.description, c.category |;
982
983   if ($form->{project_id}) {
984     $query .= qq|
985       -- add project transactions from invoice
986
987       UNION ALL
988
989       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
990       FROM invoice ac
991       JOIN ar a ON (ac.trans_id = a.id)
992       JOIN parts p ON (ac.parts_id = p.id)
993       JOIN chart c ON (p.income_accno_id = c.id)
994       $dpt_join
995       WHERE $invwhere
996         $dpt_where
997         $project
998       GROUP BY c.accno, c.description, c.category
999
1000       UNION ALL
1001
1002       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
1003       FROM invoice ac
1004       JOIN ap a ON (ac.trans_id = a.id)
1005       JOIN parts p ON (ac.parts_id = p.id)
1006       JOIN chart c ON (p.expense_accno_id = c.id)
1007       $dpt_join
1008       WHERE $invwhere
1009         $dpt_where
1010         $project
1011       GROUP BY c.accno, c.description, c.category
1012       |;
1013     }
1014
1015   $query .= qq| ORDER BY accno|;
1016
1017   $sth = prepare_execute_query($form, $dbh, $query);
1018
1019   # calculate the debit and credit in the period
1020   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1021     $trb{ $ref->{accno} }{description} = $ref->{description};
1022     $trb{ $ref->{accno} }{charttype}   = 'A';
1023     $trb{ $ref->{accno} }{category}    = $ref->{category};
1024     $trb{ $ref->{accno} }{amount} += $ref->{amount};
1025   }
1026   $sth->finish;
1027
1028   # prepare query for each account
1029   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
1030
1031   $q_drcr =
1032     qq|SELECT
1033          (SELECT SUM(ac.amount) * -1
1034           FROM acc_trans ac
1035           JOIN chart c ON (c.id = ac.chart_id)
1036           $dpt_join
1037           WHERE $where
1038             $dpt_where
1039             $project
1040           AND (ac.amount < 0)
1041           AND (c.accno = ?)) AS debit,
1042
1043          (SELECT SUM(ac.amount)
1044           FROM acc_trans ac
1045           JOIN chart c ON (c.id = ac.chart_id)
1046           $dpt_join
1047           WHERE $where
1048             $dpt_where
1049             $project
1050           AND ac.amount > 0
1051           AND c.accno = ?) AS credit,
1052         (SELECT SUM(ac.amount)
1053          FROM acc_trans ac
1054          JOIN chart c ON (ac.chart_id = c.id)
1055          $dpt_join
1056          WHERE $saldowhere
1057            $dpt_where
1058            $project
1059          AND c.accno = ?) AS saldo,
1060
1061         (SELECT SUM(ac.amount)
1062          FROM acc_trans ac
1063          JOIN chart c ON (ac.chart_id = c.id)
1064          $dpt_join
1065          WHERE $sumwhere
1066            $dpt_where
1067            $project
1068          AND amount > 0
1069          AND c.accno = ?) AS sum_credit,
1070
1071         (SELECT SUM(ac.amount)
1072          FROM acc_trans ac
1073          JOIN chart c ON (ac.chart_id = c.id)
1074          $dpt_join
1075          WHERE $sumwhere
1076            $dpt_where
1077            $project
1078          AND amount < 0
1079          AND c.accno = ?) AS sum_debit,
1080
1081         (SELECT max(ac.transdate) FROM acc_trans ac
1082         JOIN chart c ON (ac.chart_id = c.id)
1083         $dpt_join
1084         WHERE $where
1085           $dpt_where
1086           $project
1087         AND c.accno = ?) AS last_transaction
1088
1089
1090  |;
1091
1092   $drcr = prepare_query($form, $dbh, $q_drcr);
1093
1094   if ($form->{project_id}) {
1095     # prepare query for each account
1096     $q_project_drcr =
1097       qq|SELECT
1098           (SELECT SUM(ac.sellprice * ac.qty) * -1
1099            FROM invoice ac
1100            JOIN parts p ON (ac.parts_id = p.id)
1101            JOIN ap a ON (ac.trans_id = a.id)
1102            JOIN chart c ON (p.expense_accno_id = c.id)
1103            $dpt_join
1104            WHERE $invwhere
1105              $dpt_where
1106              $project
1107            AND c.accno = ?) AS debit,
1108
1109           (SELECT SUM(ac.sellprice * ac.qty)
1110            FROM invoice ac
1111            JOIN parts p ON (ac.parts_id = p.id)
1112            JOIN ar a ON (ac.trans_id = a.id)
1113            JOIN chart c ON (p.income_accno_id = c.id)
1114            $dpt_join
1115            WHERE $invwhere
1116              $dpt_where
1117              $project
1118            AND c.accno = ?) AS credit,
1119
1120         (SELECT SUM(ac.amount)
1121          FROM acc_trans ac
1122          JOIN chart c ON (ac.chart_id = c.id)
1123          $dpt_join
1124          WHERE $saldowhere
1125            $dpt_where
1126            $project
1127          AND c.accno = ?) AS saldo,
1128
1129         (SELECT SUM(ac.amount)
1130          FROM acc_trans ac
1131          JOIN chart c ON (ac.chart_id = c.id)
1132          $dpt_join
1133          WHERE $sumwhere
1134            $dpt_where
1135            $project
1136          AND amount > 0
1137          AND c.accno = ?) AS sum_credit,
1138
1139         (SELECT SUM(ac.amount)
1140          FROM acc_trans ac
1141          JOIN chart c ON (ac.chart_id = c.id)
1142          $dpt_join
1143          WHERE $sumwhere
1144            $dpt_where
1145            $project
1146          AND amount < 0
1147          AND c.accno = ?) AS sum_debit,
1148
1149
1150         (SELECT max(ac.transdate) FROM acc_trans ac
1151         JOIN chart c ON (ac.chart_id = c.id)
1152         $dpt_join
1153         WHERE $where
1154           $dpt_where
1155           $project
1156         AND c.accno = ?) AS last_transaction
1157  |;
1158
1159     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
1160   }
1161
1162   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
1163
1164   foreach my $accno (sort keys %trb) {
1165     $ref = {};
1166
1167     $ref->{accno} = $accno;
1168     map { $ref->{$_} = $trb{$accno}{$_} }
1169       qw(description category charttype amount soll_eb haben_eb);
1170
1171     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
1172
1173     if ($trb{$accno}{charttype} eq 'A') {
1174
1175       # get DR/CR
1176       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
1177
1178       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo, $soll_kumuliert, $haben_kumuliert) = (0, 0, 0, 0, 0, 0, 0);
1179       $last_transaction = "";
1180       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
1181         $ref->{debit}  += $debit;
1182         $ref->{credit} += $credit;
1183         if ($saldo >= 0) {
1184           $ref->{haben_saldo} += $saldo;
1185         } else {
1186           $ref->{soll_saldo} += $saldo * -1;
1187         }
1188         $ref->{last_transaction} = $last_transaction;
1189         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
1190         $ref->{haben_kumuliert} = $haben_kumuliert;
1191       }
1192       $drcr->finish;
1193
1194       if ($form->{project_id}) {
1195
1196         # get DR/CR
1197         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
1198
1199         ($debit, $credit) = (0, 0);
1200         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
1201           $ref->{debit}  += $debit;
1202           $ref->{credit} += $credit;
1203           if ($saldo >= 0) {
1204             $ref->{haben_saldo} += $saldo;
1205           } else {
1206             $ref->{soll_saldo} += $saldo * -1;
1207           }
1208           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
1209           $ref->{haben_kumuliert} += $haben_kumuliert;
1210         }
1211         $project_drcr->finish;
1212       }
1213
1214       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
1215       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
1216       $ref->{haben_saldo}  = $form->round_amount($ref->{haben_saldo},  2);
1217       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
1218       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
1219       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
1220     }
1221
1222     # add subtotal
1223     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
1224     $accno = pop @accno;
1225     if ($accno) {
1226       $trb{$accno}{debit}  += $ref->{debit};
1227       $trb{$accno}{credit} += $ref->{credit};
1228       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
1229       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
1230       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
1231       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
1232     }
1233
1234     push @{ $form->{TB} }, $ref;
1235
1236   }
1237
1238   $dbh->disconnect;
1239
1240   # debits and credits for headings
1241   foreach $accno (@headingaccounts) {
1242     foreach $ref (@{ $form->{TB} }) {
1243       if ($accno eq $ref->{accno}) {
1244         $ref->{debit}  = $trb{$accno}{debit};
1245         $ref->{credit} = $trb{$accno}{credit};
1246         $ref->{soll_saldo}  = $trb{$accno}{soll_saldo};
1247         $ref->{haben_saldo} = $trb{$accno}{haben_saldo};
1248         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
1249         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};      }
1250     }
1251   }
1252
1253   $main::lxdebug->leave_sub();
1254 }
1255
1256 sub get_storno {
1257   $main::lxdebug->enter_sub();
1258   my ($self, $dbh, $form) = @_;
1259   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
1260   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
1261   my $sth =  $dbh->prepare($query);
1262   while(my $ref = $sth->fetchrow_hashref()) {
1263     $ref->{invnumer} =~ s/Storno zu //g;
1264     $form->{storno}{$ref->{invnumber}} = 1;
1265   }
1266   $main::lxdebug->leave_sub();
1267 }
1268
1269 sub aging {
1270   $main::lxdebug->enter_sub();
1271
1272   my ($self, $myconfig, $form) = @_;
1273
1274   # connect to database
1275   my $dbh     = $form->dbconnect($myconfig);
1276
1277   my ($invoice, $arap, $buysell, $ct, $ct_id);
1278
1279   if ($form->{ct} eq "customer") {
1280     $invoice = "is";
1281     $arap = "ar";
1282     $buysell = "buy";
1283     $ct = "customer";
1284   } else {
1285     $invoice = "ir";
1286     $arap = "ap";
1287     $buysell = "sell";
1288     $ct = "vendor";
1289   }
1290   $ct_id = "${ct}_id";
1291
1292   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
1293   my $todate = conv_dateq($form->{todate});
1294
1295   my $where = " 1 = 1 ";
1296   my ($name, $null);
1297
1298   if ($form->{$ct_id}) {
1299     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
1300   } elsif ($form->{ $form->{ct} }) {
1301     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
1302   }
1303
1304   my $dpt_join;
1305   if ($form->{department}) {
1306     ($null, $department_id) = split /--/, $form->{department};
1307     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
1308     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
1309   }
1310
1311   my $q_details = qq|
1312     -- between 0-30 days
1313
1314     SELECT ${ct}.id AS ctid, ${ct}.name,
1315       street, zipcode, city, country, contact, email,
1316       phone as customerphone, fax as customerfax, ${ct}number,
1317       "invnumber", "transdate",
1318       (amount - paid) as "c0", 0.00 as "c30", 0.00 as "c60", 0.00 as "c90",
1319       "duedate", invoice, ${arap}.id,
1320       (SELECT $buysell
1321        FROM exchangerate
1322        WHERE (${arap}.curr = exchangerate.curr)
1323          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
1324     FROM ${arap}, ${ct}
1325     WHERE (paid != amount)
1326       AND (${arap}.storno IS FALSE)
1327       AND (${arap}.${ct}_id = ${ct}.id)
1328       AND (${ct}.id = ?)
1329       AND (transdate <= (date $todate - interval '0 days'))
1330       AND (transdate >= (date $todate - interval '30 days'))
1331
1332     UNION
1333
1334     -- between 31-60 days
1335
1336     SELECT ${ct}.id AS ctid, ${ct}.name,
1337       street, zipcode, city, country, contact, email,
1338       phone as customerphone, fax as customerfax, ${ct}number,
1339       "invnumber", "transdate",
1340       0.00 as "c0", (amount - paid) as "c30", 0.00 as "c60", 0.00 as "c90",
1341       "duedate", invoice, ${arap}.id,
1342       (SELECT $buysell
1343        FROM exchangerate
1344        WHERE (${arap}.curr = exchangerate.curr)
1345          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
1346     FROM ${arap}, ${ct}
1347     WHERE (paid != amount)
1348       AND (${arap}.storno IS FALSE)
1349       AND (${arap}.${ct}_id = ${ct}.id)
1350       AND (${ct}.id = ?)
1351       AND (transdate < (date $todate - interval '30 days'))
1352       AND (transdate >= (date $todate - interval '60 days'))
1353
1354     UNION
1355
1356     -- between 61-90 days
1357
1358     SELECT ${ct}.id AS ctid, ${ct}.name,
1359       street, zipcode, city, country, contact, email,
1360       phone as customerphone, fax as customerfax, ${ct}number,
1361       "invnumber", "transdate",
1362       0.00 as "c0", 0.00 as "c30", (amount - paid) as "c60", 0.00 as "c90",
1363       "duedate", invoice, ${arap}.id,
1364       (SELECT $buysell
1365        FROM exchangerate
1366        WHERE (${arap}.curr = exchangerate.curr)
1367          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
1368     FROM ${arap}, ${ct}
1369     WHERE (paid != amount)
1370       AND (${arap}.storno IS FALSE)
1371       AND (${arap}.${ct}_id = ${ct}.id)
1372       AND (${ct}.id = ?)
1373       AND (transdate < (date $todate - interval '60 days'))
1374       AND (transdate >= (date $todate - interval '90 days'))
1375
1376     UNION
1377
1378     -- over 90 days
1379
1380     SELECT ${ct}.id AS ctid, ${ct}.name,
1381       street, zipcode, city, country, contact, email,
1382       phone as customerphone, fax as customerfax, ${ct}number,
1383       "invnumber", "transdate",
1384       0.00 as "c0", 0.00 as "c30", 0.00 as "c60", (amount - paid) as "c90",
1385       "duedate", invoice, ${arap}.id,
1386       (SELECT $buysell
1387        FROM exchangerate
1388        WHERE (${arap}.curr = exchangerate.curr)
1389        AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
1390     FROM ${arap}, ${ct}
1391     WHERE (paid != amount)
1392       AND (${arap}.storno IS FALSE)
1393       AND (${arap}.${ct}_id = ${ct}.id)
1394       AND (${ct}.id = ?)
1395       AND (transdate < (date $todate - interval '90 days'))
1396
1397     ORDER BY ctid, transdate, invnumber |;
1398
1399   my $sth_details = prepare_query($form, $dbh, $q_details);
1400
1401   # select outstanding vendors or customers, depends on $ct
1402   my $query =
1403     qq|SELECT DISTINCT ct.id, ct.name
1404        FROM $ct ct, $arap a
1405        $dpt_join
1406        WHERE $where
1407          AND (a.${ct_id} = ct.id)
1408          AND (a.paid != a.amount)
1409          AND (a.transdate <= $todate)
1410        ORDER BY ct.name|;
1411
1412   my $sth = prepare_execute_query($form, $dbh, $query);
1413
1414   $form->{AG} = [];
1415   # for each company that has some stuff outstanding
1416   while (my ($id) = $sth->fetchrow_array) {
1417     do_statement($form, $sth_details, $q_details, $id, $id, $id, $id);
1418
1419     while (my $ref = $sth_details->fetchrow_hashref(NAME_lc)) {
1420       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
1421       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
1422       push @{ $form->{AG} }, $ref;
1423     }
1424
1425     $sth_details->finish;
1426
1427   }
1428
1429   $sth->finish;
1430
1431   # disconnect
1432   $dbh->disconnect;
1433
1434   $main::lxdebug->leave_sub();
1435 }
1436
1437 sub get_customer {
1438   $main::lxdebug->enter_sub();
1439
1440   my ($self, $myconfig, $form) = @_;
1441
1442   # connect to database
1443   my $dbh = $form->dbconnect($myconfig);
1444
1445   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
1446
1447   my $query =
1448     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
1449        FROM $ct ct
1450        WHERE ct.id = ?|;
1451   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
1452     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
1453   $dbh->disconnect;
1454
1455   $main::lxdebug->leave_sub();
1456 }
1457
1458 sub get_taxaccounts {
1459   $main::lxdebug->enter_sub();
1460
1461   my ($self, $myconfig, $form) = @_;
1462
1463   # connect to database
1464   my $dbh = $form->dbconnect($myconfig);
1465
1466   # get tax accounts
1467   my $query =
1468     qq|SELECT c.accno, c.description, t.rate
1469        FROM chart c, tax t
1470        WHERE (c.link LIKE '%CT_tax%') AND (c.id = t.chart_id)
1471        ORDER BY c.accno|;
1472   $form->{taxaccounts} = selectall_hashref_quert($form, $dbh, $query);
1473
1474   $dbh->disconnect;
1475
1476   $main::lxdebug->leave_sub();
1477 }
1478
1479 sub tax_report {
1480   $main::lxdebug->enter_sub();
1481
1482   my ($self, $myconfig, $form) = @_;
1483
1484   # connect to database
1485   my $dbh = $form->dbconnect($myconfig);
1486
1487   my ($null, $department_id) = split /--/, $form->{department};
1488
1489   # build WHERE
1490   my $where = "1 = 1";
1491
1492   if ($department_id) {
1493     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
1494   }
1495
1496   my ($accno, $rate);
1497
1498   if ($form->{accno}) {
1499     $accno = $form->{accno};
1500     $rate  = $form->{"$form->{accno}_rate"};
1501     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
1502   }
1503   $rate *= 1;
1504
1505   my ($table, $ARAP);
1506
1507   if ($form->{db} eq 'ar') {
1508     $table = "customer";
1509     $ARAP  = "AR";
1510   } else {
1511     $table = "vendor";
1512     $ARAP  = "AP";
1513   }
1514
1515   my $arap = lc($ARAP);
1516
1517   my $transdate = "a.transdate";
1518
1519   if ($form->{method} eq 'cash') {
1520     $transdate = "a.datepaid";
1521
1522     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
1523
1524     $where .= qq|
1525       AND ac.trans_id IN
1526         (
1527           SELECT trans_id
1528           FROM acc_trans
1529           JOIN chart ON (chart_id = id)
1530           WHERE (link LIKE '%${ARAP}_paid%')
1531           AND (transdate <= $todate)
1532         )
1533       |;
1534   }
1535
1536   # if there are any dates construct a where
1537   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
1538   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
1539
1540   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
1541
1542   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
1543   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
1544
1545   if ($form->{report} !~ /nontaxable/) {
1546     $query =
1547       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
1548           ac.amount * $ml AS tax
1549          FROM acc_trans ac
1550          JOIN ${arap} a ON (a.id = ac.trans_id)
1551          JOIN chart ch ON (ch.id = ac.chart_id)
1552          JOIN $table n ON (n.id = a.${table}_id)
1553          WHERE
1554            $where
1555            $accno
1556            AND (a.invoice = '0')
1557
1558          UNION
1559
1560          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
1561            i.sellprice * i.qty * $rate * $ml AS tax
1562          FROM acc_trans ac
1563          JOIN ${arap} a ON (a.id = ac.trans_id)
1564          JOIN chart ch ON (ch.id = ac.chart_id)
1565          JOIN $table n ON (n.id = a.${table}_id)
1566          JOIN ${table}tax t ON (t.${table}_id = n.id)
1567          JOIN invoice i ON (i.trans_id = a.id)
1568          JOIN partstax p ON (p.parts_id = i.parts_id)
1569          WHERE
1570            $where
1571            $accno
1572            AND (a.invoice = '1')
1573          ORDER BY $sortorder|;
1574   } else {
1575     # only gather up non-taxable transactions
1576     $query =
1577       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount
1578          FROM acc_trans ac
1579          JOIN ${arap} a ON (a.id = ac.trans_id)
1580          JOIN $table n ON (n.id = a.${table}_id)
1581          WHERE
1582            $where
1583            AND (a.invoice = '0')
1584            AND (a.netamount = a.amount)
1585
1586          UNION
1587
1588          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount
1589          FROM acc_trans ac
1590          JOIN ${arap} a ON (a.id = ac.trans_id)
1591          JOIN $table n ON (n.id = a.${table}_id)
1592          JOIN invoice i ON (i.trans_id = a.id)
1593          WHERE
1594            $where
1595            AND (a.invoice = '1')
1596            AND (
1597              a.${table}_id NOT IN (SELECT ${table}_id FROM ${table}tax t (${table}_id))
1598              OR
1599              i.parts_id NOT IN (SELECT parts_id FROM partstax p (parts_id))
1600            )
1601          GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
1602          ORDER by $sortorder|;
1603   }
1604
1605   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
1606
1607   $dbh->disconnect;
1608
1609   $main::lxdebug->leave_sub();
1610 }
1611
1612 sub paymentaccounts {
1613   $main::lxdebug->enter_sub();
1614
1615   my ($self, $myconfig, $form) = @_;
1616
1617   # connect to database, turn AutoCommit off
1618   my $dbh = $form->dbconnect_noauto($myconfig);
1619
1620   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
1621
1622   # get A(R|P)_paid accounts
1623   my $query =
1624     qq|SELECT accno, description
1625        FROM chart
1626        WHERE link LIKE '%${ARAP}_paid%'|;
1627   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
1628
1629   $dbh->disconnect;
1630
1631   $main::lxdebug->leave_sub();
1632 }
1633
1634 sub payments {
1635   $main::lxdebug->enter_sub();
1636
1637   my ($self, $myconfig, $form) = @_;
1638
1639   # connect to database, turn AutoCommit off
1640   my $dbh = $form->dbconnect_noauto($myconfig);
1641
1642   my $ml = 1;
1643   my $arap;
1644   if ($form->{db} eq 'ar') {
1645     $table = 'customer';
1646     $ml = -1;
1647     $arap = 'ar';
1648   } else {
1649     $table = 'vendor';
1650     $arap = 'ap';
1651   }
1652
1653   my ($query, $sth);
1654   my $dpt_join;
1655   my $where;
1656
1657   if ($form->{department_id}) {
1658     $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
1659     $where = qq| AND (t.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
1660   }
1661
1662   if ($form->{fromdate}) {
1663     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
1664   }
1665   if ($form->{todate}) {
1666     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
1667   }
1668   if (!$form->{fx_transaction}) {
1669     $where .= " AND ac.fx_transaction = '0'";
1670   }
1671
1672   my $invnumber;
1673   my $reference;
1674   if ($form->{reference}) {
1675     $reference = $dbh->quote('%' . $form->{reference} . '%');
1676     $invnumber = " AND (a.invnumber LIKE $reference)";
1677     $reference = " AND (g.reference LIKE $reference)";
1678   }
1679   if ($form->{source}) {
1680     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
1681   }
1682   if ($form->{memo}) {
1683     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
1684   }
1685
1686   my $sortorder = join(', ', qw(name invnumber ordnumber transdate source));
1687   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(transdate invnumber name source memo)));
1688
1689   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
1690   my $sth = prepare_query($form, $dbh, $query);
1691
1692   my $q_details =
1693       qq|SELECT c.name, a.invnumber, a.ordnumber,
1694            ac.transdate, ac.amount * $ml AS paid, ac.source,
1695            a.invoice, a.id, ac.memo, '${arap}' AS module
1696          FROM acc_trans ac
1697          JOIN $arap a ON (ac.trans_id = a.id)
1698          JOIN $table c ON (c.id = a.${table}_id)
1699          $dpt_join
1700          WHERE (ac.chart_id = ?)
1701            $where
1702            $invnumber
1703
1704          UNION
1705
1706          SELECT g.description, g.reference, NULL AS ordnumber,
1707            ac.transdate, ac.amount * $ml AS paid, ac.source,
1708            '0' as invoice, g.id, ac.memo, 'gl' AS module
1709          FROM acc_trans ac
1710          JOIN gl g ON (g.id = ac.trans_id)
1711          $dpt_join
1712          WHERE (ac.chart_id = ?)
1713            $where
1714            $reference
1715            AND (ac.amount * $ml) > 0
1716
1717          ORDER BY $sortorder|;
1718   my $sth_details = prepare_query($form, $dbh, $q_details);
1719
1720   $form->{PR} = [];
1721
1722   # cycle through each id
1723   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
1724     do_statement($form, $sth, $query, $accno);
1725     my $ref = $sth->fetchrow_hashref();
1726     push(@{ $form->{PR} }, $ref);
1727     $sth->finish();
1728
1729     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
1730
1731     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
1732     while (my $pr = $sth_details->fetchrow_hashref()) {
1733       push(@{ $form->{ $ref->{id} } }, $pr);
1734     }
1735     $sth_details->finish();
1736   }
1737
1738   $dbh->disconnect;
1739
1740   $main::lxdebug->leave_sub();
1741 }
1742
1743 sub bwa {
1744   $main::lxdebug->enter_sub();
1745
1746   my ($self, $myconfig, $form) = @_;
1747
1748   # connect to database
1749   my $dbh = $form->dbconnect($myconfig);
1750
1751   my $last_period = 0;
1752   my $category;
1753   my @categories  =
1754     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);
1755
1756   $form->{decimalplaces} *= 1;
1757
1758   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
1759
1760   # if there are any compare dates
1761   if ($form->{fromdate} || $form->{todate}) {
1762     $last_period = 1;
1763     if ($form->{fromdate}) {
1764       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
1765       $year = $1;
1766     } else {
1767       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
1768       $year = $1;
1769     }
1770     $kummfromdate = $form->{comparefromdate};
1771     $kummtodate   = $form->{comparetodate};
1772     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
1773   }
1774
1775   @periods        = qw(jetzt kumm);
1776   @gesamtleistung = qw(1 2 3);
1777   @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
1778   @ergebnisse     =
1779     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
1780
1781   foreach $key (@periods) {
1782     $form->{ "$key" . "gesamtleistung" } = 0;
1783     $form->{ "$key" . "gesamtkosten" }   = 0;
1784
1785     foreach $category (@categories) {
1786
1787       if (defined($form->{$category}{$key})) {
1788         $form->{"$key$category"} =
1789           $form->format_amount($myconfig,
1790                                $form->round_amount($form->{$category}{$key}, 2
1791                                ),
1792                                $form->{decimalplaces},
1793                                '0');
1794       }
1795     }
1796     foreach $item (@gesamtleistung) {
1797       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
1798     }
1799     foreach $item (@gesamtkosten) {
1800       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
1801     }
1802     $form->{ "$key" . "rohertrag" } =
1803       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
1804     $form->{ "$key" . "betriebrohertrag" } =
1805       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
1806     $form->{ "$key" . "betriebsergebnis" } =
1807       $form->{ "$key" . "betriebrohertrag" } -
1808       $form->{ "$key" . "gesamtkosten" };
1809     $form->{ "$key" . "neutraleraufwand" } =
1810       $form->{30}{$key} + $form->{31}{$key};
1811     $form->{ "$key" . "neutralertrag" } =
1812       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
1813     $form->{ "$key" . "ergebnisvorsteuern" } =
1814       $form->{ "$key" . "betriebsergebnis" } -
1815       $form->{ "$key" . "neutraleraufwand" } +
1816       $form->{ "$key" . "neutralertrag" };
1817     $form->{ "$key" . "ergebnis" } =
1818       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
1819
1820     if ($form->{ "$key" . "gesamtleistung" } > 0) {
1821       foreach $category (@categories) {
1822         if (defined($form->{$category}{$key})) {
1823           $form->{ "$key" . "gl" . "$category" } =
1824             $form->format_amount(
1825                                $myconfig,
1826                                $form->round_amount(
1827                                  ($form->{$category}{$key} /
1828                                     $form->{ "$key" . "gesamtleistung" } * 100
1829                                  ),
1830                                  $form->{decimalplaces}
1831                                ),
1832                                $form->{decimalplaces},
1833                                '0');
1834         }
1835       }
1836       foreach $item (@ergebnisse) {
1837         $form->{ "$key" . "gl" . "$item" } =
1838           $form->format_amount($myconfig,
1839                                $form->round_amount(
1840                                  ( $form->{ "$key" . "$item" } /
1841                                      $form->{ "$key" . "gesamtleistung" } * 100
1842                                  ),
1843                                  $form->{decimalplaces}
1844                                ),
1845                                $form->{decimalplaces},
1846                                '0');
1847       }
1848     }
1849
1850     if ($form->{ "$key" . "gesamtkosten" } > 0) {
1851       foreach $category (@categories) {
1852         if (defined($form->{$category}{$key})) {
1853           $form->{ "$key" . "gk" . "$category" } =
1854             $form->format_amount($myconfig,
1855                                  $form->round_amount(
1856                                    ($form->{$category}{$key} /
1857                                       $form->{ "$key" . "gesamtkosten" } * 100
1858                                    ),
1859                                    $form->{decimalplaces}
1860                                  ),
1861                                  $form->{decimalplaces},
1862                                  '0');
1863         }
1864       }
1865       foreach $item (@ergebnisse) {
1866         $form->{ "$key" . "gk" . "$item" } =
1867           $form->format_amount($myconfig,
1868                                $form->round_amount(
1869                                    ($form->{ "$key" . "$item" } /
1870                                       $form->{ "$key" . "gesamtkosten" } * 100
1871                                    ),
1872                                    $form->{decimalplaces}
1873                                ),
1874                                $form->{decimalplaces},
1875                                '0');
1876       }
1877     }
1878
1879     if ($form->{10}{$key} > 0) {
1880       foreach $category (@categories) {
1881         if (defined($form->{$category}{$key})) {
1882           $form->{ "$key" . "pk" . "$category" } =
1883             $form->format_amount(
1884                         $myconfig,
1885                         $form->round_amount(
1886                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
1887                           $form->{decimalplaces}
1888                         ),
1889                         $form->{decimalplaces},
1890                         '0');
1891         }
1892       }
1893       foreach $item (@ergebnisse) {
1894         $form->{ "$key" . "pk" . "$item" } =
1895           $form->format_amount($myconfig,
1896                                $form->round_amount(
1897                                                 ($form->{ "$key" . "$item" } /
1898                                                    $form->{10}{$key} * 100
1899                                                 ),
1900                                                 $form->{decimalplaces}
1901                                ),
1902                                $form->{decimalplaces},
1903                                '0');
1904       }
1905     }
1906
1907     if ($form->{4}{$key} > 0) {
1908       foreach $category (@categories) {
1909         if (defined($form->{$category}{$key})) {
1910           $form->{ "$key" . "auf" . "$category" } =
1911             $form->format_amount(
1912                          $myconfig,
1913                          $form->round_amount(
1914                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
1915                            $form->{decimalplaces}
1916                          ),
1917                          $form->{decimalplaces},
1918                          '0');
1919         }
1920       }
1921       foreach $item (@ergebnisse) {
1922         $form->{ "$key" . "auf" . "$item" } =
1923           $form->format_amount($myconfig,
1924                                $form->round_amount(
1925                                                 ($form->{ "$key" . "$item" } /
1926                                                    $form->{4}{$key} * 100
1927                                                 ),
1928                                                 $form->{decimalplaces}
1929                                ),
1930                                $form->{decimalplaces},
1931                                '0');
1932       }
1933     }
1934
1935     foreach $item (@ergebnisse) {
1936       $form->{ "$key" . "$item" } =
1937         $form->format_amount($myconfig,
1938                              $form->round_amount($form->{ "$key" . "$item" },
1939                                                  $form->{decimalplaces}
1940                              ),
1941                              $form->{decimalplaces},
1942                              '0');
1943     }
1944
1945   }
1946   $dbh->disconnect;
1947
1948   $main::lxdebug->leave_sub();
1949 }
1950
1951 sub ustva {
1952   $main::lxdebug->enter_sub();
1953
1954   my ($self, $myconfig, $form) = @_;
1955
1956   # connect to database
1957   my $dbh = $form->dbconnect($myconfig);
1958
1959   my $last_period     = 0;
1960   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
1961     96 66 43 45 53 62 65 67);
1962   my @categories_euro = qw(48 51 86 91 97 93 94);
1963   $form->{decimalplaces} *= 1;
1964
1965   foreach $item (@categories_cent) {
1966     $form->{"$item"} = 0;
1967   }
1968   foreach $item (@categories_euro) {
1969     $form->{"$item"} = 0;
1970   }
1971
1972   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_ustva");
1973
1974   #   foreach $item (@categories_cent) {
1975   #     if ($form->{$item}{"jetzt"} > 0) {
1976   #             $form->{$item} = $form->{$item}{"jetzt"};
1977   #             delete $form->{$item}{"jetzt"};
1978   #     }
1979   #   }
1980   #   foreach $item (@categories_euro) {
1981   #     if ($form->{$item}{"jetzt"} > 0) {
1982   #             $form->{$item} = $form->{$item}{"jetzt"};
1983   #             delete $form->{$item}{"jetzt"};
1984   #     }  foreach $item (@categories_cent) {
1985   #     if ($form->{$item}{"jetzt"} > 0) {
1986   #             $form->{$item} = $form->{$item}{"jetzt"};
1987   #             delete $form->{$item}{"jetzt"};
1988   #     }
1989   #   }
1990   #   foreach $item (@categories_euro) {
1991   #     if ($form->{$item}{"jetzt"} > 0) {
1992   #             $form->{$item} = $form->{$item}{"jetzt"};
1993   #             delete $form->{$item}{"jetzt"};
1994   #     }
1995   #   }
1996   #
1997   #    }
1998
1999   #
2000   # Berechnung der USTVA Formularfelder
2001   #
2002   $form->{"51r"} = $form->{"511"};
2003   $form->{"86r"} = $form->{"861"};
2004   $form->{"97r"} = $form->{"971"};
2005   $form->{"93r"} = $form->{"931"};
2006
2007   #$form->{"96"}  = $form->{"94"} * 0.16;
2008   $form->{"43"} =
2009     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
2010     $form->{"96"};
2011   $form->{"45"} = $form->{"43"};
2012   $form->{"53"} = $form->{"43"};
2013   $form->{"62"} = $form->{"43"} - $form->{"66"};
2014   $form->{"65"} = $form->{"43"} - $form->{"66"};
2015   $form->{"67"} = $form->{"43"} - $form->{"66"};
2016
2017   foreach $item (@categories_cent) {
2018     $form->{$item} =
2019       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
2020                            2, '0');
2021   }
2022
2023   foreach $item (@categories_euro) {
2024     $form->{$item} =
2025       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
2026                            0, '0');
2027   }
2028
2029   $dbh->disconnect;
2030
2031   $main::lxdebug->leave_sub();
2032 }
2033
2034 sub income_statement {
2035   $main::lxdebug->enter_sub();
2036
2037   my ($self, $myconfig, $form) = @_;
2038
2039   # connect to database
2040   my $dbh = $form->dbconnect($myconfig);
2041
2042   my $last_period          = 0;
2043   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
2044   my @categories_ausgaben  =
2045     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);
2046
2047   my @ergebnisse = qw(sumeura sumeurb guvsumme);
2048
2049   $form->{decimalplaces} *= 1;
2050
2051   foreach $item (@categories_einnahmen) {
2052     $form->{$item} = 0;
2053   }
2054   foreach $item (@categories_ausgaben) {
2055     $form->{$item} = 0;
2056   }
2057
2058   foreach $item (@ergebnisse) {
2059     $form->{$item} = 0;
2060   }
2061
2062   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2063                   $form, "pos_eur");
2064
2065   foreach $item (@categories_einnahmen) {
2066     $form->{"eur${item}"} =
2067       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2068     $form->{"sumeura"} += $form->{$item};
2069   }
2070   foreach $item (@categories_ausgaben) {
2071     $form->{"eur${item}"} =
2072       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2073     $form->{"sumeurb"} += $form->{$item};
2074   }
2075
2076   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
2077
2078   foreach $item (@ergebnisse) {
2079     $form->{$item} =
2080       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2081   }
2082   $main::lxdebug->leave_sub();
2083 }
2084 1;