Merge branch 'master' of vc.linet-services.de:public/lx-office-erp
[kivitendo-erp.git] / bin / mozilla / rp.pl
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: Antonio Gallardo <agssa@ibw.com.ni>
16 #                Benjamin Lee <benjaminlee@consultant.com>
17 #                Philip Reetz <p.reetz@linet-services.de>
18 #                Udo Spallek
19 #
20 # This program is free software; you can redistribute it and/or modify
21 # it under the terms of the GNU General Public License as published by
22 # the Free Software Foundation; either version 2 of the License, or
23 # (at your option) any later version.
24 #
25 # This program is distributed in the hope that it will be useful,
26 # but WITHOUT ANY WARRANTY; without even the implied warranty of
27 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28 # GNU General Public License for more details.
29 # You should have received a copy of the GNU General Public License
30 # along with this program; if not, write to the Free Software
31 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 #======================================================================
33 #
34 # module for preparing Income Statement and Balance Sheet
35 #
36 #======================================================================
37
38 use POSIX qw(strftime);
39
40 use SL::PE;
41 use SL::RP;
42 use SL::Iconv;
43 use SL::ReportGenerator;
44 use Data::Dumper;
45
46 require "bin/mozilla/arap.pl";
47 require "bin/mozilla/common.pl";
48 require "bin/mozilla/reportgenerator.pl";
49
50 # note: this file was particularly hard to strictify.
51 # alot of the vars are passed carelessly between invocations
52 # should there be any missing vars, declare them globally
53 use strict;
54
55 # this is for our long dates
56 # $locale->text('January')
57 # $locale->text('February')
58 # $locale->text('March')
59 # $locale->text('April')
60 # $locale->text('May ')
61 # $locale->text('June')
62 # $locale->text('July')
63 # $locale->text('August')
64 # $locale->text('September')
65 # $locale->text('October')
66 # $locale->text('November')
67 # $locale->text('December')
68
69 # this is for our short month
70 # $locale->text('Jan')
71 # $locale->text('Feb')
72 # $locale->text('Mar')
73 # $locale->text('Apr')
74 # $locale->text('May')
75 # $locale->text('Jun')
76 # $locale->text('Jul')
77 # $locale->text('Aug')
78 # $locale->text('Sep')
79 # $locale->text('Oct')
80 # $locale->text('Nov')
81 # $locale->text('Dec')
82
83 # $locale->text('Balance Sheet')
84 # $locale->text('Income Statement')
85 # $locale->text('Trial Balance')
86 # $locale->text('AR Aging')
87 # $locale->text('AP Aging')
88 # $locale->text('Search AR Aging')
89 # $locale->text('Search AP Aging')
90 # $locale->text('Tax collected')
91 # $locale->text('Tax paid')
92 # $locale->text('Receipts')
93 # $locale->text('Payments')
94 # $locale->text('Project Transactions')
95 # $locale->text('Non-taxable Sales')
96 # $locale->text('Non-taxable Purchases')
97 # $locale->text('Business evaluation')
98
99 # $form->parse_html_template('rp/html_report_susa')
100
101 my $rp_access_map = {
102   'projects'         => 'report',
103   'ar_aging'         => 'general_ledger',
104   'ap_aging'         => 'general_ledger',
105   'receipts'         => 'cash',
106   'payments'         => 'cash',
107   'trial_balance'    => 'report',
108   'income_statement' => 'report',
109   'bwa'              => 'report',
110   'balance_sheet'    => 'report',
111 };
112
113 sub check_rp_access {
114   my $form     = $main::form;
115
116   my $right   = $rp_access_map->{$form->{report}};
117   $right    ||= 'DOES_NOT_EXIST';
118
119   $main::auth->assert($right);
120 }
121
122 sub report {
123   $::lxdebug->enter_sub;
124
125   check_rp_access();
126
127   my %title = (
128     balance_sheet        => $::locale->text('Balance Sheet'),
129     income_statement     => $::locale->text('Income Statement'),
130     trial_balance        => $::locale->text('Trial Balance'),
131     ar_aging             => $::locale->text('Search AR Aging'),
132     ap_aging             => $::locale->text('Search AP Aging'),
133     tax_collected        => $::locale->text('Tax collected'),
134     tax_paid             => $::locale->text('Tax paid'),
135     nontaxable_sales     => $::locale->text('Non-taxable Sales'),
136     nontaxable_purchases => $::locale->text('Non-taxable Purchases'),
137     receipts             => $::locale->text('Receipts'),
138     payments             => $::locale->text('Payments'),
139     projects             => $::locale->text('Project Transactions'),
140     bwa                  => $::locale->text('Business evaluation'),
141   );
142
143   $::form->{title} = $title{$::form->{report}};
144
145   # get departments
146   $::form->all_departments(\%::myconfig);
147   if (@{ $::form->{all_departments} || [] }) {
148     $::form->{selectdepartment} = "<option>\n";
149     map { $::form->{selectdepartment} .= "<option>$_->{description}--$_->{id}\n" } @{ $::form->{all_departments} || [] };
150   }
151
152   $::form->get_lists("projects" => { "key" => "ALL_PROJECTS", "all" => 1 });
153
154   my $onload = qq|focus()|;
155
156   my $is_projects         = $::form->{report} eq "projects";
157   my $is_income_statement = $::form->{report} eq "income_statement";
158   my $is_bwa              = $::form->{report} eq "bwa";
159   my $is_balance_sheet    = $::form->{report} eq "balance_sheet";
160   my $is_trial_balance    = $::form->{report} eq "trial_balance";
161   my $is_aging            = $::form->{report} =~ /^a[rp]_aging$/;
162   my $is_payments         = $::form->{report} =~ /(receipts|payments)$/;
163
164   my ($label, $nextsub, $vc);
165   if ($is_aging) {
166     my $is_sales  = $::form->{report} eq 'ar_aging';
167     $label        = $is_sales ? $::locale->text('Customer') : $::locale->text('Vendor');
168     $::form->{vc} = $is_sales ? 'customer' : 'vendor';
169
170     $nextsub = "generate_$::form->{report}";
171
172     # setup vc selection
173     $::form->all_vc(\%::myconfig, $::form->{vc}, $is_sales ? "AR" : "AP");
174     $vc .= "<option>$_->{name}--$_->{id}\n" for @{ $::form->{"all_$::form->{vc}"} };
175     $vc = ($vc)
176         ? qq|<select name=$::form->{vc}><option>\n$vc</select>|
177         : qq|<input name=$::form->{vc} size=35>|;
178   }
179
180   my ($selection, $paymentaccounts);
181   if ($is_payments) {
182     $::form->{db} = $::form->{report} =~ /payments$/ ? "ap" : "ar";
183
184     RP->paymentaccounts(\%::myconfig, $::form);
185
186     $selection = "<option>\n";
187     for my $ref (@{ $::form->{PR} }) {
188       $paymentaccounts .= "$ref->{accno} ";
189       $selection       .= "<option>$ref->{accno}--$ref->{description}\n";
190     }
191   }
192
193   $::form->header;
194   print $::form->parse_html_template('rp/report', {
195     paymentaccounts     => $paymentaccounts,
196     selection           => $selection,
197     is_aging            => $is_aging,
198     vc                  => $vc,
199     label               => $label,
200     year                => DateTime->today->year,
201     onload              => $onload,
202     nextsub             => $nextsub,
203     accrual             => $::instance_conf->get_accounting_method ne 'cash',
204     cash                => $::instance_conf->get_accounting_method eq 'cash',
205     is_payments         => $is_payments,
206     is_trial_balance    => $is_trial_balance,
207     is_balance_sheet    => $is_balance_sheet,
208     is_bwa              => $is_bwa,
209     is_income_statement => $is_income_statement,
210     is_projects         => $is_projects,
211   });
212
213   $::lxdebug->leave_sub;
214 }
215
216 sub continue { call_sub($main::form->{"nextsub"}); }
217
218 sub get_project {
219   $main::lxdebug->enter_sub();
220
221   $main::auth->assert('report');
222
223   my $form     = $main::form;
224   my %myconfig = %main::myconfig;
225   my $locale   = $main::locale;
226
227   my $nextsub = shift;
228
229   $form->{project_id} = $form->{project_id_1};
230   if ($form->{projectnumber} && !$form->{project_id}) {
231     $form->{rowcount} = 1;
232
233     # call this instead of update
234     $form->{update}          = $nextsub;
235     $form->{projectnumber_1} = $form->{projectnumber};
236
237     delete $form->{sort};
238     check_project('generate_projects');
239
240     # if there is one only, assign id
241     $form->{project_id} = $form->{project_id_1};
242   }
243
244   $main::lxdebug->leave_sub();
245 }
246
247 sub generate_income_statement {
248   $main::lxdebug->enter_sub();
249
250   $main::auth->assert('report');
251
252   my $form     = $main::form;
253   my %myconfig = %main::myconfig;
254   my $locale   = $main::locale;
255
256   $form->{padding} = "&nbsp;&nbsp;";
257   $form->{bold}    = "<b>";
258   $form->{endbold} = "</b>";
259   $form->{br}      = "<br>";
260
261   if ($form->{reporttype} eq "custom") {
262
263     #forgotten the year --> thisyear
264     if ($form->{year} !~ m/^\d\d\d\d$/) {
265       $locale->date(\%myconfig, $form->current_date(\%myconfig), 0) =~
266         /(\d\d\d\d)/;
267       $form->{year} = $1;
268     }
269
270     #yearly report
271     if ($form->{duetyp} eq "13") {
272       $form->{fromdate} = "1.1.$form->{year}";
273       $form->{todate}   = "31.12.$form->{year}";
274     }
275
276     #Quater reports
277     if ($form->{duetyp} eq "A") {
278       $form->{fromdate} = "1.1.$form->{year}";
279       $form->{todate}   = "31.3.$form->{year}";
280     }
281     if ($form->{duetyp} eq "B") {
282       $form->{fromdate} = "1.4.$form->{year}";
283       $form->{todate}   = "30.6.$form->{year}";
284     }
285     if ($form->{duetyp} eq "C") {
286       $form->{fromdate} = "1.7.$form->{year}";
287       $form->{todate}   = "30.9.$form->{year}";
288     }
289     if ($form->{duetyp} eq "D") {
290       $form->{fromdate} = "1.10.$form->{year}";
291       $form->{todate}   = "31.12.$form->{year}";
292     }
293
294     #Monthly reports
295   SWITCH: {
296       $form->{duetyp} eq "1" && do {
297         $form->{fromdate} = "1.1.$form->{year}";
298         $form->{todate}   = "31.1.$form->{year}";
299         last SWITCH;
300       };
301       $form->{duetyp} eq "2" && do {
302         $form->{fromdate} = "1.2.$form->{year}";
303
304         #this works from 1901 to 2099, 1900 and 2100 fail.
305         my $leap = ($form->{year} % 4 == 0) ? "29" : "28";
306         $form->{todate} = "$leap.2.$form->{year}";
307         last SWITCH;
308       };
309       $form->{duetyp} eq "3" && do {
310         $form->{fromdate} = "1.3.$form->{year}";
311         $form->{todate}   = "31.3.$form->{year}";
312         last SWITCH;
313       };
314       $form->{duetyp} eq "4" && do {
315         $form->{fromdate} = "1.4.$form->{year}";
316         $form->{todate}   = "30.4.$form->{year}";
317         last SWITCH;
318       };
319       $form->{duetyp} eq "5" && do {
320         $form->{fromdate} = "1.5.$form->{year}";
321         $form->{todate}   = "31.5.$form->{year}";
322         last SWITCH;
323       };
324       $form->{duetyp} eq "6" && do {
325         $form->{fromdate} = "1.6.$form->{year}";
326         $form->{todate}   = "30.6.$form->{year}";
327         last SWITCH;
328       };
329       $form->{duetyp} eq "7" && do {
330         $form->{fromdate} = "1.7.$form->{year}";
331         $form->{todate}   = "31.7.$form->{year}";
332         last SWITCH;
333       };
334       $form->{duetyp} eq "8" && do {
335         $form->{fromdate} = "1.8.$form->{year}";
336         $form->{todate}   = "31.8.$form->{year}";
337         last SWITCH;
338       };
339       $form->{duetyp} eq "9" && do {
340         $form->{fromdate} = "1.9.$form->{year}";
341         $form->{todate}   = "30.9.$form->{year}";
342         last SWITCH;
343       };
344       $form->{duetyp} eq "10" && do {
345         $form->{fromdate} = "1.10.$form->{year}";
346         $form->{todate}   = "31.10.$form->{year}";
347         last SWITCH;
348       };
349       $form->{duetyp} eq "11" && do {
350         $form->{fromdate} = "1.11.$form->{year}";
351         $form->{todate}   = "30.11.$form->{year}";
352         last SWITCH;
353       };
354       $form->{duetyp} eq "12" && do {
355         $form->{fromdate} = "1.12.$form->{year}";
356         $form->{todate}   = "31.12.$form->{year}";
357         last SWITCH;
358       };
359     }
360     hotfix_reformat_date();
361   } # Ende Bericht für vorgewählten Zeitraum (warum auch immer die Prüfung (custom eq true) ist ...
362
363   RP->income_statement(\%myconfig, \%$form);
364
365   ($form->{department}) = split /--/, $form->{department};
366
367   $form->{period} =
368     $locale->date(\%myconfig, $form->current_date(\%myconfig), 1);
369   $form->{todate} = $form->current_date(\%myconfig) unless $form->{todate};
370
371   # if there are any dates construct a where
372   if ($form->{fromdate} || $form->{todate}) {
373
374     unless ($form->{todate}) {
375       $form->{todate} = $form->current_date(\%myconfig);
376     }
377
378     my $longtodate  = $locale->date(\%myconfig, $form->{todate}, 1);
379     my $shorttodate = $locale->date(\%myconfig, $form->{todate}, 0);
380
381     my $longfromdate  = $locale->date(\%myconfig, $form->{fromdate}, 1);
382     my $shortfromdate = $locale->date(\%myconfig, $form->{fromdate}, 0);
383
384     $form->{this_period} = "$shortfromdate\n$shorttodate";
385     $form->{period}      =
386         $locale->text('for Period')
387       . qq|\n$longfromdate |
388       . $locale->text('Bis')
389       . qq| $longtodate|;
390   }
391
392   if ($form->{comparefromdate} || $form->{comparetodate}) {
393     my $longcomparefromdate = $locale->date(\%myconfig, $form->{comparefromdate}, 1);
394     my $shortcomparefromdate = $locale->date(\%myconfig, $form->{comparefromdate}, 0);
395
396     my $longcomparetodate  = $locale->date(\%myconfig, $form->{comparetodate}, 1);
397     my $shortcomparetodate = $locale->date(\%myconfig, $form->{comparetodate}, 0);
398
399     $form->{last_period} = "$shortcomparefromdate\n$shortcomparetodate";
400     $form->{period} .=
401         "\n$longcomparefromdate "
402       . $locale->text('Bis')
403       . qq| $longcomparetodate|;
404   }
405
406   # setup variables for the form
407   my @a = qw(company address businessnumber);
408   map { $form->{$_} = $myconfig{$_} } @a;
409
410   $form->{templates} = $myconfig{templates};
411
412   $form->{IN} = "income_statement.html";
413
414   $form->parse_template;
415
416   $main::lxdebug->leave_sub();
417 }
418
419 sub generate_balance_sheet {
420   $::lxdebug->enter_sub;
421   $::auth->assert('report');
422
423   $::form->{decimalplaces} = $::form->{decimalplaces} * 1 || 2;
424   $::form->{padding}       = "&nbsp;&nbsp;";
425   $::form->{bold}          = "<b>";
426   $::form->{endbold}       = "</b>";
427   $::form->{br}            = "<br>";
428
429   my $data = RP->balance_sheet(\%::myconfig, $::form);
430
431   $::form->{asofdate} ||= $::form->current_date;
432   $::form->{period}     = $::locale->date(\%::myconfig, $::form->current_date, 1);
433
434   ($::form->{department}) = split /--/, $::form->{department};
435
436   # define Current Earnings account
437   my $padding = $::form->{l_heading} ? $::form->{padding} : "";
438   push @{ $::form->{equity_account} }, $padding . $::locale->text('Current Earnings');
439
440   $::form->{this_period} = $::locale->date(\%::myconfig, $::form->{asofdate}, 0);
441   $::form->{last_period} = $::locale->date(\%::myconfig, $::form->{compareasofdate}, 0);
442
443 #  $::form->{IN} = "balance_sheet.html";
444
445   # setup company variables for the form
446   map { $::form->{$_} = $::myconfig{$_} } qw(company address businessnumber nativecurr);
447
448   $::form->{templates} = $::myconfig{templates};
449
450   $::form->header;
451   print $::form->parse_html_template('rp/balance_sheet', $data);
452
453   $::lxdebug->leave_sub;
454 }
455
456 sub generate_projects {
457   $main::lxdebug->enter_sub();
458
459   $main::auth->assert('report');
460
461   my $form     = $main::form;
462   my %myconfig = %main::myconfig;
463   my $locale   = $main::locale;
464
465   &get_project("generate_projects");
466   $form->{projectnumber} = $form->{projectnumber_1};
467
468   $form->{nextsub} = "generate_projects";
469   $form->{title}   = $locale->text('Project Transactions');
470   RP->trial_balance(\%myconfig, \%$form);
471
472   list_accounts('generate_projects');
473
474   $main::lxdebug->leave_sub();
475 }
476
477 # Antonio Gallardo
478 #
479 # D.S. Feb 16, 2001
480 # included links to display transactions for period entered
481 # added headers and subtotals
482 #
483 sub generate_trial_balance {
484   $main::lxdebug->enter_sub();
485
486   $main::auth->assert('report');
487
488   my $form     = $main::form;
489   my %myconfig = %main::myconfig;
490   my $locale   = $main::locale;
491
492   if ($form->{reporttype} eq "custom") {
493
494     #forgotten the year --> thisyear
495     if ($form->{year} !~ m/^\d\d\d\d$/) {
496       $locale->date(\%myconfig, $form->current_date(\%myconfig), 0) =~
497         /(\d\d\d\d)/;
498       $form->{year} = $1;
499     }
500
501     #yearly report
502     if ($form->{duetyp} eq "13") {
503       $form->{fromdate} = "1.1.$form->{year}";
504       $form->{todate}   = "31.12.$form->{year}";
505     }
506
507     #Quater reports
508     if ($form->{duetyp} eq "A") {
509       $form->{fromdate} = "1.1.$form->{year}";
510       $form->{todate}   = "31.3.$form->{year}";
511     }
512     if ($form->{duetyp} eq "B") {
513       $form->{fromdate} = "1.4.$form->{year}";
514       $form->{todate}   = "30.6.$form->{year}";
515     }
516     if ($form->{duetyp} eq "C") {
517       $form->{fromdate} = "1.7.$form->{year}";
518       $form->{todate}   = "30.9.$form->{year}";
519     }
520     if ($form->{duetyp} eq "D") {
521       $form->{fromdate} = "1.10.$form->{year}";
522       $form->{todate}   = "31.12.$form->{year}";
523     }
524
525     #Monthly reports
526   SWITCH: {
527       $form->{duetyp} eq "1" && do {
528         $form->{fromdate} = "1.1.$form->{year}";
529         $form->{todate}   = "31.1.$form->{year}";
530         last SWITCH;
531       };
532       $form->{duetyp} eq "2" && do {
533         $form->{fromdate} = "1.2.$form->{year}";
534
535         #this works from 1901 to 2099, 1900 and 2100 fail.
536         my $leap = ($form->{year} % 4 == 0) ? "29" : "28";
537         $form->{todate} = "$leap.2.$form->{year}";
538         last SWITCH;
539       };
540       $form->{duetyp} eq "3" && do {
541         $form->{fromdate} = "1.3.$form->{year}";
542         $form->{todate}   = "31.3.$form->{year}";
543         last SWITCH;
544       };
545       $form->{duetyp} eq "4" && do {
546         $form->{fromdate} = "1.4.$form->{year}";
547         $form->{todate}   = "30.4.$form->{year}";
548         last SWITCH;
549       };
550       $form->{duetyp} eq "5" && do {
551         $form->{fromdate} = "1.5.$form->{year}";
552         $form->{todate}   = "31.5.$form->{year}";
553         last SWITCH;
554       };
555       $form->{duetyp} eq "6" && do {
556         $form->{fromdate} = "1.6.$form->{year}";
557         $form->{todate}   = "30.6.$form->{year}";
558         last SWITCH;
559       };
560       $form->{duetyp} eq "7" && do {
561         $form->{fromdate} = "1.7.$form->{year}";
562         $form->{todate}   = "31.7.$form->{year}";
563         last SWITCH;
564       };
565       $form->{duetyp} eq "8" && do {
566         $form->{fromdate} = "1.8.$form->{year}";
567         $form->{todate}   = "31.8.$form->{year}";
568         last SWITCH;
569       };
570       $form->{duetyp} eq "9" && do {
571         $form->{fromdate} = "1.9.$form->{year}";
572         $form->{todate}   = "30.9.$form->{year}";
573         last SWITCH;
574       };
575       $form->{duetyp} eq "10" && do {
576         $form->{fromdate} = "1.10.$form->{year}";
577         $form->{todate}   = "31.10.$form->{year}";
578         last SWITCH;
579       };
580       $form->{duetyp} eq "11" && do {
581         $form->{fromdate} = "1.11.$form->{year}";
582         $form->{todate}   = "30.11.$form->{year}";
583         last SWITCH;
584       };
585       $form->{duetyp} eq "12" && do {
586         $form->{fromdate} = "1.12.$form->{year}";
587         $form->{todate}   = "31.12.$form->{year}";
588         last SWITCH;
589       };
590     }
591     hotfix_reformat_date();
592   }
593
594
595   # get for each account initial balance, debits and credits
596   RP->trial_balance(\%myconfig, \%$form, 'beginning_balances' => 1);
597
598
599   $form->{rowcount} = scalar @{ $form->{TB} || [] };
600   $form->{title} = sprintf($locale->text('Trial balance between %s and %s'), $form->{fromdate}, $form->{todate});
601
602   my @columns = (
603     "accno",               "description",
604     "last_transaction",    "soll_eb",
605     "haben_eb",
606     "soll",                "haben",
607     "soll_kumuliert",      "haben_kumuliert",
608     "soll_saldo",          "haben_saldo"
609   );
610
611
612   my $attachment_basename = $locale->text('trial_balance');
613   my $report              = SL::ReportGenerator->new(\%myconfig, $form);
614
615   my @hidden_variables    = qw(fromdate todate year cash);
616
617   my $href                = build_std_url('action=generate_trial_balance', grep { $form->{$_} } @hidden_variables);
618
619   my %column_defs         = (
620     'accno'               => { 'text' => $locale->text('Account'), },
621     'description'         => { 'text' => $locale->text('Description'), },
622     'last_transaction'    => { 'text' => $locale->text('Last Transaction'), },
623     'soll_eb'             => { 'text' => $locale->text('Debit Starting Balance'), },
624     'haben_eb'            => { 'text' => $locale->text('Credit Starting Balance'), },
625     'soll'                => { 'text' => $locale->text('Debit'), },
626     'haben'               => { 'text' => $locale->text('Credit'), },
627     'soll_kumuliert'      => { 'text' => $locale->text('Sum Debit'), },
628     'haben_kumuliert'     => { 'text' => $locale->text('Sum Credit'), },
629     'soll_saldo'          => { 'text' => $locale->text('Saldo Debit'), },
630     'haben_saldo'         => { 'text' => $locale->text('Saldo Credit'), }
631   );
632
633
634
635   my %column_alignment = map { $_ => 'right' } qw(soll_eb haben_eb soll haben soll_kumuliert haben_kumuliert soll_saldo haben_saldo);
636
637   map { $column_defs{$_}->{visible} =  1 } @columns;
638
639   $report->set_columns(%column_defs);
640   $report->set_column_order(@columns);
641
642   $report->set_export_options('generate_trial_balance', @hidden_variables);
643
644   my @options;
645
646
647   $form->{template_fromto} = $locale->date(\%myconfig, $form->{fromdate}, 0) . "&nbsp; - &nbsp;" . $locale->date(\%myconfig, $form->{todate}, 0);
648
649   $form->{print_date} = $locale->text('Create Date') . " " . $locale->date(\%myconfig, $form->current_date(\%myconfig), 0);
650   push (@options, $form->{print_date});
651
652   $form->{company} = $locale->text('Company') . " " . $myconfig{company};
653   push (@options, $form->{company});
654
655
656   $form->{template_to} = $locale->date(\%myconfig, $form->{todate}, 0);
657
658   $report->set_options('output_format'        => 'HTML',
659                        'top_info_text'        => join("\n", @options),
660                        'title'                => $form->{title},
661                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
662                        'html_template'        => 'rp/html_report_susa',
663                        'pdf_template'         => 'rp/html_report_susa',
664     );
665   $report->set_options_from_form();
666   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
667
668   # add sort and escape callback, this one we use for the add sub
669   $form->{callback} = $href .= "&sort=$form->{sort}";
670
671   # escape callback for href
672   my $callback = $form->escape($href);
673
674   my @subtotal_columns = qw(soll_eb haben_eb soll haben soll_kumuliert haben_kumuliert soll_saldo haben_saldo);
675
676   my %totals    = map { $_ => 0 } @subtotal_columns;
677
678   my $edit_url = build_std_url('action=edit', 'type', 'vc');
679
680   my $idx;
681   foreach my $accno (@{ $form->{TB} || [] }) {
682
683     $accno->{soll} = $accno->{debit};
684     $accno->{haben} = $accno->{credit};
685     map { $totals{$_}    += $accno->{$_} } @subtotal_columns;
686
687     map { $accno->{$_} = $accno->{$_} == 0 ? '' : $form->format_amount(\%myconfig, $accno->{$_}, 2) }
688       qw(soll_eb haben_eb soll haben soll_kumuliert haben_kumuliert soll_saldo haben_saldo);
689
690     my $row = { };
691
692     foreach my $column (@columns) {
693       $row->{$column} = {
694         'data'  => $accno->{$column},
695         'align' => $column_alignment{$column},
696       };
697     }
698
699     $row->{accno}->{link} = build_std_url('script=ca.pl', 'action=list_transactions', 'accno=' . E($accno->{accno}), 'description=' . E($accno->{description}), 'fromdate=' . E($form->{fromdate}), 'todate=' . E($form->{todate}), 'method=' . E($form->{method}));
700
701     my $row_set = [ $row ];
702
703
704     $report->add_data($row_set);
705
706     $idx++;
707   }
708
709   $report->add_separator();
710
711   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
712
713   $report->generate_with_headers();
714
715   $main::lxdebug->leave_sub();
716
717 }
718
719 sub create_subtotal_row {
720   $main::lxdebug->enter_sub();
721
722   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
723
724   my $form     = $main::form;
725   my %myconfig = %main::myconfig;
726   my $locale   = $main::locale;
727
728   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
729
730   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
731
732   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
733
734   map { $totals->{$_} = 0 } @{ $subtotal_columns };
735
736   $main::lxdebug->leave_sub();
737
738   return $row;
739 }
740
741 sub create_list_accounts_subtotal_row {
742   $main::lxdebug->enter_sub();
743
744   my ($subtotals, $columns, $fields, $class) = @_;
745
746   my $form     = $main::form;
747   my %myconfig = %main::myconfig;
748   my $locale   = $main::locale;
749
750   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => 'right' } } @{ $columns } };
751
752   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $subtotals->{$_}, 2) } @{ $fields };
753
754   $main::lxdebug->leave_sub();
755
756   return $row;
757 }
758
759 sub list_accounts {
760   $main::lxdebug->enter_sub();
761
762   my ($action) = @_;
763
764   my $form     = $main::form;
765   my %myconfig = %main::myconfig;
766   my $locale   = $main::locale;
767
768   my @options;
769   if ($form->{department}) {
770     my ($department) = split /--/, $form->{department};
771     push @options, $locale->text('Department') . " : $department";
772   }
773   if ($form->{projectnumber}) {
774     push @options, $locale->text('Project Number') . " : $form->{projectnumber}";
775   }
776
777   # if there are any dates
778   if ($form->{fromdate} || $form->{todate}) {
779     my ($fromdate, $todate);
780
781     if ($form->{fromdate}) {
782       $fromdate = $locale->date(\%myconfig, $form->{fromdate}, 1);
783     }
784     if ($form->{todate}) {
785       $todate = $locale->date(\%myconfig, $form->{todate}, 1);
786     }
787
788     push @options, "$fromdate - $todate";
789
790   } else {
791     push @options, $locale->date(\%myconfig, $form->current_date(\%myconfig), 1);
792   }
793
794   my @columns     = qw(accno description begbalance debit credit endbalance);
795   my %column_defs = (
796     'accno'       => { 'text' => $locale->text('Account'), },
797     'description' => { 'text' => $locale->text('Description'), },
798     'debit'       => { 'text' => $locale->text('Debit'), },
799     'credit'      => { 'text' => $locale->text('Credit'), },
800     'begbalance'  => { 'text' => $locale->text('Balance'), },
801     'endbalance'  => { 'text' => $locale->text('Balance'), },
802   );
803   my %column_alignment = map { $_ => 'right' } qw(debit credit begbalance endbalance);
804
805   my @hidden_variables = qw(fromdate todate department l_heading l_subtotal all_accounts sort accounttype eur projectnumber project_id title nextsub);
806
807   $form->{callback} = build_std_url("action=$action", grep { $form->{$_} } @hidden_variables);
808
809   my $report = SL::ReportGenerator->new(\%myconfig, $form);
810
811   $report->set_options('top_info_text'         => join("\n", @options),
812                        'output_format'         => 'HTML',
813                        'title'                 => $form->{title},
814                        'attachment_basename'   => $locale->text('list_of_transactions') . strftime('_%Y%m%d', localtime time),
815                        'std_column_visibility' => 1,
816     );
817   $report->set_options_from_form();
818   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
819
820   $report->set_columns(%column_defs);
821   $report->set_column_order(@columns);
822
823   $report->set_export_options($action, @hidden_variables);
824
825   my @totals_columns = qw(credit debit begbalance endbalance);
826   my %subtotals      = map { $_ => 0 } @totals_columns;
827   my %totals         = map { $_ => 0 } @totals_columns;
828   my $found_heading  = 0;
829   my @tb             = sort { $a->{accno} cmp $b->{accno} } @{ $form->{TB} || [] };
830
831   # sort the whole thing by account numbers and display
832   foreach my $idx (0 .. scalar(@tb) - 1) {
833     my $ref  = $tb[$idx];
834     my $href = build_std_url('script=ca.pl', 'action=list_transactions', 'accno=' . E($ref->{accno}), 'description=' . E($ref->{description}), @hidden_variables);
835
836     my $ml   = ($ref->{category} =~ /(A|C|E)/) ? -1 : 1;
837
838     my $row  = { map { $_ => { 'align' => $column_alignment{$_} } } @columns };
839
840     if ($ref->{charttype} eq 'H') {
841       next unless ($form->{l_heading});
842
843       %subtotals                   = map { $_ => 0 } @totals_columns;
844       $found_heading               = 1;
845       $row->{description}->{class} = 'listheading';
846       $row->{description}->{data}  = $ref->{description};
847
848       $report->add_data($row);
849
850       next;
851     }
852
853     foreach (qw(debit credit)) {
854       $subtotals{$_} += $ref->{$_};
855       $totals{$_}    += $ref->{$_};
856     }
857
858     $subtotals{begbalance} += $ref->{balance} * $ml;
859     $subtotals{endbalance} += ($ref->{balance} + $ref->{amount}) * $ml;
860
861     map { $row->{$_}->{data} = $ref->{$_} } qw(accno description);
862     map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $ref->{$_}, 2) if ($ref->{$_} != 0) } qw(credit debit);
863
864     $row->{begbalance}->{data} = $form->format_amount(\%myconfig, $ref->{balance} * $ml, 2);
865     $row->{endbalance}->{data} = $form->format_amount(\%myconfig, ($ref->{balance} + $ref->{amount}) * $ml, 2);
866
867     $report->add_data($row);
868
869     if ($form->{l_heading} && $found_heading &&
870         (($idx == scalar(@tb) - 1) || ('H' eq $tb[$idx + 1]->{charttype}))) {
871       $report->add_data(create_list_accounts_subtotal_row(\%subtotals, \@columns, \@totals_columns, 'listsubtotal'));
872     }
873   }
874
875   $report->add_separator();
876
877   $report->add_data(create_list_accounts_subtotal_row(\%totals, \@columns, [ qw(debit credit) ], 'listtotal'));
878
879   $report->generate_with_headers();
880
881   $main::lxdebug->leave_sub();
882 }
883
884 sub generate_ar_aging {
885   $main::lxdebug->enter_sub();
886
887   $main::auth->assert('general_ledger');
888
889   my $form     = $main::form;
890   my %myconfig = %main::myconfig;
891   my $locale   = $main::locale;
892
893   # split customer
894   ($form->{customer}) = split(/--/, $form->{customer});
895
896   $form->{ct}   = "customer";
897   $form->{arap} = "ar";
898
899   $form->{callback} = build_std_url('action=generate_ar_aging', qw(todate customer title));
900
901   RP->aging(\%myconfig, \%$form);
902   aging();
903
904   $main::lxdebug->leave_sub();
905 }
906
907 sub generate_ap_aging {
908   $main::lxdebug->enter_sub();
909
910   $main::auth->assert('general_ledger');
911
912   my $form     = $main::form;
913   my %myconfig = %main::myconfig;
914   my $locale   = $main::locale;
915
916   # split vendor
917   ($form->{vendor}) = split(/--/, $form->{vendor});
918
919   $form->{ct}   = "vendor";
920   $form->{arap} = "ap";
921
922   $form->{callback} = build_std_url('action=generate_ap_aging', qw(todate vendor title));
923
924   RP->aging(\%myconfig, \%$form);
925   aging();
926
927   $main::lxdebug->leave_sub();
928 }
929
930 sub create_aging_subtotal_row {
931   $main::lxdebug->enter_sub();
932
933   my ($subtotals, $columns, $periods, $class) = @_;
934
935   my $form     = $main::form;
936   my %myconfig = %main::myconfig;
937   my $locale   = $main::locale;
938
939   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => 'right' } } @{ $columns } };
940
941   foreach (@{ $periods }) {
942     $row->{"$_"}->{data} = $subtotals->{$_} != 0 ? $form->format_amount(\%myconfig, $subtotals->{$_}, 2) : '';
943     $subtotals->{$_}      = 0;
944   }
945
946   $main::lxdebug->leave_sub();
947
948   return $row;
949 }
950
951 sub aging {
952   $main::lxdebug->enter_sub();
953
954   $main::auth->assert('general_ledger');
955
956   my $form     = $main::form;
957   my %myconfig = %main::myconfig;
958   my $locale   = $main::locale;
959   my $cgi      = $::request->{cgi};
960
961   my $report = SL::ReportGenerator->new(\%myconfig, $form);
962
963   my @columns = qw(statement ct invnumber transdate duedate amount open);
964
965   my %column_defs = (
966     'statement' => { 'text' => '', 'visible' => $form->{ct} eq 'customer' ? 'HTML' : 0, },
967     'ct'        => { 'text' => $form->{ct} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
968     'invnumber' => { 'text' => $locale->text('Invoice'), },
969     'transdate' => { 'text' => $locale->text('Date'), },
970     'duedate'   => { 'text' => $locale->text('Due'), },
971     'amount'    => { 'text' => $locale->text('Amount'), },
972     'open'      => { 'text' => $locale->text('Open'), },
973   );
974
975   my %column_alignment = ('statement' => 'center',
976                           map { $_ => 'right' } qw(open amount));
977
978   $report->set_options('std_column_visibility' => 1);
979   $report->set_columns(%column_defs);
980   $report->set_column_order(@columns);
981
982   my @hidden_variables = qw(todate customer vendor arap title ct);
983   $report->set_export_options('generate_' . ($form->{arap} eq 'ar' ? 'ar' : 'ap') . '_aging', @hidden_variables);
984
985   my @options;
986   my $attachment_basename;
987
988   if ($form->{department}) {
989     my ($department) = split /--/, $form->{department};
990     push @options, $locale->text('Department') . " : $department";
991     $form->{callback} .= "&department=" . E($department);
992   }
993
994   if (($form->{arap} eq 'ar') && $form->{customer}) {
995     push @options, $form->{customer};
996     $attachment_basename = $locale->text('ar_aging_list');
997     $form->{title} = sprintf($locale->text('Ar aging on %s'), $form->{todate});
998   }
999
1000   if (($form->{arap} eq 'ap') && $form->{vendor}) {
1001     push @options, $form->{vendor};
1002     $attachment_basename = $locale->text('ap_aging_list');
1003     $form->{title} = sprintf($locale->text('Ap aging on %s'), $form->{todate});
1004   }
1005
1006   if ($form->{fromdate}) {
1007     push @options, $locale->text('for Period') . " " . $locale->text('From') . " " .$locale->date(\%myconfig, $form->{fromdate}, 1) . " " . $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{todate}, 1);
1008   } else {
1009     push @options, $locale->text('for Period') . " " . $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{todate}, 1);
1010   }
1011
1012   $attachment_basename = $form->{ct} eq 'customer' ? $locale->text('ar_aging_list') : $locale->text('ap_aging_list');
1013
1014   $report->set_options('top_info_text'        => join("\n", @options),
1015                        'output_format'        => 'HTML',
1016                        'title'                => $form->{title},
1017                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
1018     );
1019   $report->set_options_from_form();
1020   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1021
1022   my $previous_ctid = 0;
1023   my $row_idx       = 0;
1024   my @periods       = qw(open amount);
1025   my %subtotals     = map { $_ => 0 } @periods;
1026   my %totals        = map { $_ => 0 } @periods;
1027
1028   foreach my $ref (@{ $form->{AG} }) {
1029     if ($row_idx && ($previous_ctid != $ref->{ctid})) {
1030       $report->add_data(create_aging_subtotal_row(\%subtotals, \@columns, \@periods, 'listsubtotal'));
1031     }
1032
1033     foreach my $key (@periods) {
1034       $subtotals{$key}  += $ref->{"$key"};
1035       $totals{$key}     += $ref->{"$key"};
1036       $ref->{"$key"}  = $ref->{"$key"} != 0 ? $form->format_amount(\%myconfig, $ref->{"$key"}, 2) : '';
1037     }
1038
1039     my $row = { };
1040
1041     foreach my $column (@columns) {
1042       $row->{$column} = {
1043         'data'   => (($column eq 'ct') || ($column eq 'statement')) ? '' : $ref->{$column},
1044         'align'  => $column_alignment{$column},
1045         'valign' => $column eq 'statement' ? 'center' : '',
1046       };
1047     }
1048
1049     $row->{invnumber}->{link} =  build_std_url("script=$ref->{module}.pl", 'action=edit', 'callback', 'id=' . E($ref->{id}));
1050
1051     if ($previous_ctid != $ref->{ctid}) {
1052       $row->{statement}->{raw_data} =
1053           $cgi->hidden('-name' => "customer_id_" . ($row_idx + 1), '-value' => $ref->{ctid})
1054         . $cgi->checkbox('-name' => "statement_" . ($row_idx + 1), '-value' => 1, '-label' => '', 'checked' => $ref->{checked});
1055       $row->{ct}->{data} = $ref->{name};
1056
1057       $row_idx++;
1058     }
1059
1060     $previous_ctid = $ref->{ctid};
1061
1062     $report->add_data($row);
1063   }
1064
1065   $report->add_data(create_aging_subtotal_row(\%subtotals, \@columns, \@periods, 'listsubtotal')) if ($row_idx);
1066
1067   $report->add_data(create_aging_subtotal_row(\%totals, \@columns, \@periods, 'listtotal'));
1068
1069   if ($form->{arap} eq 'ar') {
1070     my $raw_top_info_text    = $form->parse_html_template('rp/aging_ar_top');
1071     my $raw_bottom_info_text = $form->parse_html_template('rp/aging_ar_bottom', { 'row_idx' => $row_idx,
1072                                                                                'PRINT_OPTIONS' => print_options(inline => 1), });
1073     $report->set_options('raw_top_info_text'    => $raw_top_info_text,
1074                          'raw_bottom_info_text' => $raw_bottom_info_text);
1075   }
1076
1077   $report->generate_with_headers();
1078
1079   $main::lxdebug->leave_sub();
1080 }
1081
1082 sub select_all {
1083   $main::lxdebug->enter_sub();
1084
1085   my $form     = $main::form;
1086   my %myconfig = %main::myconfig;
1087   my $locale   = $main::locale;
1088
1089   RP->aging(\%myconfig, \%$form);
1090
1091   map { $_->{checked} = "checked" } @{ $form->{AG} };
1092
1093   &aging;
1094
1095   $main::lxdebug->leave_sub();
1096 }
1097
1098 sub e_mail {
1099   $::lxdebug->enter_sub;
1100   $::auth->assert('general_ledger');
1101
1102   # get name and email addresses
1103   my $selected = 0;
1104   for my $i (1 .. $::form->{rowcount}) {
1105     next unless $::form->{"statement_$i"};
1106     $::form->{"$::form->{ct}_id"} = $::form->{"$::form->{ct}_id_$i"};
1107     RP->get_customer(\%::myconfig, $::form);
1108     $selected = 1;
1109     last;
1110   }
1111
1112   $::form->error($::locale->text('Nothing selected!')) unless $selected;
1113
1114   $::form->{media} = "email";
1115
1116   # save all other variables
1117   my @hidden_values;
1118   for my $key (keys %$::form) {
1119     next if any { $key eq $_ } qw(login password action email cc bcc subject message type sendmode format header);
1120     next unless '' eq ref $::form->{$key};
1121     push @hidden_values, $key;
1122   }
1123
1124   $::form->header;
1125   print $::form->parse_html_template('rp/e_mail', {
1126     show_bcc      => $::auth->assert('email_bcc', 'may fail'),
1127     print_options => print_options(inline => 1),
1128     hidden_values => \@hidden_values,
1129   });
1130
1131   $::lxdebug->leave_sub;
1132 }
1133
1134 sub send_email {
1135   $main::lxdebug->enter_sub();
1136
1137   $main::auth->assert('general_ledger');
1138
1139   my $form     = $main::form;
1140   my %myconfig = %main::myconfig;
1141   my $locale   = $main::locale;
1142
1143   $form->{subject} = $locale->text('Statement') . qq| - $form->{todate}|
1144     unless $form->{subject};
1145
1146   RP->aging(\%myconfig, \%$form);
1147
1148   $form->{"statement_1"} = 1;
1149
1150   $form->{media} = 'email';
1151   print_form();
1152
1153   $form->redirect($locale->text('Statement sent to') . " $form->{$form->{ct}}");
1154
1155   $main::lxdebug->leave_sub();
1156 }
1157
1158 sub print {
1159   $main::lxdebug->enter_sub();
1160
1161   $main::auth->assert('general_ledger');
1162
1163   my $form     = $main::form;
1164   my %myconfig = %main::myconfig;
1165   my $locale   = $main::locale;
1166
1167   if ($form->{media} eq 'printer') {
1168     $form->error($locale->text('Select postscript or PDF!'))
1169       if ($form->{format} !~ /(postscript|pdf)/);
1170   }
1171
1172   my $selected = 0;
1173   for my $i (1 .. $form->{rowcount}) {
1174     if ($form->{"statement_$i"}) {
1175       $form->{"$form->{ct}_id"} = $form->{"$form->{ct}_id_$i"};
1176       $selected = 1;
1177       last;
1178     }
1179   }
1180
1181   $form->error($locale->text('Nothing selected!')) unless $selected;
1182
1183   if ($form->{media} eq 'printer') {
1184     $form->{"$form->{ct}_id"} = "";
1185   } else {
1186     $form->{"statement_1"} = 1;
1187   }
1188
1189   RP->aging(\%myconfig, \%$form);
1190
1191   print_form();
1192
1193   $form->redirect($locale->text('Statements sent to printer!'))
1194     if ($form->{media} eq 'printer');
1195
1196   $main::lxdebug->leave_sub();
1197 }
1198
1199 sub print_form {
1200   $main::lxdebug->enter_sub();
1201
1202   $main::auth->assert('general_ledger');
1203
1204   my $form     = $main::form;
1205   my %myconfig = %main::myconfig;
1206   my $locale   = $main::locale;
1207
1208   $form->{statementdate} = $locale->date(\%myconfig, $form->{todate}, 1);
1209
1210   $form->{templates} = "$myconfig{templates}";
1211
1212   my $suffix = "html";
1213   my $attachment_suffix = "html";
1214   if ($form->{format} eq 'postscript') {
1215     $form->{postscript} = 1;
1216     $suffix = "tex";
1217     $attachment_suffix = "ps";
1218   } elsif ($form->{format} eq 'pdf') {
1219     $form->{pdf} = 1;
1220     $suffix = "tex";
1221     $attachment_suffix = "pdf";
1222   }
1223
1224   $form->{IN}  = "$form->{type}.$suffix";
1225   $form->{OUT} = $form->{media} eq 'printer' ? "| $myconfig{printer}" : "";
1226
1227   # Save $form->{email} because it will be overwritten.
1228   $form->{EMAIL_RECIPIENT} = $form->{email};
1229
1230   my $i = 0;
1231   my $ctid;
1232   while (@{ $form->{AG} }) {
1233
1234     my $ref = shift @{ $form->{AG} };
1235
1236     if ($ctid != $ref->{ctid}) {
1237
1238       $ctid = $ref->{ctid};
1239       $i++;
1240
1241       if ($form->{"statement_$i"}) {
1242
1243         my @a =
1244           ("name", "street", "zipcode", "city", "country", "contact", "email",
1245            "$form->{ct}phone", "$form->{ct}fax");
1246         map { $form->{$_} = $ref->{$_} } @a;
1247
1248         $form->{ $form->{ct} } = $form->{name};
1249         $form->{"$form->{ct}_id"} = $ref->{ctid};
1250
1251         map { $form->{$_} = () } qw(invnumber invdate duedate amount open);
1252         $form->{total} = 0;
1253         foreach my $item (qw(c0 c30 c60 c90)) {
1254           $form->{$item} = ();
1255           $form->{"${item}total"} = 0;
1256         }
1257
1258         &statement_details($ref);
1259
1260         while ($ref) {
1261
1262           if (scalar(@{ $form->{AG} }) > 0) {
1263
1264             # one or more left to go
1265             if ($ctid == $form->{AG}->[0]->{ctid}) {
1266               $ref = shift @{ $form->{AG} };
1267               &statement_details($ref);
1268
1269               # any more?
1270               $ref = scalar(@{ $form->{AG} });
1271             } else {
1272               $ref = 0;
1273             }
1274           } else {
1275
1276             # set initial ref to 0
1277             $ref = 0;
1278           }
1279
1280         }
1281
1282         map {
1283           $form->{"${_}total"} =
1284             $form->format_amount(\%myconfig, $form->{"${_}total"}, 2)
1285         } ('c0', 'c30', 'c60', 'c90', "");
1286
1287         $form->{attachment_filename} =  $locale->quote_special_chars('filenames', $locale->text("Statement") . "_$form->{todate}.$attachment_suffix");
1288         $form->{attachment_filename} =~ s/\s+/_/g;
1289
1290         $form->parse_template(\%myconfig);
1291
1292       }
1293     }
1294   }
1295   # saving the history
1296   if(!exists $form->{addition} && $form->{id} ne "") {
1297     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1298     $form->{addition} = "PRINTED";
1299     $form->{what_done} = $form->{type};
1300     $form->save_history;
1301   }
1302   # /saving the history
1303   $main::lxdebug->leave_sub();
1304 }
1305
1306 sub statement_details {
1307   $main::lxdebug->enter_sub();
1308
1309   $main::auth->assert('general_ledger');
1310
1311   my $form     = $main::form;
1312   my %myconfig = %main::myconfig;
1313   my $locale   = $main::locale;
1314
1315   my ($ref) = @_;
1316
1317   push @{ $form->{invnumber} }, $ref->{invnumber};
1318   push @{ $form->{invdate} },   $ref->{transdate};
1319   push @{ $form->{duedate} },   $ref->{duedate};
1320   push @{ $form->{amount} },    $form->format_amount(\%myconfig, $ref->{amount} / $ref->{exchangerate}, 2);
1321   push @{ $form->{open} },      $form->format_amount(\%myconfig, $ref->{open} / $ref->{exchangerate}, 2);
1322
1323   foreach my $item (qw(c0 c30 c60 c90)) {
1324     if ($ref->{exchangerate} * 1) {
1325       # add only the open amount of the invoice to the aging, not the total amount
1326       $ref->{"${item}"} = $form->round_amount($ref->{open} / $ref->{exchangerate}, 2) if $ref->{overduedays} < 30 and $item eq 'c0';
1327       $ref->{"${item}"} = $form->round_amount($ref->{open} / $ref->{exchangerate}, 2) if $ref->{overduedays} >= 30 and $ref->{overduedays} < 60 and $item eq 'c30';
1328       $ref->{"${item}"} = $form->round_amount($ref->{open} / $ref->{exchangerate}, 2) if $ref->{overduedays} >= 60 and $ref->{overduedays} < 90 and $item eq 'c60';
1329       $ref->{"${item}"} = $form->round_amount($ref->{open} / $ref->{exchangerate}, 2) if $ref->{overduedays} >= 90 and $item eq 'c90';
1330     }
1331     $form->{"${item}total"} += $ref->{$item};
1332     $form->{total}          += $ref->{$item};
1333     push @{ $form->{$item} },
1334       $form->format_amount(\%myconfig, $ref->{$item}, 2);
1335   }
1336
1337   $main::lxdebug->leave_sub();
1338 }
1339
1340 sub generate_tax_report {
1341   $::lxdebug->enter_sub;
1342   $::auth->assert('report');
1343
1344   RP->tax_report(\%::myconfig, $::form);
1345
1346   my $descvar     = "$::form->{accno}_description";
1347   my ($subtotalnetamount, $subtotaltax, $subtotal) = (0, 0, 0);
1348
1349   # construct href
1350   my $href     =
1351   my $callback = build_std_url('action=generate_tax_report', $descvar,
1352     qw(fromdate todate db method accno department report title));
1353
1354   my @columns = $::form->sort_columns(qw(id transdate invnumber name netamount tax amount));
1355   my @column_index;
1356
1357   for my $item (@columns, 'subtotal') {
1358     if ($::form->{"l_$item"} eq "Y") {
1359       $callback .= "&l_$item=Y";
1360       $href     .= "&l_$item=Y";
1361     }
1362   }
1363
1364   for my $item (@columns) {
1365     if ($::form->{"l_$item"} eq "Y") {
1366       push @column_index, $item;
1367     }
1368   }
1369
1370   my @options;
1371   if ($::form->{department}) {
1372     my ($department) = split /--/, $::form->{department};
1373     push @options, $::locale->text('Department') . " : $department";
1374   }
1375
1376   # if there are any dates
1377   if ($::form->{fromdate} || $::form->{todate}) {
1378     my $fromdate = $::form->{fromdate} ? $::locale->date(\%::myconfig, $::form->{fromdate}, 1) : '';
1379     my $todate   = $::form->{todate}   ? $::locale->date(\%::myconfig, $::form->{todate}, 1)   : '';
1380     push @options, "$fromdate - $todate";
1381   } else {
1382     push @options, $::locale->date(\%::myconfig, $::form->current_date, 1);
1383   }
1384
1385   my ($name, $invoice, $arap);
1386   if ($::form->{db} eq 'ar') {
1387     $name    = $::locale->text('Customer');
1388     $invoice = 'is.pl';
1389     $arap    = 'ar.pl';
1390   }
1391   if ($::form->{db} eq 'ap') {
1392     $name    = $::locale->text('Vendor');
1393     $invoice = 'ir.pl';
1394     $arap    = 'ap.pl';
1395   }
1396
1397   my %column_header = (
1398     id        => $::locale->text('ID'),
1399     invnumber => $::locale->text('Invoice'),
1400     transdate => $::locale->text('Date'),
1401     netamount => $::locale->text('Amount'),
1402     tax       => $::locale->text('Tax'),
1403     amount    => $::locale->text('Total'),
1404     name      => $name,
1405   );
1406
1407   my %column_sorted = map { $_ => 1 } qw(id invnumber transdate);
1408
1409   $callback .= "&sort=$::form->{sort}";
1410
1411   my $sameitem;
1412   if (@{ $::form->{TR} }) {
1413     $sameitem = $::form->{TR}->[0]->{ $::form->{sort} };
1414   }
1415
1416   my ($totalnetamount, $totaltax, @data);
1417   for my $ref (@{ $::form->{TR} }) {
1418
1419     my $module = ($ref->{invoice}) ? $invoice : $arap;
1420
1421     if ($::form->{l_subtotal} eq 'Y') {
1422       if ($sameitem ne $ref->{ $::form->{sort} }) {
1423         push @data, {
1424           subtotal  => 1,
1425           netamount => $subtotalnetamount,
1426           tax       => $subtotaltax,
1427           amount    => $subtotal,
1428         };
1429         $subtotalnetamount = 0;
1430         $subtotaltax       = 0;
1431         $sameitem          = $ref->{ $::form->{sort} };
1432       }
1433     }
1434
1435     $subtotalnetamount += $ref->{netamount};
1436     $subtotaltax       += $ref->{tax};
1437     $totalnetamount    += $ref->{netamount};
1438     $totaltax          += $ref->{tax};
1439     $ref->{amount}      = $ref->{netamount} + $ref->{tax};
1440
1441     push @data, { map { $_ => { data => $ref->{$_} } } keys %$ref };
1442     $data[-1]{invnumber}{link} = "$module?action=edit&id=$ref->{id}&callback=$callback";
1443     $data[-1]{$_}{numeric}     = 1 for qw(netamount tax amount);
1444   }
1445
1446   if ($::form->{l_subtotal} eq 'Y') {
1447     push @data, {
1448       subtotal  => 1,
1449       netamount => $subtotalnetamount,
1450       tax       => $subtotaltax,
1451       amount    => $subtotal,
1452     };
1453   }
1454
1455   push @data, {
1456     total     => 1,
1457     netamount => $totalnetamount,
1458     tax       => $totaltax,
1459     amount    => $totalnetamount + $totaltax,
1460   };
1461
1462   $::form->header;
1463   print $::form->parse_html_template('rp/tax_report', {
1464     column_index  => \@column_index,
1465     column_header => \%column_header,
1466     column_sorted => \%column_sorted,
1467     sort_base     => $href,
1468     DATA          => \@data,
1469     options       => \@options,
1470   });
1471
1472   $::lxdebug->leave_sub;
1473 }
1474
1475 sub list_payments {
1476   $main::lxdebug->enter_sub();
1477
1478   $main::auth->assert('cash');
1479
1480   my $form     = $main::form;
1481   my %myconfig = %main::myconfig;
1482   my $locale   = $main::locale;
1483
1484   if ($form->{account}) {
1485     ($form->{paymentaccounts}) = split /--/, $form->{account};
1486   }
1487
1488   my $option;
1489   if ($form->{department}) {
1490     (my $department, $form->{department_id}) = split /--/, $form->{department};
1491     $option = $locale->text('Department') . " : $department";
1492   }
1493
1494   report_generator_set_default_sort('transdate', 1);
1495
1496   RP->payments(\%myconfig, \%$form);
1497
1498   my @hidden_variables = qw(account title department reference source memo fromdate todate
1499                             fx_transaction db prepayment paymentaccounts sort);
1500
1501   my $href = build_std_url('action=list_payments', grep { $form->{$_} } @hidden_variables);
1502   $form->{callback} = $href;
1503
1504   my @columns     = qw(transdate invnumber name paid source memo);
1505   my %column_defs = (
1506     'name'      => { 'text' => $locale->text('Description'), },
1507     'invnumber' => { 'text' => $locale->text('Reference'), },
1508     'transdate' => { 'text' => $locale->text('Date'), },
1509     'paid'      => { 'text' => $locale->text('Amount'), },
1510     'source'    => { 'text' => $locale->text('Source'), },
1511     'memo'      => { 'text' => $locale->text('Memo'), },
1512   );
1513   my %column_alignment = ('paid' => 'right');
1514
1515   foreach my $name (grep { $_ ne 'paid' } @columns) {
1516     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1517     $column_defs{$name}->{link} = $href . "&sort=${name}&sortdir=$sortdir";
1518   }
1519
1520   my @options;
1521   if ($form->{fromdate}) {
1522     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{fromdate}, 1);
1523   }
1524   if ($form->{todate}) {
1525     push @options, $locale->text('bis') . " " . $locale->date(\%myconfig, $form->{todate}, 1);
1526   }
1527
1528   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1529
1530   my $attachment_basename = $form->{db} eq 'ar' ? $locale->text('list_of_receipts') : $locale->text('list_of_payments');
1531
1532   $report->set_options('top_info_text'         => join("\n", @options),
1533                        'output_format'         => 'HTML',
1534                        'title'                 => $form->{title},
1535                        'attachment_basename'   => $attachment_basename . strftime('_%Y%m%d', localtime time),
1536                        'std_column_visibility' => 1,
1537     );
1538   $report->set_options_from_form();
1539
1540   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1541
1542   $report->set_columns(%column_defs);
1543   $report->set_column_order(@columns);
1544
1545   $report->set_export_options('list_payments', @hidden_variables, qw(sort sortdir));
1546
1547   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1548
1549   my $total_paid    = 0;
1550
1551   foreach my $ref (sort { $a->{accno} cmp $b->{accno} } @{ $form->{PR} }) {
1552     next unless @{ $form->{ $ref->{id} } };
1553
1554     $report->add_control({ 'type' => 'colspan_data', 'data' => "$ref->{accno}--$ref->{description}" });
1555
1556     my $subtotal_paid = 0;
1557
1558     foreach my $payment (@{ $form->{ $ref->{id} } }) {
1559       my $module = $payment->{module};
1560       $module = 'is' if ($payment->{invoice} && $payment->{module} eq 'ar');
1561       $module = 'ir' if ($payment->{invoice} && $payment->{module} eq 'ap');
1562
1563       $subtotal_paid += $payment->{paid};
1564       $total_paid    += $payment->{paid};
1565
1566       $payment->{paid} = $form->format_amount(\%myconfig, $payment->{paid}, 2);
1567
1568       my $row = { };
1569
1570       foreach my $column (@columns) {
1571         $row->{$column} = {
1572           'data'  => $payment->{$column},
1573           'align' => $column_alignment{$column},
1574         };
1575       }
1576
1577       $row->{invnumber}->{link} = build_std_url("script=${module}.pl", 'action=edit', 'id=' . E($payment->{id}), 'callback');
1578
1579       $report->add_data($row);
1580     }
1581
1582     my $row = { map { $_ => { 'class' => 'listsubtotal' } } @columns };
1583     $row->{paid} = {
1584       'data'  => $form->format_amount(\%myconfig, $subtotal_paid, 2),
1585       'align' => 'right',
1586       'class' => 'listsubtotal',
1587     };
1588
1589     $report->add_data($row);
1590   }
1591
1592   $report->add_separator();
1593
1594   my $row = { map { $_ => { 'class' => 'listtotal' } } @columns };
1595   $row->{paid} = {
1596     'data'  => $form->format_amount(\%myconfig, $total_paid, 2),
1597     'align' => 'right',
1598     'class' => 'listtotal',
1599   };
1600
1601   $report->add_data($row);
1602
1603   $report->generate_with_headers();
1604
1605   $main::lxdebug->leave_sub();
1606 }
1607
1608 sub print_options {
1609   $::lxdebug->enter_sub;
1610
1611   my ($dont_print) = @_;
1612
1613   $::form->{sendmode} = "attachment";
1614   $::form->{format} ||= $::myconfig{template_format} || "pdf";
1615   $::form->{copies} ||= $::myconfig{copies}          || 2;
1616
1617   $::form->{PD}{ $::form->{type} }     = "selected";
1618   $::form->{DF}{ $::form->{format} }   = "selected";
1619   $::form->{OP}{ $::form->{media} }    = "selected";
1620   $::form->{SM}{ $::form->{sendmode} } = "selected";
1621
1622   my $output = $::form->parse_html_template('rp/print_options', {
1623     got_printer => $::myconfig{printer},
1624     show_latex  => $::lx_office_conf{print_templates}->{latex},
1625     is_email    => $::form->{media} eq 'email',
1626   });
1627
1628   print $output unless $dont_print;
1629
1630   $::lxdebug->leave_sub;
1631
1632   return $output;
1633 }
1634
1635 sub generate_bwa {
1636   $main::lxdebug->enter_sub();
1637
1638   $main::auth->assert('report');
1639
1640   my $form     = $main::form;
1641   my %myconfig = %main::myconfig;
1642   my $locale   = $main::locale;
1643
1644   $form->{padding} = "&nbsp;&nbsp;";
1645   $form->{bold}    = "<b>";
1646   $form->{endbold} = "</b>";
1647   $form->{br}      = "<br>";
1648
1649   if ($form->{reporttype} eq "custom") {
1650
1651     #forgotten the year --> thisyear
1652     if ($form->{year} !~ m/^\d\d\d\d$/) {
1653       $locale->date(\%myconfig, $form->current_date(\%myconfig), 0) =~
1654         /(\d\d\d\d)/;
1655       $form->{year} = $1;
1656     }
1657
1658     #yearly report
1659     if ($form->{duetyp} eq "13") {
1660       $form->{fromdate}        = "1.1.$form->{year}";
1661       $form->{todate}          = "31.12.$form->{year}";
1662       $form->{comparefromdate} = "1.01.$form->{year}";
1663       $form->{comparetodate}   = "31.12.$form->{year}";
1664     }
1665
1666     #Quater reports
1667     if ($form->{duetyp} eq "A") {
1668       $form->{fromdate}        = "1.1.$form->{year}";
1669       $form->{todate}          = "31.3.$form->{year}";
1670       $form->{comparefromdate} = "1.01.$form->{year}";
1671       $form->{comparetodate}   = "31.03.$form->{year}";
1672     }
1673     if ($form->{duetyp} eq "B") {
1674       $form->{fromdate}        = "1.4.$form->{year}";
1675       $form->{todate}          = "30.6.$form->{year}";
1676       $form->{comparefromdate} = "1.01.$form->{year}";
1677       $form->{comparetodate}   = "30.06.$form->{year}";
1678     }
1679     if ($form->{duetyp} eq "C") {
1680       $form->{fromdate}        = "1.7.$form->{year}";
1681       $form->{todate}          = "30.9.$form->{year}";
1682       $form->{comparefromdate} = "1.01.$form->{year}";
1683       $form->{comparetodate}   = "30.09.$form->{year}";
1684     }
1685     if ($form->{duetyp} eq "D") {
1686       $form->{fromdate}        = "1.10.$form->{year}";
1687       $form->{todate}          = "31.12.$form->{year}";
1688       $form->{comparefromdate} = "1.01.$form->{year}";
1689       $form->{comparetodate}   = "31.12.$form->{year}";
1690     }
1691
1692     #Monthly reports
1693   SWITCH: {
1694       $form->{duetyp} eq "1" && do {
1695         $form->{fromdate}        = "1.1.$form->{year}";
1696         $form->{todate}          = "31.1.$form->{year}";
1697         $form->{comparefromdate} = "1.01.$form->{year}";
1698         $form->{comparetodate}   = "31.01.$form->{year}";
1699         last SWITCH;
1700       };
1701       $form->{duetyp} eq "2" && do {
1702         $form->{fromdate} = "1.2.$form->{year}";
1703
1704         #this works from 1901 to 2099, 1900 and 2100 fail.
1705         my $leap = ($form->{year} % 4 == 0) ? "29" : "28";
1706         $form->{todate}          = "$leap.2.$form->{year}";
1707         $form->{comparefromdate} = "1.01.$form->{year}";
1708         $form->{comparetodate}   = "$leap.02.$form->{year}";
1709         last SWITCH;
1710       };
1711       $form->{duetyp} eq "3" && do {
1712         $form->{fromdate}        = "1.3.$form->{year}";
1713         $form->{todate}          = "31.3.$form->{year}";
1714         $form->{comparefromdate} = "1.01.$form->{year}";
1715         $form->{comparetodate}   = "31.03.$form->{year}";
1716         last SWITCH;
1717       };
1718       $form->{duetyp} eq "4" && do {
1719         $form->{fromdate}        = "1.4.$form->{year}";
1720         $form->{todate}          = "30.4.$form->{year}";
1721         $form->{comparefromdate} = "1.01.$form->{year}";
1722         $form->{comparetodate}   = "30.04.$form->{year}";
1723         last SWITCH;
1724       };
1725       $form->{duetyp} eq "5" && do {
1726         $form->{fromdate}        = "1.5.$form->{year}";
1727         $form->{todate}          = "31.5.$form->{year}";
1728         $form->{comparefromdate} = "1.01.$form->{year}";
1729         $form->{comparetodate}   = "31.05.$form->{year}";
1730         last SWITCH;
1731       };
1732       $form->{duetyp} eq "6" && do {
1733         $form->{fromdate}        = "1.6.$form->{year}";
1734         $form->{todate}          = "30.6.$form->{year}";
1735         $form->{comparefromdate} = "1.01.$form->{year}";
1736         $form->{comparetodate}   = "30.06.$form->{year}";
1737         last SWITCH;
1738       };
1739       $form->{duetyp} eq "7" && do {
1740         $form->{fromdate}        = "1.7.$form->{year}";
1741         $form->{todate}          = "31.7.$form->{year}";
1742         $form->{comparefromdate} = "1.01.$form->{year}";
1743         $form->{comparetodate}   = "31.07.$form->{year}";
1744         last SWITCH;
1745       };
1746       $form->{duetyp} eq "8" && do {
1747         $form->{fromdate}        = "1.8.$form->{year}";
1748         $form->{todate}          = "31.8.$form->{year}";
1749         $form->{comparefromdate} = "1.01.$form->{year}";
1750         $form->{comparetodate}   = "31.08.$form->{year}";
1751         last SWITCH;
1752       };
1753       $form->{duetyp} eq "9" && do {
1754         $form->{fromdate}        = "1.9.$form->{year}";
1755         $form->{todate}          = "30.9.$form->{year}";
1756         $form->{comparefromdate} = "1.01.$form->{year}";
1757         $form->{comparetodate}   = "30.09.$form->{year}";
1758         last SWITCH;
1759       };
1760       $form->{duetyp} eq "10" && do {
1761         $form->{fromdate}        = "1.10.$form->{year}";
1762         $form->{todate}          = "31.10.$form->{year}";
1763         $form->{comparefromdate} = "1.01.$form->{year}";
1764         $form->{comparetodate}   = "31.10.$form->{year}";
1765         last SWITCH;
1766       };
1767       $form->{duetyp} eq "11" && do {
1768         $form->{fromdate}        = "1.11.$form->{year}";
1769         $form->{todate}          = "30.11.$form->{year}";
1770         $form->{comparefromdate} = "1.01.$form->{year}";
1771         $form->{comparetodate}   = "30.11.$form->{year}";
1772         last SWITCH;
1773       };
1774       $form->{duetyp} eq "12" && do {
1775         $form->{fromdate}        = "1.12.$form->{year}";
1776         $form->{todate}          = "31.12.$form->{year}";
1777         $form->{comparefromdate} = "1.01.$form->{year}";
1778         $form->{comparetodate}   = "31.12.$form->{year}";
1779         last SWITCH;
1780       };
1781     }
1782     hotfix_reformat_date();
1783   } else {
1784     # die konvertierungen nur dann durchführen, wenn auch daten gesetzt sind.
1785     # ansonsten ist die prüfung in RP.pm
1786     # if (defined ($form->{fromdate|todate}=='..'))
1787     # immer wahr
1788     if ($form->{fromdate}){
1789       my ($yy, $mm, $dd) = $locale->parse_date(\%myconfig, $form->{fromdate});
1790       my $datetime = $locale->parse_date_to_object(\%myconfig, $form->{fromdate});
1791       $datetime->set( month      => 1,
1792                       day        => 1);
1793       $form->{comparefromdate} = $locale->format_date(\%::myconfig, $datetime);
1794     }
1795     if ($form->{todate}){
1796       $form->{comparetodate}   = $form->{todate};
1797     }
1798   }
1799
1800   RP->bwa(\%myconfig, \%$form);
1801
1802   ($form->{department}) = split /--/, $form->{department};
1803
1804   $form->{period} =
1805     $locale->date(\%myconfig, $form->current_date(\%myconfig), 1);
1806   $form->{todate} = $form->current_date(\%myconfig) unless $form->{todate};
1807
1808   # if there are any dates construct a where
1809   if ($form->{fromdate} || $form->{todate}) {
1810
1811     unless ($form->{todate}) {
1812       $form->{todate} = $form->current_date(\%myconfig);
1813     }
1814
1815     my %germandate = ("dateformat" => "dd.mm.yyyy");
1816
1817     my $longtodate  = $locale->date(\%germandate, $form->{todate}, 1);
1818     my $shorttodate = $locale->date(\%germandate, $form->{todate}, 0);
1819
1820     my $longfromdate  = $locale->date(\%germandate, $form->{fromdate}, 1);
1821     my $shortfromdate = $locale->date(\%germandate, $form->{fromdate}, 0);
1822
1823     $form->{this_period} = "$shortfromdate\n$shorttodate";
1824     $form->{period}      =
1825         $locale->text('for Period')
1826       . qq|\n$longfromdate |
1827       . $locale->text('bis')
1828       . qq| $longtodate|;
1829   }
1830
1831   # setup variables for the form
1832   my @a = qw(company address businessnumber);
1833   map { $form->{$_} = $myconfig{$_} } @a;
1834   $form->{templates} = $myconfig{templates};
1835
1836   $form->{IN} = "bwa.html";
1837
1838   $form->parse_template;
1839
1840   $main::lxdebug->leave_sub();
1841 }
1842 ###
1843 # Hotfix, um das Datumsformat, die unten hart auf deutsches Datumsformat eingestellt
1844 # sind, entsprechend mit anderem Formaten (z.B. iso-kodiert) zum Laufen zu bringen (S.a.: Bug 1388)
1845 sub hotfix_reformat_date {
1846
1847   $main::lxdebug->enter_sub();
1848
1849   my $form     = $main::form;
1850   my %myconfig = %main::myconfig;
1851   my $locale   = $main::locale;
1852
1853   if ($myconfig{dateformat} ne 'dd.mm.yyyy'){
1854     my $current_dateformat = $myconfig{dateformat};
1855     $myconfig{dateformat} = 'dd.mm.yyyy';
1856     $form->{fromdate} = $main::locale->reformat_date(\%myconfig, $form->{fromdate}, $current_dateformat);
1857     $form->{todate} = $main::locale->reformat_date(\%myconfig, $form->{todate}, $current_dateformat);
1858     $form->{comparefromdate} = $main::locale->reformat_date(\%myconfig, $form->{comparefromdate}, $current_dateformat)
1859       unless (!defined ($form->{comparefromdate}));
1860     $form->{comparetodate} = $main::locale->reformat_date(\%myconfig, $form->{comparetodate}, $current_dateformat)
1861       unless (!defined ($form->{comparetodate}));
1862
1863     # Und wieder zurücksetzen
1864     $myconfig{dateformat} =  $current_dateformat; #'dd.mm.yyyy';
1865   } # Ende Hotifx Bug 1388
1866
1867   $main::lxdebug->leave_sub();
1868
1869 }
1870 1;