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