365d6e0235d4c2dd81f733efc731d2db2840f5fd
[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   my $acc_cash_where = "";
807   my $ar_cash_where = "";
808   my $ap_cash_where = "";
809
810
811   if ($form->{method} eq "cash") {
812     $acc_cash_where = qq| AND (ac.trans_id IN (SELECT id FROM ar WHERE datepaid>='$form->{fromdate}' AND datepaid<='$form->{todate}' UNION SELECT id FROM ap WHERE datepaid>='$form->{fromdate}' AND datepaid<='$form->{todate}' UNION SELECT id FROM gl WHERE transdate>='$form->{fromdate}' AND transdate<='$form->{todate}')) |;
813     $ar_ap_cash_where = qq| AND (a.datepaid>='$form->{fromdate}' AND a.datepaid<='$form->{todate}') |;
814   }
815
816   # get beginning balances
817   $query =
818     qq|SELECT c.accno, c.category, SUM(ac.amount) AS amount, c.description
819         FROM acc_trans ac
820         LEFT JOIN chart c ON (ac.chart_id = c.id)
821         $dpt_join
822         WHERE ((select date_trunc('year', ac.transdate::date)) = (select date_trunc('year', ?::date))) AND ac.ob_transaction $acc_cash_where
823           $dpt_where
824           $project
825         GROUP BY c.accno, c.category, c.description |;
826
827   $sth = prepare_execute_query($form, $dbh, $query, $form->{fromdate});
828
829   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
830
831     if ($ref->{amount} != 0 || $form->{all_accounts}) {
832       $trb{ $ref->{accno} }{description} = $ref->{description};
833       $trb{ $ref->{accno} }{charttype}   = 'A';
834    
835       if ($ref->{amount} > 0) {
836         $trb{ $ref->{accno} }{haben_eb}   = $ref->{amount};
837       } else {
838         $trb{ $ref->{accno} }{soll_eb}   = $ref->{amount} * -1;
839       }
840       $trb{ $ref->{accno} }{category}    = $ref->{category};
841     }
842
843   }
844   $sth->finish;
845
846
847   # get headings
848   $query =
849     qq|SELECT c.accno, c.description, c.category
850        FROM chart c
851        WHERE c.charttype = 'H'
852        ORDER by c.accno|;
853
854   $sth = prepare_execute_query($form, $dbh, $query);
855
856   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
857     $trb{ $ref->{accno} }{description} = $ref->{description};
858     $trb{ $ref->{accno} }{charttype}   = 'H';
859     $trb{ $ref->{accno} }{category}    = $ref->{category};
860
861     push @headingaccounts, $ref->{accno};
862   }
863
864   $sth->finish;
865
866   $where = " 1 = 1 ";
867   $saldowhere = " 1 = 1 ";
868   $sumwhere = " 1 = 1 ";
869   my $tofrom;
870
871   if ($form->{fromdate} || $form->{todate}) {
872     if ($form->{fromdate}) {
873       my $fromdate = conv_dateq($form->{fromdate});
874       $tofrom   .= " AND (ac.transdate >= $fromdate)";
875       $subwhere .= " AND (transdate >= $fromdate)";
876       $sumsubwhere .= " AND (transdate >= (select date_trunc('year', date $fromdate))) ";
877       $saldosubwhere .= " AND transdate>=(select date_trunc('year', date $fromdate))  ";
878       $invwhere .= " AND (a.transdate >= $fromdate)";
879       $glsaldowhere .= " AND ac.transdate>=(select date_trunc('year', date $fromdate)) ";
880       $glwhere = " AND (ac.transdate >= $fromdate)";
881       $glsumwhere = " AND (ac.transdate >= (select date_trunc('year', date $fromdate))) ";
882     }
883     if ($form->{todate}) {
884       my $todate = conv_dateq($form->{todate});
885       $tofrom   .= " AND (ac.transdate <= $todate)";
886       $invwhere .= " AND (a.transdate <= $todate)";
887       $saldosubwhere .= " AND (transdate <= $todate)";
888       $sumsubwhere .= " AND (transdate <= $todate)";
889       $subwhere .= " AND (transdate <= $todate)";
890       $glwhere  .= " AND (ac.transdate <= $todate)";
891       $glsumwhere .= " AND (ac.transdate <= $todate) ";
892       $glsaldowhere .= " AND (ac.transdate <= $todate) ";
893    }
894   }
895
896   if ($form->{method} eq "cash") {
897     $where .=
898       qq| AND ((ac.trans_id IN (SELECT id from ar) AND
899                 ac.trans_id IN
900                   (
901                     SELECT trans_id
902                     FROM acc_trans
903                     JOIN chart ON (chart_id = id)
904                     WHERE (link LIKE '%AR_paid%')
905                       $subwhere
906                   )
907                )
908                OR
909                (ac.trans_id in (SELECT id from ap) AND
910                 ac.trans_id IN
911                   (
912                     SELECT trans_id
913                     FROM acc_trans
914                     JOIN chart ON (chart_id = id)
915                     WHERE (link LIKE '%AP_paid%')
916                       $subwhere
917                   )
918                )
919                OR
920                (ac.trans_id in (SELECT id from gl)
921                 $glwhere)
922               )|;
923     $saldowhere .=       
924 qq| AND ((ac.trans_id IN (SELECT id from ar) AND
925                 ac.trans_id IN
926                   (
927                     SELECT trans_id
928                     FROM acc_trans
929                     JOIN chart ON (chart_id = id)
930                     WHERE (link LIKE '%AR_paid%')
931                       $saldosubwhere
932                   )
933                )
934                OR
935                (ac.trans_id in (SELECT id from ap) AND
936                 ac.trans_id IN
937                   (
938                     SELECT trans_id
939                     FROM acc_trans
940                     JOIN chart ON (chart_id = id)
941                     WHERE (link LIKE '%AP_paid%')
942                       $saldosubwhere
943                   )
944                )
945                OR
946                (ac.trans_id in (SELECT id from gl)
947                 $glsaldowhere)
948               )|;
949     $sumwhere .=       
950 qq| AND ((ac.trans_id IN (SELECT id from ar) AND
951                 ac.trans_id IN
952                   (
953                     SELECT trans_id
954                     FROM acc_trans
955                     JOIN chart ON (chart_id = id)
956                     WHERE (link LIKE '%AR_paid%')
957                       $sumsubwhere
958                   )
959                )
960                OR
961                (ac.trans_id in (SELECT id from ap) AND
962                 ac.trans_id IN
963                   (
964                     SELECT trans_id
965                     FROM acc_trans
966                     JOIN chart ON (chart_id = id)
967                     WHERE (link LIKE '%AP_paid%')
968                       $sumsubwhere
969                   )
970                )
971                OR
972                (ac.trans_id in (SELECT id from gl)
973                 $glsumwhere)
974               )|;
975
976   } else {
977     $where .= $tofrom . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
978     $saldowhere .= $glsaldowhere . " AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
979     $sumwhere .= $glsumwhere . " AND (NOT ac.ob_transaction OR ac.ob_transaction IS NULL) AND (NOT ac.cb_transaction OR ac.cb_transaction IS NULL)";
980   }
981
982   $query = qq|
983        SELECT c.accno, c.description, c.category, SUM(ac.amount) AS amount
984        FROM acc_trans ac
985        JOIN chart c ON (c.id = ac.chart_id)
986        $dpt_join
987        WHERE $where
988          $dpt_where
989          $project
990        GROUP BY c.accno, c.description, c.category |;
991
992   if ($form->{project_id}) {
993     $query .= qq|
994       -- add project transactions from invoice
995
996       UNION ALL
997
998       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) AS amount
999       FROM invoice ac
1000       JOIN ar a ON (ac.trans_id = a.id)
1001       JOIN parts p ON (ac.parts_id = p.id)
1002       JOIN chart c ON (p.income_accno_id = c.id)
1003       $dpt_join
1004       WHERE $invwhere
1005         $dpt_where
1006         $project
1007       GROUP BY c.accno, c.description, c.category
1008
1009       UNION ALL
1010
1011       SELECT c.accno, c.description, c.category, SUM(ac.sellprice * ac.qty) * -1 AS amount
1012       FROM invoice ac
1013       JOIN ap a ON (ac.trans_id = a.id)
1014       JOIN parts p ON (ac.parts_id = p.id)
1015       JOIN chart c ON (p.expense_accno_id = c.id)
1016       $dpt_join
1017       WHERE $invwhere
1018         $dpt_where
1019         $project
1020       GROUP BY c.accno, c.description, c.category
1021       |;
1022     }
1023
1024   $query .= qq| ORDER BY accno|;
1025
1026   $sth = prepare_execute_query($form, $dbh, $query);
1027
1028   # calculate the debit and credit in the period
1029   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1030     $trb{ $ref->{accno} }{description} = $ref->{description};
1031     $trb{ $ref->{accno} }{charttype}   = 'A';
1032     $trb{ $ref->{accno} }{category}    = $ref->{category};
1033     $trb{ $ref->{accno} }{amount} += $ref->{amount};
1034   }
1035   $sth->finish;
1036
1037   # prepare query for each account
1038   my ($q_drcr, $drcr, $q_project_drcr, $project_drcr);
1039
1040   $q_drcr =
1041     qq|SELECT
1042          (SELECT SUM(ac.amount) * -1
1043           FROM acc_trans ac
1044           JOIN chart c ON (c.id = ac.chart_id)
1045           $dpt_join
1046           WHERE $where
1047             $dpt_where
1048             $project
1049           AND (ac.amount < 0)
1050           AND (c.accno = ?)) AS debit,
1051
1052          (SELECT SUM(ac.amount)
1053           FROM acc_trans ac
1054           JOIN chart c ON (c.id = ac.chart_id)
1055           $dpt_join
1056           WHERE $where
1057             $dpt_where
1058             $project
1059           AND ac.amount > 0
1060           AND c.accno = ?) AS credit,
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 $saldowhere
1066            $dpt_where
1067            $project
1068          AND c.accno = ?) AS saldo,
1069
1070         (SELECT SUM(ac.amount)
1071          FROM acc_trans ac
1072          JOIN chart c ON (ac.chart_id = c.id)
1073          $dpt_join
1074          WHERE $sumwhere
1075            $dpt_where
1076            $project
1077          AND amount > 0
1078          AND c.accno = ?) AS sum_credit,
1079
1080         (SELECT SUM(ac.amount)
1081          FROM acc_trans ac
1082          JOIN chart c ON (ac.chart_id = c.id)
1083          $dpt_join
1084          WHERE $sumwhere
1085            $dpt_where
1086            $project
1087          AND amount < 0
1088          AND c.accno = ?) AS sum_debit,
1089
1090         (SELECT max(ac.transdate) FROM acc_trans ac
1091         JOIN chart c ON (ac.chart_id = c.id)
1092         $dpt_join
1093         WHERE $where
1094           $dpt_where
1095           $project
1096         AND c.accno = ?) AS last_transaction
1097
1098
1099  |;
1100
1101   $drcr = prepare_query($form, $dbh, $q_drcr);
1102
1103   if ($form->{project_id}) {
1104     # prepare query for each account
1105     $q_project_drcr =
1106       qq|SELECT
1107           (SELECT SUM(ac.sellprice * ac.qty) * -1
1108            FROM invoice ac
1109            JOIN parts p ON (ac.parts_id = p.id)
1110            JOIN ap a ON (ac.trans_id = a.id)
1111            JOIN chart c ON (p.expense_accno_id = c.id)
1112            $dpt_join
1113            WHERE $invwhere
1114              $dpt_where
1115              $project
1116            AND c.accno = ?) AS debit,
1117
1118           (SELECT SUM(ac.sellprice * ac.qty)
1119            FROM invoice ac
1120            JOIN parts p ON (ac.parts_id = p.id)
1121            JOIN ar a ON (ac.trans_id = a.id)
1122            JOIN chart c ON (p.income_accno_id = c.id)
1123            $dpt_join
1124            WHERE $invwhere
1125              $dpt_where
1126              $project
1127            AND c.accno = ?) AS credit,
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 $saldowhere
1134            $dpt_where
1135            $project
1136          AND c.accno = ?) AS saldo,
1137
1138         (SELECT SUM(ac.amount)
1139          FROM acc_trans ac
1140          JOIN chart c ON (ac.chart_id = c.id)
1141          $dpt_join
1142          WHERE $sumwhere
1143            $dpt_where
1144            $project
1145          AND amount > 0
1146          AND c.accno = ?) AS sum_credit,
1147
1148         (SELECT SUM(ac.amount)
1149          FROM acc_trans ac
1150          JOIN chart c ON (ac.chart_id = c.id)
1151          $dpt_join
1152          WHERE $sumwhere
1153            $dpt_where
1154            $project
1155          AND amount < 0
1156          AND c.accno = ?) AS sum_debit,
1157
1158
1159         (SELECT max(ac.transdate) FROM acc_trans ac
1160         JOIN chart c ON (ac.chart_id = c.id)
1161         $dpt_join
1162         WHERE $where
1163           $dpt_where
1164           $project
1165         AND c.accno = ?) AS last_transaction
1166  |;
1167
1168     $project_drcr = prepare_query($form, $dbh, $q_project_drcr);
1169   }
1170
1171
1172   my ($debit, $credit, $saldo, $soll_saldo, $haben_saldo,$soll_kummuliert, $haben_kummuliert, $last_transaction);
1173
1174   foreach my $accno (sort keys %trb) {
1175     $ref = {};
1176
1177     $ref->{accno} = $accno;
1178     map { $ref->{$_} = $trb{$accno}{$_} }
1179       qw(description category charttype amount soll_eb haben_eb);
1180
1181     $ref->{balance} = $form->round_amount($balance{ $ref->{accno} }, 2);
1182
1183     if ($trb{$accno}{charttype} eq 'A') {
1184
1185       # get DR/CR
1186       do_statement($form, $drcr, $q_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
1187
1188       ($debit, $credit, $saldo, $haben_saldo, $soll_saldo, $soll_kumuliert, $haben_kumuliert) = (0, 0, 0, 0, 0, 0, 0);
1189       $last_transaction = "";
1190       while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $drcr->fetchrow_array) {
1191         $ref->{debit}  += $debit;
1192         $ref->{credit} += $credit;
1193         if ($saldo >= 0) {
1194           $ref->{haben_saldo} += $saldo;
1195         } else {
1196           $ref->{soll_saldo} += $saldo * -1;
1197         }
1198         $ref->{last_transaction} = $last_transaction;
1199         $ref->{soll_kumuliert} = $soll_kumuliert * -1;
1200         $ref->{haben_kumuliert} = $haben_kumuliert;
1201       }
1202       $drcr->finish;
1203
1204       if ($form->{project_id}) {
1205
1206         # get DR/CR
1207         do_statement($form, $project_drcr, $q_project_drcr, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno}, $ref->{accno});
1208
1209         ($debit, $credit) = (0, 0);
1210         while (($debit, $credit, $saldo, $haben_kumuliert, $soll_kumuliert, $last_transaction) = $project_drcr->fetchrow_array) {
1211           $ref->{debit}  += $debit;
1212           $ref->{credit} += $credit;
1213           if ($saldo >= 0) {
1214             $ref->{haben_saldo} += $saldo;
1215           } else {
1216             $ref->{soll_saldo} += $saldo * -1;
1217           }
1218           $ref->{soll_kumuliert} += $soll_kumuliert * -1;
1219           $ref->{haben_kumuliert} += $haben_kumuliert;
1220         }
1221         $project_drcr->finish;
1222       }
1223
1224       $ref->{debit}  = $form->round_amount($ref->{debit},  2);
1225       $ref->{credit} = $form->round_amount($ref->{credit}, 2);
1226       $ref->{haben_saldo}  = $form->round_amount($ref->{haben_saldo},  2);
1227       $ref->{soll_saldo} = $form->round_amount($ref->{soll_saldo}, 2);
1228       $ref->{haben_kumuliert}  = $form->round_amount($ref->{haben_kumuliert},  2);
1229       $ref->{soll_kumuliert} = $form->round_amount($ref->{soll_kumuliert}, 2);
1230     }
1231
1232     # add subtotal
1233     @accno = grep { $_ le "$ref->{accno}" } @headingaccounts;
1234     $accno = pop @accno;
1235     if ($accno) {
1236       $trb{$accno}{debit}  += $ref->{debit};
1237       $trb{$accno}{credit} += $ref->{credit};
1238       $trb{$accno}{soll_saldo}  += $ref->{soll_saldo};
1239       $trb{$accno}{haben_saldo} += $ref->{haben_saldo};
1240       $trb{$accno}{soll_kumuliert}  += $ref->{soll_kumuliert};
1241       $trb{$accno}{haben_kumuliert} += $ref->{haben_kumuliert};
1242     }
1243
1244     push @{ $form->{TB} }, $ref;
1245
1246   }
1247
1248   $dbh->disconnect;
1249
1250   # debits and credits for headings
1251   foreach $accno (@headingaccounts) {
1252     foreach $ref (@{ $form->{TB} }) {
1253       if ($accno eq $ref->{accno}) {
1254         $ref->{debit}  = $trb{$accno}{debit};
1255         $ref->{credit} = $trb{$accno}{credit};
1256         $ref->{soll_saldo}  = $trb{$accno}{soll_saldo};
1257         $ref->{haben_saldo} = $trb{$accno}{haben_saldo};
1258         $ref->{soll_kumuliert}  = $trb{$accno}{soll_kumuliert};
1259         $ref->{haben_kumuliert} = $trb{$accno}{haben_kumuliert};      }
1260     }
1261   }
1262
1263   $main::lxdebug->leave_sub();
1264 }
1265
1266 sub get_storno {
1267   $main::lxdebug->enter_sub();
1268   my ($self, $dbh, $form) = @_;
1269   my $arap = $form->{arap} eq "ar" ? "ar" : "ap";
1270   my $query = qq|SELECT invnumber FROM $arap WHERE invnumber LIKE "Storno zu "|;
1271   my $sth =  $dbh->prepare($query);
1272   while(my $ref = $sth->fetchrow_hashref()) {
1273     $ref->{invnumer} =~ s/Storno zu //g;
1274     $form->{storno}{$ref->{invnumber}} = 1;
1275   }
1276   $main::lxdebug->leave_sub();
1277 }
1278
1279 sub aging {
1280   $main::lxdebug->enter_sub();
1281
1282   my ($self, $myconfig, $form) = @_;
1283
1284   # connect to database
1285   my $dbh     = $form->dbconnect($myconfig);
1286
1287   my ($invoice, $arap, $buysell, $ct, $ct_id, $ml);
1288
1289   if ($form->{ct} eq "customer") {
1290     $invoice = "is";
1291     $arap = "ar";
1292     $buysell = "buy";
1293     $ct = "customer";
1294     $ml = -1;
1295   } else {
1296     $invoice = "ir";
1297     $arap = "ap";
1298     $buysell = "sell";
1299     $ct = "vendor";
1300     $ml = 1;
1301   }
1302   $ct_id = "${ct}_id";
1303
1304   $form->{todate} = $form->current_date($myconfig) unless ($form->{todate});
1305   my $todate = conv_dateq($form->{todate});
1306   my $fromdate = conv_dateq($form->{fromdate});
1307
1308   my $fromwhere = ($form->{fromdate} ne "") ? " AND (transdate >= (date $fromdate)) " : "";
1309
1310   my $where = " 1 = 1 ";
1311   my ($name, $null);
1312
1313   if ($form->{$ct_id}) {
1314     $where .= qq| AND (ct.id = | . conv_i($form->{$ct_id}) . qq|)|;
1315   } elsif ($form->{ $form->{ct} }) {
1316     $where .= qq| AND (ct.name ILIKE | . $dbh->quote('%' . $form->{$ct} . '%') . qq|)|;
1317   }
1318
1319   my $dpt_join;
1320   if ($form->{department}) {
1321     ($null, $department_id) = split /--/, $form->{department};
1322     $dpt_join = qq| JOIN department d ON (a.department_id = d.id) |;
1323     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|)|;
1324   }
1325
1326   my $q_details = qq|
1327     -- between 0-30 days
1328
1329     SELECT ${ct}.id AS ctid, ${ct}.name,
1330       street, zipcode, city, country, contact, email,
1331       phone as customerphone, fax as customerfax, ${ct}number,
1332       "invnumber", "transdate",
1333       (amount - COALESCE((SELECT sum(amount)*$ml FROM acc_trans LEFT JOIN chart ON (acc_trans.chart_id=chart.id) WHERE link ilike '%paid%' AND acc_trans.trans_id=${arap}.id AND acc_trans.transdate <= (date $todate)),0)) as "open", "amount",
1334       "duedate", invoice, ${arap}.id,
1335       (SELECT $buysell
1336        FROM exchangerate
1337        WHERE (${arap}.curr = exchangerate.curr)
1338          AND (exchangerate.transdate = ${arap}.transdate)) AS exchangerate
1339     FROM ${arap}, ${ct}
1340     WHERE ((paid != amount) OR (datepaid > (date $todate) AND datepaid is not null))
1341       AND (${arap}.storno IS FALSE)
1342       AND (${arap}.${ct}_id = ${ct}.id)
1343       AND (${ct}.id = ?)
1344       AND (transdate <= (date $todate) $fromwhere )
1345
1346     ORDER BY ctid, transdate, invnumber |;
1347
1348   my $sth_details = prepare_query($form, $dbh, $q_details);
1349
1350   # select outstanding vendors or customers, depends on $ct
1351   my $query =
1352     qq|SELECT DISTINCT ct.id, ct.name
1353        FROM $ct ct, $arap a
1354        $dpt_join
1355        WHERE $where
1356          AND (a.${ct_id} = ct.id)
1357          AND ((a.paid != a.amount) OR ((a.datepaid > $todate) AND (datepaid is NOT NULL)))
1358          AND (a.transdate <= $todate $fromwhere)
1359        ORDER BY ct.name|;
1360
1361   my $sth = prepare_execute_query($form, $dbh, $query);
1362
1363   $form->{AG} = [];
1364   # for each company that has some stuff outstanding
1365   while (my ($id) = $sth->fetchrow_array) {
1366     do_statement($form, $sth_details, $q_details, $id);
1367
1368     while (my $ref = $sth_details->fetchrow_hashref(NAME_lc)) {
1369       $ref->{module} = ($ref->{invoice}) ? $invoice : $arap;
1370       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
1371       push @{ $form->{AG} }, $ref;
1372     }
1373
1374     $sth_details->finish;
1375
1376   }
1377
1378   $sth->finish;
1379
1380   # disconnect
1381   $dbh->disconnect;
1382
1383   $main::lxdebug->leave_sub();
1384 }
1385
1386 sub get_customer {
1387   $main::lxdebug->enter_sub();
1388
1389   my ($self, $myconfig, $form) = @_;
1390
1391   # connect to database
1392   my $dbh = $form->dbconnect($myconfig);
1393
1394   my $ct = $form->{ct} eq "customer" ? "customer" : "vendor";
1395
1396   my $query =
1397     qq|SELECT ct.name, ct.email, ct.cc, ct.bcc
1398        FROM $ct ct
1399        WHERE ct.id = ?|;
1400   ($form->{ $form->{ct} }, $form->{email}, $form->{cc}, $form->{bcc}) =
1401     selectrow_query($form, $dbh, $query, $form->{"${ct}_id"});
1402   $dbh->disconnect;
1403
1404   $main::lxdebug->leave_sub();
1405 }
1406
1407 sub get_taxaccounts {
1408   $main::lxdebug->enter_sub();
1409
1410   my ($self, $myconfig, $form) = @_;
1411
1412   # connect to database
1413   my $dbh = $form->dbconnect($myconfig);
1414
1415   # get tax accounts
1416   my $query =
1417     qq|SELECT c.accno, c.description, t.rate
1418        FROM chart c, tax t
1419        WHERE (c.link LIKE '%CT_tax%') AND (c.id = t.chart_id)
1420        ORDER BY c.accno|;
1421   $form->{taxaccounts} = selectall_hashref_quert($form, $dbh, $query);
1422
1423   $dbh->disconnect;
1424
1425   $main::lxdebug->leave_sub();
1426 }
1427
1428 sub tax_report {
1429   $main::lxdebug->enter_sub();
1430
1431   my ($self, $myconfig, $form) = @_;
1432
1433   # connect to database
1434   my $dbh = $form->dbconnect($myconfig);
1435
1436   my ($null, $department_id) = split /--/, $form->{department};
1437
1438   # build WHERE
1439   my $where = "1 = 1";
1440
1441   if ($department_id) {
1442     $where .= qq| AND (a.department_id = | . conv_i($department_id, 'NULL') . qq|) |;
1443   }
1444
1445   my ($accno, $rate);
1446
1447   if ($form->{accno}) {
1448     $accno = $form->{accno};
1449     $rate  = $form->{"$form->{accno}_rate"};
1450     $accno = qq| AND (ch.accno = | . $dbh->quote($accno) . qq|)|;
1451   }
1452   $rate *= 1;
1453
1454   my ($table, $ARAP);
1455
1456   if ($form->{db} eq 'ar') {
1457     $table = "customer";
1458     $ARAP  = "AR";
1459   } else {
1460     $table = "vendor";
1461     $ARAP  = "AP";
1462   }
1463
1464   my $arap = lc($ARAP);
1465
1466   my $transdate = "a.transdate";
1467
1468   if ($form->{method} eq 'cash') {
1469     $transdate = "a.datepaid";
1470
1471     my $todate = conv_dateq($form->{todate} ? $form->{todate} : $form->current_date($myconfig));
1472
1473     $where .= qq|
1474       AND ac.trans_id IN
1475         (
1476           SELECT trans_id
1477           FROM acc_trans
1478           JOIN chart ON (chart_id = id)
1479           WHERE (link LIKE '%${ARAP}_paid%')
1480           AND (transdate <= $todate)
1481         )
1482       |;
1483   }
1484
1485   # if there are any dates construct a where
1486   $where .= " AND ($transdate >= " . conv_dateq($form->{fromdate}) . ") " if ($form->{fromdate});
1487   $where .= " AND ($transdate <= " . conv_dateq($form->{todate}) . ") " if ($form->{todate});
1488
1489   my $ml = ($form->{db} eq 'ar') ? 1 : -1;
1490
1491   my $sortorder = join ', ', $form->sort_columns(qw(transdate invnumber name));
1492   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(id transdate invnumber name netamount tax)));
1493
1494   if ($form->{report} !~ /nontaxable/) {
1495     $query =
1496       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount,
1497           ac.amount * $ml AS tax
1498          FROM acc_trans ac
1499          JOIN ${arap} a ON (a.id = ac.trans_id)
1500          JOIN chart ch ON (ch.id = ac.chart_id)
1501          JOIN $table n ON (n.id = a.${table}_id)
1502          WHERE
1503            $where
1504            $accno
1505            AND (a.invoice = '0')
1506
1507          UNION
1508
1509          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount,
1510            i.sellprice * i.qty * $rate * $ml AS tax
1511          FROM acc_trans ac
1512          JOIN ${arap} a ON (a.id = ac.trans_id)
1513          JOIN chart ch ON (ch.id = ac.chart_id)
1514          JOIN $table n ON (n.id = a.${table}_id)
1515          JOIN ${table}tax t ON (t.${table}_id = n.id)
1516          JOIN invoice i ON (i.trans_id = a.id)
1517          JOIN partstax p ON (p.parts_id = i.parts_id)
1518          WHERE
1519            $where
1520            $accno
1521            AND (a.invoice = '1')
1522          ORDER BY $sortorder|;
1523   } else {
1524     # only gather up non-taxable transactions
1525     $query =
1526       qq|SELECT a.id, '0' AS invoice, $transdate AS transdate, a.invnumber, n.name, a.netamount
1527          FROM acc_trans ac
1528          JOIN ${arap} a ON (a.id = ac.trans_id)
1529          JOIN $table n ON (n.id = a.${table}_id)
1530          WHERE
1531            $where
1532            AND (a.invoice = '0')
1533            AND (a.netamount = a.amount)
1534
1535          UNION
1536
1537          SELECT a.id, '1' AS invoice, $transdate AS transdate, a.invnumber, n.name, i.sellprice * i.qty AS netamount
1538          FROM acc_trans ac
1539          JOIN ${arap} a ON (a.id = ac.trans_id)
1540          JOIN $table n ON (n.id = a.${table}_id)
1541          JOIN invoice i ON (i.trans_id = a.id)
1542          WHERE
1543            $where
1544            AND (a.invoice = '1')
1545            AND (
1546              a.${table}_id NOT IN (SELECT ${table}_id FROM ${table}tax t (${table}_id))
1547              OR
1548              i.parts_id NOT IN (SELECT parts_id FROM partstax p (parts_id))
1549            )
1550          GROUP BY a.id, a.invnumber, $transdate, n.name, i.sellprice, i.qty
1551          ORDER by $sortorder|;
1552   }
1553
1554   $form->{TR} = selectall_hashref_query($form, $dbh, $query);
1555
1556   $dbh->disconnect;
1557
1558   $main::lxdebug->leave_sub();
1559 }
1560
1561 sub paymentaccounts {
1562   $main::lxdebug->enter_sub();
1563
1564   my ($self, $myconfig, $form) = @_;
1565
1566   # connect to database, turn AutoCommit off
1567   my $dbh = $form->dbconnect_noauto($myconfig);
1568
1569   my $ARAP = $form->{db} eq "ar" ? "AR" : "AP";
1570
1571   # get A(R|P)_paid accounts
1572   my $query =
1573     qq|SELECT accno, description
1574        FROM chart
1575        WHERE link LIKE '%${ARAP}_paid%'|;
1576   $form->{PR} = selectall_hashref_query($form, $dbh, $query);
1577
1578   $dbh->disconnect;
1579
1580   $main::lxdebug->leave_sub();
1581 }
1582
1583 sub payments {
1584   $main::lxdebug->enter_sub();
1585
1586   my ($self, $myconfig, $form) = @_;
1587
1588   # connect to database, turn AutoCommit off
1589   my $dbh = $form->dbconnect_noauto($myconfig);
1590
1591   my $ml = 1;
1592   my $arap;
1593   if ($form->{db} eq 'ar') {
1594     $table = 'customer';
1595     $ml = -1;
1596     $arap = 'ar';
1597   } else {
1598     $table = 'vendor';
1599     $arap = 'ap';
1600   }
1601
1602   my ($query, $sth);
1603   my $dpt_join;
1604   my $where;
1605
1606   if ($form->{department_id}) {
1607     $dpt_join = qq| JOIN dpt_trans t ON (t.trans_id = ac.trans_id) |;
1608     $where = qq| AND (t.department_id = | . conv_i($form->{department_id}, 'NULL') . qq|) |;
1609   }
1610
1611   if ($form->{fromdate}) {
1612     $where .= " AND (ac.transdate >= " . $dbh->quote($form->{fromdate}) . ") ";
1613   }
1614   if ($form->{todate}) {
1615     $where .= " AND (ac.transdate <= " . $dbh->quote($form->{todate}) . ") ";
1616   }
1617   if (!$form->{fx_transaction}) {
1618     $where .= " AND ac.fx_transaction = '0'";
1619   }
1620
1621   my $invnumber;
1622   my $reference;
1623   if ($form->{reference}) {
1624     $reference = $dbh->quote('%' . $form->{reference} . '%');
1625     $invnumber = " AND (a.invnumber LIKE $reference)";
1626     $reference = " AND (g.reference LIKE $reference)";
1627   }
1628   if ($form->{source}) {
1629     $where .= " AND (ac.source ILIKE " . $dbh->quote('%' . $form->{source} . '%') . ") ";
1630   }
1631   if ($form->{memo}) {
1632     $where .= " AND (ac.memo ILIKE " . $dbh->quote('%' . $form->{memo} . '%') . ") ";
1633   }
1634
1635   my $sortorder = join(', ', qw(name invnumber ordnumber transdate source));
1636   $sortorder = $form->{sort} if ($form->{sort} && grep({ $_ eq $form->{sort} } qw(transdate invnumber name source memo)));
1637
1638   $query = qq|SELECT id, accno, description FROM chart WHERE accno = ?|;
1639   my $sth = prepare_query($form, $dbh, $query);
1640
1641   my $q_details =
1642       qq|SELECT c.name, a.invnumber, a.ordnumber,
1643            ac.transdate, ac.amount * $ml AS paid, ac.source,
1644            a.invoice, a.id, ac.memo, '${arap}' AS module
1645          FROM acc_trans ac
1646          JOIN $arap a ON (ac.trans_id = a.id)
1647          JOIN $table c ON (c.id = a.${table}_id)
1648          $dpt_join
1649          WHERE (ac.chart_id = ?)
1650            $where
1651            $invnumber
1652
1653          UNION
1654
1655          SELECT g.description, g.reference, NULL AS ordnumber,
1656            ac.transdate, ac.amount * $ml AS paid, ac.source,
1657            '0' as invoice, g.id, ac.memo, 'gl' AS module
1658          FROM acc_trans ac
1659          JOIN gl g ON (g.id = ac.trans_id)
1660          $dpt_join
1661          WHERE (ac.chart_id = ?)
1662            $where
1663            $reference
1664            AND (ac.amount * $ml) > 0
1665
1666          ORDER BY $sortorder|;
1667   my $sth_details = prepare_query($form, $dbh, $q_details);
1668
1669   $form->{PR} = [];
1670
1671   # cycle through each id
1672   foreach my $accno (split(/ /, $form->{paymentaccounts})) {
1673     do_statement($form, $sth, $query, $accno);
1674     my $ref = $sth->fetchrow_hashref();
1675     push(@{ $form->{PR} }, $ref);
1676     $sth->finish();
1677
1678     $form->{ $ref->{id} } = [] unless ($form->{ $ref->{id} });
1679
1680     do_statement($form, $sth_details, $q_details, $ref->{id}, $ref->{id});
1681     while (my $pr = $sth_details->fetchrow_hashref()) {
1682       push(@{ $form->{ $ref->{id} } }, $pr);
1683     }
1684     $sth_details->finish();
1685   }
1686
1687   $dbh->disconnect;
1688
1689   $main::lxdebug->leave_sub();
1690 }
1691
1692 sub bwa {
1693   $main::lxdebug->enter_sub();
1694
1695   my ($self, $myconfig, $form) = @_;
1696
1697   # connect to database
1698   my $dbh = $form->dbconnect($myconfig);
1699
1700   my $last_period = 0;
1701   my $category;
1702   my @categories  =
1703     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);
1704
1705   $form->{decimalplaces} *= 1;
1706
1707   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_bwa");
1708
1709   # if there are any compare dates
1710   if ($form->{fromdate} || $form->{todate}) {
1711     $last_period = 1;
1712     if ($form->{fromdate}) {
1713       $form->{fromdate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
1714       $year = $1;
1715     } else {
1716       $form->{todate} =~ /[0-9]*\.[0-9]*\.([0-9]*)/;
1717       $year = $1;
1718     }
1719     $kummfromdate = $form->{comparefromdate};
1720     $kummtodate   = $form->{comparetodate};
1721     &get_accounts_g($dbh, $last_period, $kummfromdate, $kummtodate, $form, "pos_bwa");
1722   }
1723
1724   @periods        = qw(jetzt kumm);
1725   @gesamtleistung = qw(1 2 3);
1726   @gesamtkosten   = qw (10 11 12 13 14 15 16 17 18 19 20);
1727   @ergebnisse     =
1728     qw (rohertrag betriebrohertrag betriebsergebnis neutraleraufwand neutralerertrag ergebnisvorsteuern ergebnis gesamtleistung gesamtkosten);
1729
1730   foreach $key (@periods) {
1731     $form->{ "$key" . "gesamtleistung" } = 0;
1732     $form->{ "$key" . "gesamtkosten" }   = 0;
1733
1734     foreach $category (@categories) {
1735
1736       if (defined($form->{$category}{$key})) {
1737         $form->{"$key$category"} =
1738           $form->format_amount($myconfig,
1739                                $form->round_amount($form->{$category}{$key}, 2
1740                                ),
1741                                $form->{decimalplaces},
1742                                '0');
1743       }
1744     }
1745     foreach $item (@gesamtleistung) {
1746       $form->{ "$key" . "gesamtleistung" } += $form->{$item}{$key};
1747     }
1748     foreach $item (@gesamtkosten) {
1749       $form->{ "$key" . "gesamtkosten" } += $form->{$item}{$key};
1750     }
1751     $form->{ "$key" . "rohertrag" } =
1752       $form->{ "$key" . "gesamtleistung" } - $form->{4}{$key};
1753     $form->{ "$key" . "betriebrohertrag" } =
1754       $form->{ "$key" . "rohertrag" } + $form->{5}{$key};
1755     $form->{ "$key" . "betriebsergebnis" } =
1756       $form->{ "$key" . "betriebrohertrag" } -
1757       $form->{ "$key" . "gesamtkosten" };
1758     $form->{ "$key" . "neutraleraufwand" } =
1759       $form->{30}{$key} + $form->{31}{$key};
1760     $form->{ "$key" . "neutralertrag" } =
1761       $form->{32}{$key} + $form->{33}{$key} + $form->{34}{$key};
1762     $form->{ "$key" . "ergebnisvorsteuern" } =
1763       $form->{ "$key" . "betriebsergebnis" } -
1764       $form->{ "$key" . "neutraleraufwand" } +
1765       $form->{ "$key" . "neutralertrag" };
1766     $form->{ "$key" . "ergebnis" } =
1767       $form->{ "$key" . "ergebnisvorsteuern" } - $form->{35}{$key};
1768
1769     if ($form->{ "$key" . "gesamtleistung" } > 0) {
1770       foreach $category (@categories) {
1771         if (defined($form->{$category}{$key})) {
1772           $form->{ "$key" . "gl" . "$category" } =
1773             $form->format_amount(
1774                                $myconfig,
1775                                $form->round_amount(
1776                                  ($form->{$category}{$key} /
1777                                     $form->{ "$key" . "gesamtleistung" } * 100
1778                                  ),
1779                                  $form->{decimalplaces}
1780                                ),
1781                                $form->{decimalplaces},
1782                                '0');
1783         }
1784       }
1785       foreach $item (@ergebnisse) {
1786         $form->{ "$key" . "gl" . "$item" } =
1787           $form->format_amount($myconfig,
1788                                $form->round_amount(
1789                                  ( $form->{ "$key" . "$item" } /
1790                                      $form->{ "$key" . "gesamtleistung" } * 100
1791                                  ),
1792                                  $form->{decimalplaces}
1793                                ),
1794                                $form->{decimalplaces},
1795                                '0');
1796       }
1797     }
1798
1799     if ($form->{ "$key" . "gesamtkosten" } > 0) {
1800       foreach $category (@categories) {
1801         if (defined($form->{$category}{$key})) {
1802           $form->{ "$key" . "gk" . "$category" } =
1803             $form->format_amount($myconfig,
1804                                  $form->round_amount(
1805                                    ($form->{$category}{$key} /
1806                                       $form->{ "$key" . "gesamtkosten" } * 100
1807                                    ),
1808                                    $form->{decimalplaces}
1809                                  ),
1810                                  $form->{decimalplaces},
1811                                  '0');
1812         }
1813       }
1814       foreach $item (@ergebnisse) {
1815         $form->{ "$key" . "gk" . "$item" } =
1816           $form->format_amount($myconfig,
1817                                $form->round_amount(
1818                                    ($form->{ "$key" . "$item" } /
1819                                       $form->{ "$key" . "gesamtkosten" } * 100
1820                                    ),
1821                                    $form->{decimalplaces}
1822                                ),
1823                                $form->{decimalplaces},
1824                                '0');
1825       }
1826     }
1827
1828     if ($form->{10}{$key} > 0) {
1829       foreach $category (@categories) {
1830         if (defined($form->{$category}{$key})) {
1831           $form->{ "$key" . "pk" . "$category" } =
1832             $form->format_amount(
1833                         $myconfig,
1834                         $form->round_amount(
1835                           ($form->{$category}{$key} / $form->{10}{$key} * 100),
1836                           $form->{decimalplaces}
1837                         ),
1838                         $form->{decimalplaces},
1839                         '0');
1840         }
1841       }
1842       foreach $item (@ergebnisse) {
1843         $form->{ "$key" . "pk" . "$item" } =
1844           $form->format_amount($myconfig,
1845                                $form->round_amount(
1846                                                 ($form->{ "$key" . "$item" } /
1847                                                    $form->{10}{$key} * 100
1848                                                 ),
1849                                                 $form->{decimalplaces}
1850                                ),
1851                                $form->{decimalplaces},
1852                                '0');
1853       }
1854     }
1855
1856     if ($form->{4}{$key} > 0) {
1857       foreach $category (@categories) {
1858         if (defined($form->{$category}{$key})) {
1859           $form->{ "$key" . "auf" . "$category" } =
1860             $form->format_amount(
1861                          $myconfig,
1862                          $form->round_amount(
1863                            ($form->{$category}{$key} / $form->{4}{$key} * 100),
1864                            $form->{decimalplaces}
1865                          ),
1866                          $form->{decimalplaces},
1867                          '0');
1868         }
1869       }
1870       foreach $item (@ergebnisse) {
1871         $form->{ "$key" . "auf" . "$item" } =
1872           $form->format_amount($myconfig,
1873                                $form->round_amount(
1874                                                 ($form->{ "$key" . "$item" } /
1875                                                    $form->{4}{$key} * 100
1876                                                 ),
1877                                                 $form->{decimalplaces}
1878                                ),
1879                                $form->{decimalplaces},
1880                                '0');
1881       }
1882     }
1883
1884     foreach $item (@ergebnisse) {
1885       $form->{ "$key" . "$item" } =
1886         $form->format_amount($myconfig,
1887                              $form->round_amount($form->{ "$key" . "$item" },
1888                                                  $form->{decimalplaces}
1889                              ),
1890                              $form->{decimalplaces},
1891                              '0');
1892     }
1893
1894   }
1895   $dbh->disconnect;
1896
1897   $main::lxdebug->leave_sub();
1898 }
1899
1900 sub ustva {
1901   $main::lxdebug->enter_sub();
1902
1903   my ($self, $myconfig, $form) = @_;
1904
1905   # connect to database
1906   my $dbh = $form->dbconnect($myconfig);
1907
1908   my $last_period     = 0;
1909   my @categories_cent = qw(51r 511 86r 861 97r 971 93r 931
1910     96 66 43 45 53 62 65 67);
1911   my @categories_euro = qw(48 51 86 91 97 93 94);
1912   $form->{decimalplaces} *= 1;
1913
1914   foreach $item (@categories_cent) {
1915     $form->{"$item"} = 0;
1916   }
1917   foreach $item (@categories_euro) {
1918     $form->{"$item"} = 0;
1919   }
1920
1921   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate}, $form, "pos_ustva");
1922
1923   #   foreach $item (@categories_cent) {
1924   #     if ($form->{$item}{"jetzt"} > 0) {
1925   #             $form->{$item} = $form->{$item}{"jetzt"};
1926   #             delete $form->{$item}{"jetzt"};
1927   #     }
1928   #   }
1929   #   foreach $item (@categories_euro) {
1930   #     if ($form->{$item}{"jetzt"} > 0) {
1931   #             $form->{$item} = $form->{$item}{"jetzt"};
1932   #             delete $form->{$item}{"jetzt"};
1933   #     }  foreach $item (@categories_cent) {
1934   #     if ($form->{$item}{"jetzt"} > 0) {
1935   #             $form->{$item} = $form->{$item}{"jetzt"};
1936   #             delete $form->{$item}{"jetzt"};
1937   #     }
1938   #   }
1939   #   foreach $item (@categories_euro) {
1940   #     if ($form->{$item}{"jetzt"} > 0) {
1941   #             $form->{$item} = $form->{$item}{"jetzt"};
1942   #             delete $form->{$item}{"jetzt"};
1943   #     }
1944   #   }
1945   #
1946   #    }
1947
1948   #
1949   # Berechnung der USTVA Formularfelder
1950   #
1951   $form->{"51r"} = $form->{"511"};
1952   $form->{"86r"} = $form->{"861"};
1953   $form->{"97r"} = $form->{"971"};
1954   $form->{"93r"} = $form->{"931"};
1955
1956   #$form->{"96"}  = $form->{"94"} * 0.16;
1957   $form->{"43"} =
1958     $form->{"51r"} + $form->{"86r"} + $form->{"97r"} + $form->{"93r"} +
1959     $form->{"96"};
1960   $form->{"45"} = $form->{"43"};
1961   $form->{"53"} = $form->{"43"};
1962   $form->{"62"} = $form->{"43"} - $form->{"66"};
1963   $form->{"65"} = $form->{"43"} - $form->{"66"};
1964   $form->{"67"} = $form->{"43"} - $form->{"66"};
1965
1966   foreach $item (@categories_cent) {
1967     $form->{$item} =
1968       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2),
1969                            2, '0');
1970   }
1971
1972   foreach $item (@categories_euro) {
1973     $form->{$item} =
1974       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 0),
1975                            0, '0');
1976   }
1977
1978   $dbh->disconnect;
1979
1980   $main::lxdebug->leave_sub();
1981 }
1982
1983 sub income_statement {
1984   $main::lxdebug->enter_sub();
1985
1986   my ($self, $myconfig, $form) = @_;
1987
1988   # connect to database
1989   my $dbh = $form->dbconnect($myconfig);
1990
1991   my $last_period          = 0;
1992   my @categories_einnahmen = qw(1 2 3 4 5 6 7);
1993   my @categories_ausgaben  =
1994     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);
1995
1996   my @ergebnisse = qw(sumeura sumeurb guvsumme);
1997
1998   $form->{decimalplaces} *= 1;
1999
2000   foreach $item (@categories_einnahmen) {
2001     $form->{$item} = 0;
2002   }
2003   foreach $item (@categories_ausgaben) {
2004     $form->{$item} = 0;
2005   }
2006
2007   foreach $item (@ergebnisse) {
2008     $form->{$item} = 0;
2009   }
2010
2011   &get_accounts_g($dbh, $last_period, $form->{fromdate}, $form->{todate},
2012                   $form, "pos_eur");
2013
2014   foreach $item (@categories_einnahmen) {
2015     $form->{"eur${item}"} =
2016       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2017     $form->{"sumeura"} += $form->{$item};
2018   }
2019   foreach $item (@categories_ausgaben) {
2020     $form->{"eur${item}"} =
2021       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2022     $form->{"sumeurb"} += $form->{$item};
2023   }
2024
2025   $form->{"guvsumme"} = $form->{"sumeura"} - $form->{"sumeurb"};
2026
2027   foreach $item (@ergebnisse) {
2028     $form->{$item} =
2029       $form->format_amount($myconfig, $form->round_amount($form->{$item}, 2));
2030   }
2031   $main::lxdebug->leave_sub();
2032 }
2033 1;