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