Dispatcher: end_of_request() sub aus main namespace verbannt
[kivitendo-erp.git] / bin / mozilla / ar.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) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Accounts Receivables
31 #
32 #======================================================================
33
34 use POSIX qw(strftime);
35 use List::Util qw(sum first max);
36 use List::UtilsBy qw(sort_by);
37
38 use SL::AR;
39 use SL::FU;
40 use SL::IS;
41 use SL::PE;
42 use SL::DB::Default;
43 use SL::DB::Invoice;
44 use SL::ReportGenerator;
45
46 require "bin/mozilla/arap.pl";
47 require "bin/mozilla/common.pl";
48 require "bin/mozilla/drafts.pl";
49 require "bin/mozilla/reportgenerator.pl";
50
51 use strict;
52 #use warnings;
53
54 # this is for our long dates
55 # $locale->text('January')
56 # $locale->text('February')
57 # $locale->text('March')
58 # $locale->text('April')
59 # $locale->text('May ')
60 # $locale->text('June')
61 # $locale->text('July')
62 # $locale->text('August')
63 # $locale->text('September')
64 # $locale->text('October')
65 # $locale->text('November')
66 # $locale->text('December')
67
68 # this is for our short month
69 # $locale->text('Jan')
70 # $locale->text('Feb')
71 # $locale->text('Mar')
72 # $locale->text('Apr')
73 # $locale->text('May')
74 # $locale->text('Jun')
75 # $locale->text('Jul')
76 # $locale->text('Aug')
77 # $locale->text('Sep')
78 # $locale->text('Oct')
79 # $locale->text('Nov')
80 # $locale->text('Dec')
81
82 sub add {
83   $main::lxdebug->enter_sub();
84
85   $main::auth->assert('general_ledger');
86
87   my $form     = $main::form;
88   my %myconfig = %main::myconfig;
89
90   return $main::lxdebug->leave_sub() if (load_draft_maybe());
91
92   # saving the history
93   if(!exists $form->{addition} && ($form->{id} ne "")) {
94     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
95     $form->{addition} = "ADDED";
96     $form->save_history;
97   }
98   # /saving the history
99
100   $form->{title}    = "Add";
101   $form->{callback} = "ar.pl?action=add&DONT_LOAD_DRAFT=1" unless $form->{callback};
102
103   AR->get_transdate(\%myconfig, $form);
104   $form->{initial_transdate} = $form->{transdate};
105   create_links(dont_save => 1);
106   $form->{transdate} = $form->{initial_transdate};
107   &display_form;
108   $main::lxdebug->leave_sub();
109 }
110
111 sub edit {
112   $main::lxdebug->enter_sub();
113
114   $main::auth->assert('general_ledger');
115
116   my $form     = $main::form;
117
118   # show history button
119   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
120   #/show hhistory button
121   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
122   $form->{title} = "Edit";
123
124   create_links();
125   &display_form;
126
127   $main::lxdebug->leave_sub();
128 }
129
130 sub display_form {
131   $main::lxdebug->enter_sub();
132
133   $main::auth->assert('general_ledger');
134
135   my $form     = $main::form;
136
137   &form_header;
138   &form_footer;
139
140   $main::lxdebug->leave_sub();
141 }
142
143 sub _retrieve_invoice_object {
144   return undef if !$::form->{id};
145   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
146   return SL::DB::Invoice->new(id => $::form->{id})->load;
147 }
148
149 sub create_links {
150   $main::lxdebug->enter_sub();
151
152   $main::auth->assert('general_ledger');
153
154   my %params   = @_;
155   my $form     = $main::form;
156   my %myconfig = %main::myconfig;
157
158   $form->create_links("AR", \%myconfig, "customer");
159   $form->{invoice_obj} = _retrieve_invoice_object();
160
161   my %saved;
162   if (!$params{dont_save}) {
163     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
164     $saved{duedate} = $form->{duedate} if $form->{duedate};
165   }
166
167   IS->get_customer(\%myconfig, \%$form);
168
169   $form->{$_}          = $saved{$_} for keys %saved;
170   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
171   $form->{rowcount}    = 1;
172
173   # currencies
174   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
175
176   map { $form->{selectcurrency} .= "<option>$_\n" } $form->get_all_currencies(\%myconfig);
177
178   # customers
179   if (@{ $form->{all_customer} || [] }) {
180     $form->{customer} = "$form->{customer}--$form->{customer_id}";
181     map { $form->{selectcustomer} .= "<option>$_->{name}--$_->{id}\n" }
182       (@{ $form->{all_customer} });
183   }
184
185   # departments
186   if (@{ $form->{all_departments} || [] }) {
187     $form->{selectdepartment} = "<option>\n";
188     $form->{department}       = "$form->{department}--$form->{department_id}";
189
190     map {
191       $form->{selectdepartment} .=
192         "<option>$_->{description}--$_->{id}\n"
193     } (@{ $form->{all_departments} || [] });
194   }
195
196   $form->{employee} = "$form->{employee}--$form->{employee_id}";
197
198   # sales staff
199   if (@{ $form->{all_employees} || [] }) {
200     $form->{selectemployee} = "";
201     map { $form->{selectemployee} .= "<option>$_->{name}--$_->{id}\n" }
202       (@{ $form->{all_employees} || [] });
203   }
204
205   # build the popup menus
206   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
207
208   AR->setup_form($form);
209
210   $form->{locked} =
211     ($form->datetonum($form->{transdate}, \%myconfig) <=
212      $form->datetonum($form->{closedto}, \%myconfig));
213
214   $main::lxdebug->leave_sub();
215 }
216
217 sub form_header {
218   $main::lxdebug->enter_sub();
219
220   $main::auth->assert('general_ledger');
221
222   my $form     = $main::form;
223   my %myconfig = %main::myconfig;
224   my $locale   = $main::locale;
225   my $cgi      = $::request->{cgi};
226
227   $form->{invoice_obj} = _retrieve_invoice_object();
228
229   my ($title, $readonly, $exchangerate, $rows);
230   my ($notes, $department, $customer, $employee, $amount, $project);
231   my ($ARselected);
232
233
234   $title = $form->{title};
235   # $locale->text('Add Accounts Receivables Transaction')
236   # $locale->text('Edit Accounts Receivables Transaction')
237   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
238
239   $form->{javascript} = qq|<script type="text/javascript">
240   <!--
241   function setTaxkey(accno, row) {
242     var taxkey = accno.options[accno.selectedIndex].value;
243     var reg = /--([0-9]*)/;
244     var found = reg.exec(taxkey);
245     var index = found[1];
246     index = parseInt(index);
247     var tax = 'taxchart_' + row;
248     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
249       var reg2 = new RegExp("^"+ index, "");
250       if (reg2.exec(document.getElementById(tax).options[i].value)) {
251         document.getElementById(tax).options[i].selected = true;
252         break;
253       }
254     }
255   };
256   //-->
257   </script>|;
258   # show history button js
259   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
260   #/show history button js
261   $readonly = ($form->{id}) ? "readonly" : "";
262
263   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
264                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
265                       : ($::instance_conf->get_ar_changeable == 1);
266   $readonly = ($form->{radier}) ? "" : $readonly;
267
268   # set option selected
269   foreach my $item (qw(customer currency department employee)) {
270     $form->{"select$item"} =~ s/ selected//;
271     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
272   }
273
274   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
275   $form->{exchangerate} = $form->{forex} if $form->{forex};
276
277   $rows = max 2, $form->numtextrows($form->{notes}, 50);
278
279   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
280
281   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
282                                     "all"       => 0,
283                                     "old_id"    => \@old_project_ids },
284                    "charts"    => { "key"       => "ALL_CHARTS",
285                                     "transdate" => $form->{transdate} },
286                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
287                                     "module"    => "AR" },);
288
289   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
290
291   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
292
293   my (@AR_amount_values);
294   my (@AR_values);
295   my (@AR_paid_values);
296   my %chart_labels;
297   my %charts;
298   my $taxchart_init;
299
300   foreach my $item (@{ $form->{ALL_CHARTS} }) {
301     if ($item->{link_split}{AR_amount}) {
302       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
303       my $key = "$item->{accno}--$item->{tax_id}";
304       push(@AR_amount_values, $key);
305     } elsif ($item->{link_split}{AR}) {
306       push(@AR_values, $item->{accno});
307     } elsif ($item->{link_split}{AR_paid}) {
308       push(@AR_paid_values, $item->{accno});
309     }
310
311     # weirdness for AR_amount
312     $chart_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
313     $chart_labels{"$item->{accno}--$item->{tax_id}"} = "$item->{accno}--$item->{description}";
314
315     $charts{$item->{accno}} = $item;
316   }
317
318   my %taxchart_labels = ();
319   my @taxchart_values = ();
320   my %taxcharts = ();
321   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
322     my $key = "$item->{id}--$item->{rate}";
323     $taxchart_init = $key if ($taxchart_init eq $item->{id});
324     push(@taxchart_values, $key);
325     $taxchart_labels{$key} = "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
326     $taxcharts{$item->{id}} = $item;
327   }
328
329   my $follow_up_vc         =  $form->{customer};
330   $follow_up_vc            =~ s/--.*?//;
331   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
332
333   $form->{javascript} .=
334     qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
335     qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
336
337 #  $amount  = $locale->text('Amount');
338 #  $project = $locale->text('Project');
339
340   my @transactions;
341   for my $i (1 .. $form->{rowcount}) {
342     my $transaction = {
343       amount     => $form->{"amount_$i"},
344       tax        => $form->{"tax_$i"},
345       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
346     };
347
348     my $selected_accno_full;
349     my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
350     my $item = $charts{$accno_row};
351     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
352
353     my $selected_taxchart = $form->{"taxchart_$i"};
354     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
355     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AR_amount_$i"});
356
357     if ($previous_accno &&
358         ($previous_accno eq $selected_accno) &&
359         ($previous_tax_id ne $selected_tax_id)) {
360       my $item = $taxcharts{$selected_tax_id};
361       $selected_taxchart = "$item->{id}--$item->{rate}";
362     }
363
364     if (!$form->{"taxchart_$i"}) {
365       if ($form->{"AR_amount_$i"} =~ m/.--./) {
366         $selected_taxchart = join '--', map { ($_->{id}, $_->{rate}) } first { $_->{id} == $item->{tax_id} } @{ $form->{ALL_TAXCHARTS} };
367       } else {
368         $selected_taxchart = $taxchart_init;
369       }
370     }
371
372     $transaction->{selectAR_amount} =
373       NTI($cgi->popup_menu('-name' => "AR_amount_$i",
374                            '-id' => "AR_amount_$i",
375                            '-style' => 'width:400px',
376                            '-onChange' => "setTaxkey(this, $i)",
377                            '-values' => \@AR_amount_values,
378                            '-labels' => \%chart_labels,
379                            '-default' => $selected_accno_full))
380       . $cgi->hidden('-name' => "previous_AR_amount_$i",
381                      '-default' => $selected_accno_full);
382
383     $transaction->{taxchart} =
384       NTI($cgi->popup_menu('-name' => "taxchart_$i",
385                            '-id' => "taxchart_$i",
386                            '-style' => 'width:200px',
387                            '-values' => \@taxchart_values,
388                            '-labels' => \%taxchart_labels,
389                            '-default' => $selected_taxchart));
390
391     push @transactions, $transaction;
392   }
393
394   $form->{invtotal_unformatted} = $form->{invtotal};
395
396   $ARselected =
397     NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
398                          '-style' => 'width:400px',
399                          '-values' => \@AR_values, '-labels' => \%chart_labels,
400                          '-default' => $form->{ARselected}));
401
402
403   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
404
405   my $now = $form->current_date(\%myconfig);
406
407   my @payments;
408   for my $i (1 .. $form->{paidaccounts}) {
409     my $payment = {
410       paid             => $form->{"paid_$i"},
411       exchangerate     => $form->{"exchangerate_$i"} || '',
412       gldate           => $form->{"gldate_$i"},
413       acc_trans_id     => $form->{"acc_trans_id_$i"},
414       source           => $form->{"source_$i"},
415       memo             => $form->{"memo_$i"},
416       AR_paid          => $form->{"AR_paid_$i"},
417       forex            => $form->{"forex_$i"},
418       datepaid         => $form->{"datepaid_$i"},
419       paid_project_id  => $form->{"paid_project_id_$i"},
420       gldate           => $form->{"gldate_$i"},
421     };
422
423     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
424     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
425
426     $payment->{selectAR_paid} =
427       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
428                            '-id' => "AR_paid_$i",
429                            '-values' => \@AR_paid_values,
430                            '-labels' => \%chart_labels,
431                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
432
433
434
435     $payment->{changeable} =
436         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
437       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
438       :                                                           1;
439
440     push @payments, $payment;
441   }
442
443   my @empty = grep { $_->{paid} eq '' } @payments;
444   @payments = (
445     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
446     @empty,
447   );
448
449   $form->{totalpaid} = sum map { $_->{paid} } @payments;
450
451   $form->header;
452   print $::form->parse_html_template('ar/form_header', {
453     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
454     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
455     payments             => \@payments,
456     transactions         => \@transactions,
457     project_labels       => \%project_labels,
458     rows                 => $rows,
459     ARselected           => $ARselected,
460     title_str            => $title,
461     follow_up_trans_info => $follow_up_trans_info,
462     today                => DateTime->today,
463   });
464
465   $main::lxdebug->leave_sub();
466 }
467
468 sub form_footer {
469   $main::lxdebug->enter_sub();
470
471   $main::auth->assert('general_ledger');
472
473   my $form     = $main::form;
474   my %myconfig = %main::myconfig;
475   my $locale   = $main::locale;
476   my $cgi      = $::request->{cgi};
477
478   if ( $form->{id} ) {
479     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
480     if ( @{ $follow_ups} ) {
481       $form->{follow_up_length} = scalar(@{$follow_ups});
482       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
483     }
484   }
485
486   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
487   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
488
489   $form->{is_closed} = $transdate <= $closedto;
490
491   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
492   $form->{show_storno_button} =
493     $form->{id} &&
494     !IS->has_storno(\%myconfig, $form, 'ar') &&
495     !IS->is_storno(\%myconfig, $form, 'ar') &&
496     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
497
498   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
499
500   print $::form->parse_html_template('ar/form_footer');
501
502   $main::lxdebug->leave_sub();
503 }
504
505 sub mark_as_paid {
506   $main::lxdebug->enter_sub();
507
508   $main::auth->assert('general_ledger');
509
510   my $form     = $main::form;
511   my %myconfig = %main::myconfig;
512
513   &mark_as_paid_common(\%myconfig,"ar");
514
515   $main::lxdebug->leave_sub();
516 }
517
518 sub update {
519   $main::lxdebug->enter_sub();
520
521   $main::auth->assert('general_ledger');
522
523   my $form     = $main::form;
524   my %myconfig = %main::myconfig;
525
526   my $display = shift;
527
528   my ($totaltax, $exchangerate);
529
530   $form->{invtotal} = 0;
531
532   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
533
534   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
535     qw(exchangerate creditlimit creditremaining);
536
537   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
538   my $count = 0;
539   my @a     = ();
540
541   for my $i (1 .. $form->{rowcount}) {
542     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
543     if ($form->{"amount_$i"}) {
544       push @a, {};
545       my $j = $#a;
546       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
547
548       my $tmpnetamount;
549       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
550
551       $totaltax += $form->{"tax_$i"};
552       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
553       $count++;
554     }
555   }
556
557   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
558   $form->{rowcount} = $count + 1;
559   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
560
561   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
562   $form->{exchangerate} = $form->{forex} if $form->{forex};
563
564   $form->{invdate} = $form->{transdate};
565
566   $form->{invdate} = $form->{transdate};
567
568   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id notes);
569
570   &check_name("customer");
571
572   $form->{AR} = $saved_variables{AR};
573   if ($saved_variables{AR_amount_1} =~ m/.--./) {
574     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
575   } else {
576     delete $form->{taxchart_1};
577   }
578
579   $form->{invtotal} =
580     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
581
582   for my $i (1 .. $form->{paidaccounts}) {
583     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
584       map {
585         $form->{"${_}_$i"} =
586           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
587       } qw(paid exchangerate);
588
589       $form->{totalpaid} += $form->{"paid_$i"};
590
591       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
592       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
593     }
594   }
595
596   $form->{creditremaining} -=
597     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
598      $form->{oldinvtotal});
599   $form->{oldinvtotal}  = $form->{invtotal};
600   $form->{oldtotalpaid} = $form->{totalpaid};
601
602   &display_form;
603
604   $main::lxdebug->leave_sub();
605 }
606
607 #
608 # ToDO: fix $closedto and $invdate
609 #
610 sub post_payment {
611   $main::lxdebug->enter_sub();
612
613   $main::auth->assert('general_ledger');
614
615   my $form     = $main::form;
616   my %myconfig = %main::myconfig;
617   my $locale   = $main::locale;
618
619   $form->mtime_ischanged('ar');
620   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
621
622   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
623
624   for my $i (1 .. $form->{paidaccounts}) {
625
626     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
627       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
628
629       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
630
631       $form->error($locale->text('Cannot post payment for a closed period!')) if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
632
633       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
634 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
635         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
636       }
637     }
638   }
639
640   ($form->{AR})      = split /--/, $form->{AR};
641   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
642   if (AR->post_payment(\%myconfig, \%$form)) {
643     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
644     $form->{what_done} = 'invoice';
645     $form->{addition}  = "PAYMENT POSTED";
646     $form->save_history;
647     $form->redirect($locale->text('Payment posted!'))
648   } else {
649     $form->error($locale->text('Cannot post payment!'));
650   };
651
652   $main::lxdebug->leave_sub();
653 }
654
655 sub _post {
656
657   $main::auth->assert('general_ledger');
658
659   my $form     = $main::form;
660
661   # inline post
662   post(1);
663 }
664
665 sub post {
666   $main::lxdebug->enter_sub();
667
668   $main::auth->assert('general_ledger');
669
670   my $form     = $main::form;
671   my %myconfig = %main::myconfig;
672   my $locale   = $main::locale;
673
674   my ($inline) = @_;
675
676   $form->mtime_ischanged('ar');
677
678   my ($datepaid);
679
680   # check if there is an invoice number, invoice and due date
681   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
682   $form->isblank("duedate",   $locale->text('Due Date missing!'));
683   $form->isblank("customer",  $locale->text('Customer missing!'));
684
685   if ($myconfig{mandatory_departments} && !$form->{department}) {
686     $form->{saved_message} = $::locale->text('You have to specify a department.');
687     update();
688     exit;
689   }
690
691   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
692   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
693
694   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
695     if ($form->date_max_future($transdate, \%myconfig));
696   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
697
698   $form->error($locale->text('Zero amount posting!'))
699     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
700
701   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
702     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
703
704   delete($form->{AR});
705
706   for my $i (1 .. $form->{paidaccounts}) {
707     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
708       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
709
710       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
711
712       $form->error($locale->text('Cannot post payment for a closed period!'))
713         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
714
715       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
716         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
717         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
718       }
719     }
720   }
721
722   # if oldcustomer ne customer redo form
723   my ($customer) = split /--/, $form->{customer};
724   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
725     update();
726     $::dispatcher->end_request;
727   }
728
729   $form->{AR}{receivables} = $form->{ARselected};
730   $form->{storno}          = 0;
731
732   $form->{id} = 0 if $form->{postasnew};
733   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
734
735   # saving the history
736   if(!exists $form->{addition} && $form->{id} ne "") {
737     $form->{snumbers}  = "invnumber_$form->{invnumber}";
738     $form->{what_done} = "invoice";
739     $form->{addition}  = "POSTED";
740     $form->save_history;
741   }
742   # /saving the history
743   remove_draft() if $form->{remove_draft};
744
745   $form->redirect($locale->text('Transaction posted!')) unless $inline;
746
747   $main::lxdebug->leave_sub();
748 }
749
750 sub post_as_new {
751   $main::lxdebug->enter_sub();
752
753   $main::auth->assert('general_ledger');
754
755   my $form     = $main::form;
756   my %myconfig = %main::myconfig;
757
758   $form->{postasnew} = 1;
759   # saving the history
760   if(!exists $form->{addition} && $form->{id} ne "") {
761     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
762     $form->{what_done} = "invoice";
763     $form->{addition}  = "POSTED AS NEW";
764     $form->save_history;
765   }
766   # /saving the history
767   &post;
768
769   $main::lxdebug->leave_sub();
770 }
771
772 sub use_as_new {
773   $main::lxdebug->enter_sub();
774
775   $main::auth->assert('general_ledger');
776
777   my $form     = $main::form;
778   my %myconfig = %main::myconfig;
779
780   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
781   $form->{paidaccounts} = 1;
782   $form->{rowcount}--;
783   $form->{invdate} = $form->current_date(\%myconfig);
784   &update;
785
786   $main::lxdebug->leave_sub();
787 }
788
789 sub delete {
790   $main::lxdebug->enter_sub();
791
792   $main::auth->assert('general_ledger');
793
794   my $form     = $main::form;
795   my $locale   = $main::locale;
796
797   $form->{title} = $locale->text('Confirm!');
798
799   $form->header;
800
801   delete $form->{header};
802
803   print qq|
804 <form method=post action=$form->{script}>
805 |;
806
807   foreach my $key (keys %$form) {
808     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
809     $form->{$key} =~ s/\"/&quot;/g;
810     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
811   }
812
813   print qq|
814 <h2 class=confirm>$form->{title}</h2>
815
816 <h4>|
817     . $locale->text('Are you sure you want to delete Transaction')
818     . qq| $form->{invnumber}</h4>
819
820 <input name=action class=submit type=submit value="|
821     . $locale->text('Yes') . qq|">
822 </form>
823 |;
824
825   $main::lxdebug->leave_sub();
826 }
827
828 sub yes {
829   $main::lxdebug->enter_sub();
830
831   $main::auth->assert('general_ledger');
832
833   my $form     = $main::form;
834   my %myconfig = %main::myconfig;
835   my $locale   = $main::locale;
836
837   if (AR->delete_transaction(\%myconfig, \%$form)) {
838     # saving the history
839     if(!exists $form->{addition}) {
840       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
841       $form->{what_done} = "invoice";
842       $form->{addition}  = "DELETED";
843       $form->save_history;
844     }
845     # /saving the history
846     $form->redirect($locale->text('Transaction deleted!'));
847   }
848   $form->error($locale->text('Cannot delete transaction!'));
849
850   $main::lxdebug->leave_sub();
851 }
852
853 sub search {
854   $main::lxdebug->enter_sub();
855
856   $main::auth->assert('invoice_edit');
857
858   my $form     = $main::form;
859   my %myconfig = %main::myconfig;
860   my $locale   = $main::locale;
861   my $cgi      = $::request->{cgi};
862
863   # setup customer selection
864   $form->all_vc(\%myconfig, "customer", "AR");
865
866   $form->{title}    = $locale->text('AR Transactions');
867
868   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
869   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
870                    "departments"    => "ALL_DEPARTMENTS",
871                    "customers"      => "ALL_VC",
872                    "business_types" => "ALL_BUSINESS_TYPES");
873   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
874   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
875
876   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
877   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
878    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
879                                                                               'include_prefix' => 'l_',
880                                                                               'include_value'  => 'Y');
881
882   # constants and subs for template
883   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
884
885   $form->header;
886   print $form->parse_html_template('ar/search', { %myconfig });
887
888   $main::lxdebug->leave_sub();
889 }
890
891 sub create_subtotal_row {
892   $main::lxdebug->enter_sub();
893
894   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
895
896   my $form     = $main::form;
897   my %myconfig = %main::myconfig;
898
899   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
900
901   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
902
903   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
904
905   map { $totals->{$_} = 0 } @{ $subtotal_columns };
906
907   $main::lxdebug->leave_sub();
908
909   return $row;
910 }
911
912 sub ar_transactions {
913   $main::lxdebug->enter_sub();
914
915   $main::auth->assert('invoice_edit');
916
917   my $form     = $main::form;
918   my %myconfig = %main::myconfig;
919   my $locale   = $main::locale;
920
921   my ($callback, $href, @columns);
922
923   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
924
925   report_generator_set_default_sort('transdate', 1);
926
927   AR->ar_transactions(\%myconfig, \%$form);
928
929   $form->{title} = $locale->text('AR Transactions');
930
931   my $report = SL::ReportGenerator->new(\%myconfig, $form);
932
933   @columns =
934     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
935        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
936        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone payment_terms charts customertype direct_debit dunning_description);
937
938   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
939   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
940   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
941
942   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
943   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
944
945   my @hidden_variables = map { "l_${_}" } @columns;
946   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
947                                            employee_id salesman_id business_id parts_partnumber parts_description);
948   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
949
950   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
951
952   my %column_defs = (
953     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
954     'transdate'               => { 'text' => $locale->text('Date'), },
955     'id'                      => { 'text' => $locale->text('ID'), },
956     'type'                    => { 'text' => $locale->text('Type'), },
957     'invnumber'               => { 'text' => $locale->text('Invoice'), },
958     'ordnumber'               => { 'text' => $locale->text('Order'), },
959     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
960     'name'                    => { 'text' => $locale->text('Customer'), },
961     'netamount'               => { 'text' => $locale->text('Amount'), },
962     'tax'                     => { 'text' => $locale->text('Tax'), },
963     'amount'                  => { 'text' => $locale->text('Total'), },
964     'paid'                    => { 'text' => $locale->text('Paid'), },
965     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
966     'due'                     => { 'text' => $locale->text('Amount Due'), },
967     'duedate'                 => { 'text' => $locale->text('Due Date'), },
968     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
969     'notes'                   => { 'text' => $locale->text('Notes'), },
970     'salesman'                => { 'text' => $locale->text('Salesperson'), },
971     'employee'                => { 'text' => $locale->text('Employee'), },
972     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
973     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
974     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
975     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
976     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
977     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
978     'country'                 => { 'text' => $locale->text('Country'), },
979     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
980     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
981     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
982     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
983     'customertype'            => { 'text' => $locale->text('Customer type'), },
984     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
985     dunning_description       => { 'text' => $locale->text('Dunning level'), },
986     %column_defs_cvars,
987   );
988
989   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
990     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
991     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
992   }
993
994   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
995
996   $form->{"l_type"} = "Y";
997   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
998
999   $column_defs{ids}->{visible} = 'HTML';
1000
1001   $report->set_columns(%column_defs);
1002   $report->set_column_order(@columns);
1003
1004   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1005
1006   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1007
1008   CVar->add_custom_variables_to_report('module'         => 'CT',
1009                                        'trans_id_field' => 'customer_id',
1010                                        'configs'        => $ct_cvar_configs,
1011                                        'column_defs'    => \%column_defs,
1012                                        'data'           => $form->{AR});
1013
1014   my @options;
1015   if ($form->{customer}) {
1016     push @options, $locale->text('Customer') . " : $form->{customer}";
1017   }
1018   if ($form->{cp_name}) {
1019     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1020   }
1021   if ($form->{department}) {
1022     my ($department) = split /--/, $form->{department};
1023     push @options, $locale->text('Department') . " : $department";
1024   }
1025   if ($form->{department_id}) {
1026     push @options, $locale->text('Department Id') . " : $form->{department_id}";
1027   }
1028   if ($form->{invnumber}) {
1029     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1030   }
1031   if ($form->{ordnumber}) {
1032     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1033   }
1034   if ($form->{cusordnumber}) {
1035     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1036   }
1037   if ($form->{notes}) {
1038     push @options, $locale->text('Notes') . " : $form->{notes}";
1039   }
1040   if ($form->{transaction_description}) {
1041     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1042   }
1043   if ($form->{parts_partnumber}) {
1044     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1045   }
1046   if ($form->{parts_description}) {
1047     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1048   }
1049   if ($form->{transdatefrom}) {
1050     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1051   }
1052   if ($form->{transdateto}) {
1053     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1054   }
1055   if ($form->{open}) {
1056     push @options, $locale->text('Open');
1057   }
1058   if ($form->{employee_id}) {
1059     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1060     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1061   }
1062   if ($form->{salesman_id}) {
1063     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1064     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1065   }
1066   if ($form->{closed}) {
1067     push @options, $locale->text('Closed');
1068   }
1069
1070   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1071
1072   $report->set_options('top_info_text'        => join("\n", @options),
1073                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1074                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1075                        'output_format'        => 'HTML',
1076                        'title'                => $form->{title},
1077                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1078     );
1079   $report->set_options_from_form();
1080   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1081
1082   # add sort and escape callback, this one we use for the add sub
1083   $form->{callback} = $href .= "&sort=$form->{sort}";
1084
1085   # escape callback for href
1086   $callback = $form->escape($href);
1087
1088   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1089
1090   my %totals    = map { $_ => 0 } @subtotal_columns;
1091   my %subtotals = map { $_ => 0 } @subtotal_columns;
1092
1093   my $idx = 0;
1094
1095   foreach my $ar (@{ $form->{AR} }) {
1096     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1097     $ar->{due} = $ar->{amount} - $ar->{paid};
1098
1099     map { $subtotals{$_} += $ar->{$_};
1100           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1101
1102     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1103     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1104
1105     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1106
1107     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1108     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1109
1110     $ar->{type} =
1111       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1112       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1113       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1114       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1115                           $locale->text("AR Transaction (abbreviation)");
1116
1117     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1118
1119     my $row = { };
1120
1121     foreach my $column (@columns) {
1122       $row->{$column} = {
1123         'data'  => $ar->{$column},
1124         'align' => $column_alignment{$column},
1125       };
1126     }
1127
1128     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1129       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1130
1131     $row->{ids} = {
1132       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1133       valign   => 'center',
1134       align    => 'center',
1135     };
1136
1137     my $row_set = [ $row ];
1138
1139     if (($form->{l_subtotal} eq 'Y')
1140         && (($idx == (scalar @{ $form->{AR} } - 1))
1141             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1142       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1143     }
1144
1145     $report->add_data($row_set);
1146
1147     $idx++;
1148   }
1149
1150   $report->add_separator();
1151   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1152
1153   $report->generate_with_headers();
1154
1155   $main::lxdebug->leave_sub();
1156 }
1157
1158 sub storno {
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   # don't cancel cancelled transactions
1168   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1169     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1170     $form->error($locale->text("Transaction has already been cancelled!"));
1171   }
1172
1173   AR->storno($form, \%myconfig, $form->{id});
1174
1175   # saving the history
1176   if(!exists $form->{addition} && $form->{id} ne "") {
1177     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1178     $form->{addition}  = "STORNO";
1179     $form->{what_done} = "invoice";
1180     $form->save_history;
1181   }
1182   # /saving the history
1183
1184   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1185
1186   $main::lxdebug->leave_sub();
1187 }
1188
1189 1;