fix FSF address
[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., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Accounts Receivables
32 #
33 #======================================================================
34
35 use POSIX qw(strftime);
36 use List::Util qw(sum first max);
37 use List::UtilsBy qw(sort_by);
38
39 use SL::AR;
40 use SL::FU;
41 use SL::IS;
42 use SL::PE;
43 use SL::DB::Default;
44 use SL::DB::Invoice;
45 use SL::ReportGenerator;
46
47 require "bin/mozilla/arap.pl";
48 require "bin/mozilla/common.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('ar_transactions');
86
87   my $form     = $main::form;
88   my %myconfig = %main::myconfig;
89
90   # saving the history
91   if(!exists $form->{addition} && ($form->{id} ne "")) {
92     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
93     $form->{addition} = "ADDED";
94     $form->save_history;
95   }
96   # /saving the history
97
98   $form->{title}    = "Add";
99   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
100
101   AR->get_transdate(\%myconfig, $form);
102   $form->{initial_transdate} = $form->{transdate};
103   create_links(dont_save => 1);
104   $form->{transdate} = $form->{initial_transdate};
105   &display_form;
106   $main::lxdebug->leave_sub();
107 }
108
109 sub edit {
110   $main::lxdebug->enter_sub();
111
112   $main::auth->assert('ar_transactions');
113
114   my $form     = $main::form;
115
116   # show history button
117   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
118   #/show hhistory button
119   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
120   $form->{title} = "Edit";
121
122   create_links();
123   &display_form;
124
125   $main::lxdebug->leave_sub();
126 }
127
128 sub display_form {
129   $main::lxdebug->enter_sub();
130
131   $main::auth->assert('ar_transactions');
132
133   my $form     = $main::form;
134
135   &form_header;
136   &form_footer;
137
138   $main::lxdebug->leave_sub();
139 }
140
141 sub _retrieve_invoice_object {
142   return undef if !$::form->{id};
143   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
144   return SL::DB::Invoice->new(id => $::form->{id})->load;
145 }
146
147 sub create_links {
148   $main::lxdebug->enter_sub();
149
150   $main::auth->assert('ar_transactions');
151
152   my %params   = @_;
153   my $form     = $main::form;
154   my %myconfig = %main::myconfig;
155
156   $form->create_links("AR", \%myconfig, "customer");
157   $form->{invoice_obj} = _retrieve_invoice_object();
158
159   my %saved;
160   if (!$params{dont_save}) {
161     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
162     $saved{duedate} = $form->{duedate} if $form->{duedate};
163     $saved{currency} = $form->{currency} if $form->{currency};
164   }
165
166   IS->get_customer(\%myconfig, \%$form);
167
168   $form->{$_}          = $saved{$_} for keys %saved;
169   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
170   $form->{rowcount}    = 1;
171
172   # currencies
173   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
174
175   $form->{selectcurrency} = "";
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('ar_transactions');
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   # format exchangerate
278   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
279
280   $rows = max 2, $form->numtextrows($form->{notes}, 50);
281
282   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
283
284   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
285                                     "all"       => 0,
286                                     "old_id"    => \@old_project_ids },
287                    "charts"    => { "key"       => "ALL_CHARTS",
288                                     "transdate" => $form->{transdate} },
289                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
290                                     "module"    => "AR" },);
291
292   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
293
294   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
295
296   my (@AR_amount_values);
297   my (@AR_values);
298   my (@AR_paid_values);
299   my %chart_labels;
300   my %charts;
301   my $taxchart_init;
302
303   foreach my $item (@{ $form->{ALL_CHARTS} }) {
304     if ($item->{link_split}{AR_amount}) {
305       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
306       my $key = "$item->{accno}--$item->{tax_id}";
307       push(@AR_amount_values, $key);
308     } elsif ($item->{link_split}{AR}) {
309       push(@AR_values, $item->{accno});
310     } elsif ($item->{link_split}{AR_paid}) {
311       push(@AR_paid_values, $item->{accno});
312     }
313
314     # weirdness for AR_amount
315     $chart_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
316     $chart_labels{"$item->{accno}--$item->{tax_id}"} = "$item->{accno}--$item->{description}";
317
318     $charts{$item->{accno}} = $item;
319   }
320
321   my %taxchart_labels = ();
322   my @taxchart_values = ();
323   my %taxcharts = ();
324   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
325     my $key = "$item->{id}--$item->{rate}";
326     $taxchart_init = $key if ($taxchart_init eq $item->{id});
327     push(@taxchart_values, $key);
328     $taxchart_labels{$key} = "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
329     $taxcharts{$item->{id}} = $item;
330   }
331
332   my $follow_up_vc         =  $form->{customer};
333   $follow_up_vc            =~ s/--.*?//;
334   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
335
336   $form->{javascript} .=
337     qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
338     qq|<script type="text/javascript" src="js/follow_up.js"></script>| .
339     qq|<script type="text/javascript" src="js/kivi.Draft.js"></script>|;
340
341 #  $amount  = $locale->text('Amount');
342 #  $project = $locale->text('Project');
343
344   my @transactions;
345   for my $i (1 .. $form->{rowcount}) {
346     my $transaction = {
347       amount     => $form->{"amount_$i"},
348       tax        => $form->{"tax_$i"},
349       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
350     };
351
352     my $selected_accno_full;
353     my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
354     my $item = $charts{$accno_row};
355     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
356
357     my $selected_taxchart = $form->{"taxchart_$i"};
358     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
359     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AR_amount_$i"});
360
361     if ($previous_accno &&
362         ($previous_accno eq $selected_accno) &&
363         ($previous_tax_id ne $selected_tax_id)) {
364       my $item = $taxcharts{$selected_tax_id};
365       $selected_taxchart = "$item->{id}--$item->{rate}";
366     }
367
368     if (!$form->{"taxchart_$i"}) {
369       if ($form->{"AR_amount_$i"} =~ m/.--./) {
370         $selected_taxchart = join '--', map { ($_->{id}, $_->{rate}) } first { $_->{id} == $item->{tax_id} } @{ $form->{ALL_TAXCHARTS} };
371       } else {
372         $selected_taxchart = $taxchart_init;
373       }
374     }
375
376     $transaction->{selectAR_amount} =
377       NTI($cgi->popup_menu('-name' => "AR_amount_$i",
378                            '-id' => "AR_amount_$i",
379                            '-style' => 'width:400px',
380                            '-onChange' => "setTaxkey(this, $i)",
381                            '-values' => \@AR_amount_values,
382                            '-labels' => \%chart_labels,
383                            '-default' => $selected_accno_full))
384       . $cgi->hidden('-name' => "previous_AR_amount_$i",
385                      '-default' => $selected_accno_full);
386
387     $transaction->{taxchart} =
388       NTI($cgi->popup_menu('-name' => "taxchart_$i",
389                            '-id' => "taxchart_$i",
390                            '-style' => 'width:200px',
391                            '-values' => \@taxchart_values,
392                            '-labels' => \%taxchart_labels,
393                            '-default' => $selected_taxchart));
394
395     push @transactions, $transaction;
396   }
397
398   $form->{invtotal_unformatted} = $form->{invtotal};
399
400   $ARselected =
401     NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
402                          '-style' => 'width:400px',
403                          '-values' => \@AR_values, '-labels' => \%chart_labels,
404                          '-default' => $form->{ARselected}));
405
406
407   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
408
409   my $now = $form->current_date(\%myconfig);
410
411   my @payments;
412   for my $i (1 .. $form->{paidaccounts}) {
413     my $payment = {
414       paid             => $form->{"paid_$i"},
415       exchangerate     => $form->{"exchangerate_$i"} || '',
416       gldate           => $form->{"gldate_$i"},
417       acc_trans_id     => $form->{"acc_trans_id_$i"},
418       source           => $form->{"source_$i"},
419       memo             => $form->{"memo_$i"},
420       AR_paid          => $form->{"AR_paid_$i"},
421       forex            => $form->{"forex_$i"},
422       datepaid         => $form->{"datepaid_$i"},
423       paid_project_id  => $form->{"paid_project_id_$i"},
424       gldate           => $form->{"gldate_$i"},
425     };
426
427     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
428     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
429
430     $payment->{selectAR_paid} =
431       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
432                            '-id' => "AR_paid_$i",
433                            '-values' => \@AR_paid_values,
434                            '-labels' => \%chart_labels,
435                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
436
437
438
439     $payment->{changeable} =
440         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
441       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
442       :                                                           1;
443
444     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
445     if ($form->date_closed($payment->{"gldate_$i"})) {
446         $payment->{changeable} = 0;
447     }
448
449     push @payments, $payment;
450   }
451
452   my @empty = grep { $_->{paid} eq '' } @payments;
453   @payments = (
454     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
455     @empty,
456   );
457
458   $form->{totalpaid} = sum map { $_->{paid} } @payments;
459
460   $form->header;
461   print $::form->parse_html_template('ar/form_header', {
462     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
463     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
464     payments             => \@payments,
465     transactions         => \@transactions,
466     project_labels       => \%project_labels,
467     rows                 => $rows,
468     ARselected           => $ARselected,
469     title_str            => $title,
470     follow_up_trans_info => $follow_up_trans_info,
471     today                => DateTime->today,
472   });
473
474   $main::lxdebug->leave_sub();
475 }
476
477 sub form_footer {
478   $main::lxdebug->enter_sub();
479
480   $main::auth->assert('ar_transactions');
481
482   my $form     = $main::form;
483   my %myconfig = %main::myconfig;
484   my $locale   = $main::locale;
485   my $cgi      = $::request->{cgi};
486
487   if ( $form->{id} ) {
488     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
489     if ( @{ $follow_ups} ) {
490       $form->{follow_up_length} = scalar(@{$follow_ups});
491       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
492     }
493   }
494
495   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
496   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
497
498   $form->{is_closed} = $transdate <= $closedto;
499
500   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
501   $form->{show_storno_button} =
502     $form->{id} &&
503     !IS->has_storno(\%myconfig, $form, 'ar') &&
504     !IS->is_storno(\%myconfig, $form, 'ar') &&
505     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
506
507   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
508
509   print $::form->parse_html_template('ar/form_footer');
510
511   $main::lxdebug->leave_sub();
512 }
513
514 sub mark_as_paid {
515   $main::lxdebug->enter_sub();
516
517   $main::auth->assert('ar_transactions');
518
519   my $form     = $main::form;
520   my %myconfig = %main::myconfig;
521
522   &mark_as_paid_common(\%myconfig,"ar");
523
524   $main::lxdebug->leave_sub();
525 }
526
527 sub update {
528   $main::lxdebug->enter_sub();
529
530   $main::auth->assert('ar_transactions');
531
532   my $form     = $main::form;
533   my %myconfig = %main::myconfig;
534
535   my $display = shift;
536
537   my ($totaltax, $exchangerate);
538
539   $form->{invtotal} = 0;
540
541   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
542
543   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
544     qw(exchangerate creditlimit creditremaining);
545
546   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
547   my $count = 0;
548   my @a     = ();
549
550   for my $i (1 .. $form->{rowcount}) {
551     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
552     if ($form->{"amount_$i"}) {
553       push @a, {};
554       my $j = $#a;
555       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
556
557       my $tmpnetamount;
558       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
559
560       $totaltax += $form->{"tax_$i"};
561       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
562       $count++;
563     }
564   }
565
566   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
567   $form->{rowcount} = $count + 1;
568   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
569
570   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
571   $form->{exchangerate} = $form->{forex} if $form->{forex};
572
573   $form->{invdate} = $form->{transdate};
574
575   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id notes);
576
577   &check_name("customer");
578
579   $form->{AR} = $saved_variables{AR};
580   if ($saved_variables{AR_amount_1} =~ m/.--./) {
581     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
582   } else {
583     delete $form->{taxchart_1};
584   }
585
586   $form->{invtotal} =
587     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
588
589   for my $i (1 .. $form->{paidaccounts}) {
590     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
591       map {
592         $form->{"${_}_$i"} =
593           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
594       } qw(paid exchangerate);
595
596       $form->{totalpaid} += $form->{"paid_$i"};
597
598       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
599       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
600     }
601   }
602
603   $form->{creditremaining} -=
604     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
605      $form->{oldinvtotal});
606   $form->{oldinvtotal}  = $form->{invtotal};
607   $form->{oldtotalpaid} = $form->{totalpaid};
608
609   &display_form;
610
611   $main::lxdebug->leave_sub();
612 }
613
614 #
615 # ToDO: fix $closedto and $invdate
616 #
617 sub post_payment {
618   $main::lxdebug->enter_sub();
619
620   $main::auth->assert('ar_transactions');
621
622   my $form     = $main::form;
623   my %myconfig = %main::myconfig;
624   my $locale   = $main::locale;
625
626   $form->mtime_ischanged('ar');
627   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
628
629   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
630
631   for my $i (1 .. $form->{paidaccounts}) {
632
633     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
634       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
635
636       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
637
638       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
639         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
640
641       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
642       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
643       $form->error($locale->text('Cannot post payment for a closed period!'))
644         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
645
646       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
647 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
648         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
649       }
650     }
651   }
652
653   ($form->{AR})      = split /--/, $form->{AR};
654   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
655   if (AR->post_payment(\%myconfig, \%$form)) {
656     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
657     $form->{what_done} = 'invoice';
658     $form->{addition}  = "PAYMENT POSTED";
659     $form->save_history;
660     $form->redirect($locale->text('Payment posted!'))
661   } else {
662     $form->error($locale->text('Cannot post payment!'));
663   };
664
665   $main::lxdebug->leave_sub();
666 }
667
668 sub _post {
669
670   $main::auth->assert('ar_transactions');
671
672   my $form     = $main::form;
673
674   # inline post
675   post(1);
676 }
677
678 sub post {
679   $main::lxdebug->enter_sub();
680
681   $main::auth->assert('ar_transactions');
682
683   my $form     = $main::form;
684   my %myconfig = %main::myconfig;
685   my $locale   = $main::locale;
686
687   my ($inline) = @_;
688
689   $form->mtime_ischanged('ar');
690
691   my ($datepaid);
692
693   # check if there is an invoice number, invoice and due date
694   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
695   $form->isblank("duedate",   $locale->text('Due Date missing!'));
696   $form->isblank("customer",  $locale->text('Customer missing!'));
697
698   if ($myconfig{mandatory_departments} && !$form->{department}) {
699     $form->{saved_message} = $::locale->text('You have to specify a department.');
700     update();
701     exit;
702   }
703
704   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
705   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
706
707   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
708     if ($form->date_max_future($transdate, \%myconfig));
709
710   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
711
712   $form->error($locale->text('Zero amount posting!'))
713     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
714
715   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
716     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
717
718   delete($form->{AR});
719
720   for my $i (1 .. $form->{paidaccounts}) {
721     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
722       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
723
724       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
725
726       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
727         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
728
729       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
730       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
731       $form->error($locale->text('Cannot post payment for a closed period!'))
732         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
733
734       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
735         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
736         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
737       }
738     }
739   }
740
741   # if oldcustomer ne customer redo form
742   my ($customer) = split /--/, $form->{customer};
743   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
744     update();
745     $::dispatcher->end_request;
746   }
747
748   $form->{AR}{receivables} = $form->{ARselected};
749   $form->{storno}          = 0;
750
751   $form->{id} = 0 if $form->{postasnew};
752   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
753
754   # saving the history
755   if(!exists $form->{addition} && $form->{id} ne "") {
756     $form->{snumbers}  = "invnumber_$form->{invnumber}";
757     $form->{what_done} = "invoice";
758     $form->{addition}  = "POSTED";
759     $form->save_history;
760   }
761   # /saving the history
762
763   $form->redirect($locale->text('Transaction posted!')) unless $inline;
764
765   $main::lxdebug->leave_sub();
766 }
767
768 sub post_as_new {
769   $main::lxdebug->enter_sub();
770
771   $main::auth->assert('ar_transactions');
772
773   my $form     = $main::form;
774   my %myconfig = %main::myconfig;
775
776   $form->{postasnew} = 1;
777   # saving the history
778   if(!exists $form->{addition} && $form->{id} ne "") {
779     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
780     $form->{what_done} = "invoice";
781     $form->{addition}  = "POSTED AS NEW";
782     $form->save_history;
783   }
784   # /saving the history
785   &post;
786
787   $main::lxdebug->leave_sub();
788 }
789
790 sub use_as_new {
791   $main::lxdebug->enter_sub();
792
793   $main::auth->assert('ar_transactions');
794
795   my $form     = $main::form;
796   my %myconfig = %main::myconfig;
797
798   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);
799   $form->{paidaccounts} = 1;
800   $form->{rowcount}--;
801   $form->{invdate} = $form->current_date(\%myconfig);
802   &update;
803
804   $main::lxdebug->leave_sub();
805 }
806
807 sub delete {
808   $main::lxdebug->enter_sub();
809
810   $main::auth->assert('ar_transactions');
811
812   my $form     = $main::form;
813   my $locale   = $main::locale;
814
815   $form->{title} = $locale->text('Confirm!');
816
817   $form->header;
818
819   delete $form->{header};
820
821   print qq|
822 <form method=post action=$form->{script}>
823 |;
824
825   foreach my $key (keys %$form) {
826     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
827     $form->{$key} =~ s/\"/&quot;/g;
828     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
829   }
830
831   print qq|
832 <h2 class=confirm>$form->{title}</h2>
833
834 <h4>|
835     . $locale->text('Are you sure you want to delete Transaction')
836     . qq| $form->{invnumber}</h4>
837
838 <input name=action class=submit type=submit value="|
839     . $locale->text('Yes') . qq|">
840 </form>
841 |;
842
843   $main::lxdebug->leave_sub();
844 }
845
846 sub yes {
847   $main::lxdebug->enter_sub();
848
849   $main::auth->assert('ar_transactions');
850
851   my $form     = $main::form;
852   my %myconfig = %main::myconfig;
853   my $locale   = $main::locale;
854
855   if (AR->delete_transaction(\%myconfig, \%$form)) {
856     # saving the history
857     if(!exists $form->{addition}) {
858       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
859       $form->{what_done} = "invoice";
860       $form->{addition}  = "DELETED";
861       $form->save_history;
862     }
863     # /saving the history
864     $form->redirect($locale->text('Transaction deleted!'));
865   }
866   $form->error($locale->text('Cannot delete transaction!'));
867
868   $main::lxdebug->leave_sub();
869 }
870
871 sub search {
872   $main::lxdebug->enter_sub();
873
874   $main::auth->assert('invoice_edit');
875
876   my $form     = $main::form;
877   my %myconfig = %main::myconfig;
878   my $locale   = $main::locale;
879   my $cgi      = $::request->{cgi};
880
881   # setup customer selection
882   $form->all_vc(\%myconfig, "customer", "AR");
883
884   $form->{title}    = $locale->text('AR Transactions');
885
886   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
887   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
888                    "departments"    => "ALL_DEPARTMENTS",
889                    "customers"      => "ALL_VC",
890                    "business_types" => "ALL_BUSINESS_TYPES");
891   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
892   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
893
894   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
895   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
896    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
897                                                                               'include_prefix' => 'l_',
898                                                                               'include_value'  => 'Y');
899
900   # constants and subs for template
901   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
902
903   $form->header;
904   print $form->parse_html_template('ar/search', { %myconfig });
905
906   $main::lxdebug->leave_sub();
907 }
908
909 sub create_subtotal_row {
910   $main::lxdebug->enter_sub();
911
912   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
913
914   my $form     = $main::form;
915   my %myconfig = %main::myconfig;
916
917   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
918
919   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
920
921   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
922
923   map { $totals->{$_} = 0 } @{ $subtotal_columns };
924
925   $main::lxdebug->leave_sub();
926
927   return $row;
928 }
929
930 sub ar_transactions {
931   $main::lxdebug->enter_sub();
932
933   $main::auth->assert('invoice_edit');
934
935   my $form     = $main::form;
936   my %myconfig = %main::myconfig;
937   my $locale   = $main::locale;
938
939   my ($callback, $href, @columns);
940
941   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
942
943   report_generator_set_default_sort('transdate', 1);
944
945   AR->ar_transactions(\%myconfig, \%$form);
946
947   $form->{title} = $locale->text('AR Transactions');
948
949   my $report = SL::ReportGenerator->new(\%myconfig, $form);
950
951   @columns =
952     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
953        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
954        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
955        payment_terms charts customertype direct_debit dunning_description department);
956
957   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
958   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
959   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
960
961   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
962   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
963
964   my @hidden_variables = map { "l_${_}" } @columns;
965   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
966                                            employee_id salesman_id business_id parts_partnumber parts_description department_id);
967   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
968
969   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
970
971   my %column_defs = (
972     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
973     'transdate'               => { 'text' => $locale->text('Date'), },
974     'id'                      => { 'text' => $locale->text('ID'), },
975     'type'                    => { 'text' => $locale->text('Type'), },
976     'invnumber'               => { 'text' => $locale->text('Invoice'), },
977     'ordnumber'               => { 'text' => $locale->text('Order'), },
978     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
979     'name'                    => { 'text' => $locale->text('Customer'), },
980     'netamount'               => { 'text' => $locale->text('Amount'), },
981     'tax'                     => { 'text' => $locale->text('Tax'), },
982     'amount'                  => { 'text' => $locale->text('Total'), },
983     'paid'                    => { 'text' => $locale->text('Paid'), },
984     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
985     'due'                     => { 'text' => $locale->text('Amount Due'), },
986     'duedate'                 => { 'text' => $locale->text('Due Date'), },
987     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
988     'notes'                   => { 'text' => $locale->text('Notes'), },
989     'salesman'                => { 'text' => $locale->text('Salesperson'), },
990     'employee'                => { 'text' => $locale->text('Employee'), },
991     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
992     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
993     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
994     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
995     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
996     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
997     'country'                 => { 'text' => $locale->text('Country'), },
998     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
999     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1000     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1001     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1002     'customertype'            => { 'text' => $locale->text('Customer type'), },
1003     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1004     'department'              => { 'text' => $locale->text('Department'), },
1005     dunning_description       => { 'text' => $locale->text('Dunning level'), },
1006     %column_defs_cvars,
1007   );
1008
1009   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1010     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1011     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1012   }
1013
1014   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1015
1016   $form->{"l_type"} = "Y";
1017   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1018
1019   $column_defs{ids}->{visible} = 'HTML';
1020
1021   $report->set_columns(%column_defs);
1022   $report->set_column_order(@columns);
1023
1024   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1025
1026   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1027
1028   CVar->add_custom_variables_to_report('module'         => 'CT',
1029                                        'trans_id_field' => 'customer_id',
1030                                        'configs'        => $ct_cvar_configs,
1031                                        'column_defs'    => \%column_defs,
1032                                        'data'           => $form->{AR});
1033
1034   my @options;
1035   if ($form->{customer}) {
1036     push @options, $locale->text('Customer') . " : $form->{customer}";
1037   }
1038   if ($form->{cp_name}) {
1039     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1040   }
1041
1042   # $form->{department} seems to never be filled, and showing the department_id
1043   # at the top of the report doesn't make much sense.
1044   # So determine the department name from the id whenever we have a filter for
1045   # department
1046   if ($form->{department}) {
1047     my ($department) = split /--/, $form->{department};
1048     push @options, $locale->text('Department') . " : $department";
1049   }
1050   if ($form->{department_id}) {
1051     # push @options, $locale->text('Department Id') . " : $form->{department_id}";
1052     unless ($form->{department}) {
1053       require SL::DB::Department;
1054       my $department = SL::DB::Manager::Department->find_by(id => $::form->{department_id});
1055       push @options, $locale->text('Department') . " : " . $department->description if $department;
1056     }
1057   }
1058   if ($form->{invnumber}) {
1059     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1060   }
1061   if ($form->{ordnumber}) {
1062     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1063   }
1064   if ($form->{cusordnumber}) {
1065     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1066   }
1067   if ($form->{notes}) {
1068     push @options, $locale->text('Notes') . " : $form->{notes}";
1069   }
1070   if ($form->{transaction_description}) {
1071     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1072   }
1073   if ($form->{parts_partnumber}) {
1074     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1075   }
1076   if ($form->{parts_description}) {
1077     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1078   }
1079   if ($form->{transdatefrom}) {
1080     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1081   }
1082   if ($form->{transdateto}) {
1083     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1084   }
1085   if ($form->{open}) {
1086     push @options, $locale->text('Open');
1087   }
1088   if ($form->{employee_id}) {
1089     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1090     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1091   }
1092   if ($form->{salesman_id}) {
1093     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1094     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1095   }
1096   if ($form->{closed}) {
1097     push @options, $locale->text('Closed');
1098   }
1099
1100   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1101
1102   $report->set_options('top_info_text'        => join("\n", @options),
1103                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1104                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1105                        'output_format'        => 'HTML',
1106                        'title'                => $form->{title},
1107                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1108     );
1109   $report->set_options_from_form();
1110   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1111
1112   # add sort and escape callback, this one we use for the add sub
1113   $form->{callback} = $href .= "&sort=$form->{sort}";
1114
1115   # escape callback for href
1116   $callback = $form->escape($href);
1117
1118   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1119
1120   my %totals    = map { $_ => 0 } @subtotal_columns;
1121   my %subtotals = map { $_ => 0 } @subtotal_columns;
1122
1123   my $idx = 0;
1124
1125   foreach my $ar (@{ $form->{AR} }) {
1126     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1127     $ar->{due} = $ar->{amount} - $ar->{paid};
1128
1129     map { $subtotals{$_} += $ar->{$_};
1130           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1131
1132     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1133     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1134
1135     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1136     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1137
1138     $ar->{type} =
1139       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1140       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1141       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1142       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1143                           $locale->text("AR Transaction (abbreviation)");
1144
1145     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1146
1147     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1148
1149     my $row = { };
1150
1151     foreach my $column (@columns) {
1152       $row->{$column} = {
1153         'data'  => $ar->{$column},
1154         'align' => $column_alignment{$column},
1155       };
1156     }
1157
1158     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1159       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1160
1161     $row->{ids} = {
1162       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1163       valign   => 'center',
1164       align    => 'center',
1165     };
1166
1167     my $row_set = [ $row ];
1168
1169     if (($form->{l_subtotal} eq 'Y')
1170         && (($idx == (scalar @{ $form->{AR} } - 1))
1171             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1172       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1173     }
1174
1175     $report->add_data($row_set);
1176
1177     $idx++;
1178   }
1179
1180   $report->add_separator();
1181   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1182
1183   $report->generate_with_headers();
1184
1185   $main::lxdebug->leave_sub();
1186 }
1187
1188 sub storno {
1189   $main::lxdebug->enter_sub();
1190
1191   $main::auth->assert('ar_transactions');
1192
1193   my $form     = $main::form;
1194   my %myconfig = %main::myconfig;
1195   my $locale   = $main::locale;
1196
1197   # don't cancel cancelled transactions
1198   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1199     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1200     $form->error($locale->text("Transaction has already been cancelled!"));
1201   }
1202
1203   AR->storno($form, \%myconfig, $form->{id});
1204
1205   # saving the history
1206   if(!exists $form->{addition} && $form->{id} ne "") {
1207     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1208     $form->{addition}  = "STORNO";
1209     $form->{what_done} = "invoice";
1210     $form->save_history;
1211   }
1212   # /saving the history
1213
1214   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1215
1216   $main::lxdebug->leave_sub();
1217 }
1218
1219 1;