a4f559034fd11c4af2ce055d78e3df8ed8a7ef92
[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::Controller::Base;
41 use SL::FU;
42 use SL::GL;
43 use SL::IS;
44 use SL::DB::Business;
45 use SL::DB::Chart;
46 use SL::DB::Currency;
47 use SL::DB::Default;
48 use SL::DB::Employee;
49 use SL::DB::Invoice;
50 use SL::DB::RecordTemplate;
51 use SL::DB::Tax;
52 use SL::Helper::Flash qw(flash);
53 use SL::ReportGenerator;
54
55 require "bin/mozilla/common.pl";
56 require "bin/mozilla/reportgenerator.pl";
57
58 use strict;
59 #use warnings;
60
61 # this is for our long dates
62 # $locale->text('January')
63 # $locale->text('February')
64 # $locale->text('March')
65 # $locale->text('April')
66 # $locale->text('May ')
67 # $locale->text('June')
68 # $locale->text('July')
69 # $locale->text('August')
70 # $locale->text('September')
71 # $locale->text('October')
72 # $locale->text('November')
73 # $locale->text('December')
74
75 # this is for our short month
76 # $locale->text('Jan')
77 # $locale->text('Feb')
78 # $locale->text('Mar')
79 # $locale->text('Apr')
80 # $locale->text('May')
81 # $locale->text('Jun')
82 # $locale->text('Jul')
83 # $locale->text('Aug')
84 # $locale->text('Sep')
85 # $locale->text('Oct')
86 # $locale->text('Nov')
87 # $locale->text('Dec')
88
89 sub load_record_template {
90   $::auth->assert('ar_transactions');
91
92   # Load existing template and verify that its one for this module.
93   my $template = SL::DB::RecordTemplate
94     ->new(id => $::form->{id})
95     ->load(
96       with_object => [ qw(customer payment currency record_items record_items.chart) ],
97     );
98
99   die "invalid template type" unless $template->template_type eq 'ar_transaction';
100
101   $template->substitute_variables;
102
103   # Clean the current $::form before rebuilding it from the template.
104   my $form_defaults = delete $::form->{form_defaults};
105   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
106
107   # Fill $::form from the template.
108   my $today                   = DateTime->today_local;
109   $::form->{title}            = "Add";
110   $::form->{currency}         = $template->currency->name;
111   $::form->{direct_debit}     = $template->direct_debit;
112   $::form->{globalproject_id} = $template->project_id;
113   $::form->{AR_chart_id}      = $template->ar_ap_chart_id;
114   $::form->{transdate}        = $today->to_kivitendo;
115   $::form->{duedate}          = $today->to_kivitendo;
116   $::form->{rowcount}         = @{ $template->items };
117   $::form->{paidaccounts}     = 1;
118   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded employee_id notes);
119
120   if ($template->customer) {
121     $::form->{customer_id} = $template->customer_id;
122     $::form->{customer}    = $template->customer->name;
123     $::form->{duedate}     = $template->customer->payment->calc_date(reference_date => $today)->to_kivitendo if $template->customer->payment;
124   }
125
126   my $row = 0;
127   foreach my $item (@{ $template->items }) {
128     $row++;
129
130     my $active_taxkey = $item->chart->get_active_taxkey;
131     my $taxes         = SL::DB::Manager::Tax->get_all(
132       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
133       sort_by => 'taxkey, rate',
134     );
135
136     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
137     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
138     $tax    //= $taxes->[0];
139
140     if (!$tax) {
141       $row--;
142       next;
143     }
144
145     $::form->{"AR_amount_chart_id_${row}"}          = $item->chart_id;
146     $::form->{"previous_AR_amount_chart_id_${row}"} = $item->chart_id;
147     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
148     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
149     $::form->{"project_id_${row}"}                  = $item->project_id;
150   }
151
152   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
153
154   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
155
156   update(
157     keep_rows_without_amount => 1,
158     dont_add_new_row         => 1,
159   );
160 }
161
162 sub save_record_template {
163   $::auth->assert('ar_transactions');
164
165   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
166   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
167   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
168
169   $js->dialog->close('#record_template_dialog');
170
171   my @items = grep {
172     $_->{chart_id} && (($_->{tax_id} // '') ne '')
173   } map {
174     +{ chart_id   => $::form->{"AR_amount_chart_id_${_}"},
175        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
176        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
177        project_id => $::form->{"project_id_${_}"} || undef,
178      }
179   } (1..($::form->{rowcount} || 1));
180
181   $template->assign_attributes(
182     template_type  => 'ar_transaction',
183     template_name  => $new_name,
184
185     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
186     ar_ap_chart_id => $::form->{AR_chart_id}      || undef,
187     customer_id    => $::form->{customer_id}      || undef,
188     department_id  => $::form->{department_id}    || undef,
189     project_id     => $::form->{globalproject_id} || undef,
190     employee_id    => $::form->{employee_id}      || undef,
191     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
192     direct_debit   => $::form->{direct_debit} ? 1 : 0,
193     ordnumber      => $::form->{ordnumber},
194     notes          => $::form->{notes},
195
196     items          => \@items,
197   );
198
199   eval {
200     $template->save;
201     1;
202   } or do {
203     return $js
204       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
205       ->render;
206   };
207
208   return $js
209     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
210     ->render;
211 }
212
213 sub add {
214   $main::lxdebug->enter_sub();
215
216   $main::auth->assert('ar_transactions');
217
218   my $form     = $main::form;
219   my %myconfig = %main::myconfig;
220
221   # saving the history
222   if(!exists $form->{addition} && ($form->{id} ne "")) {
223     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
224     $form->{addition} = "ADDED";
225     $form->save_history;
226   }
227   # /saving the history
228
229   $form->{title}    = "Add";
230   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
231
232   AR->get_transdate(\%myconfig, $form);
233   $form->{initial_transdate} = $form->{transdate};
234   create_links(dont_save => 1);
235   $form->{transdate} = $form->{initial_transdate};
236
237   if ($form->{customer_id}) {
238     my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
239     $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
240   }
241
242   &display_form;
243   $main::lxdebug->leave_sub();
244 }
245
246 sub edit {
247   $main::lxdebug->enter_sub();
248
249   $main::auth->assert('ar_transactions');
250
251   my $form     = $main::form;
252
253   # show history button
254   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
255   #/show hhistory button
256   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
257   $form->{title} = "Edit";
258
259   create_links();
260   &display_form;
261
262   $main::lxdebug->leave_sub();
263 }
264
265 sub display_form {
266   $main::lxdebug->enter_sub();
267
268   $main::auth->assert('ar_transactions');
269
270   my $form     = $main::form;
271
272   &form_header;
273   &form_footer;
274
275   $main::lxdebug->leave_sub();
276 }
277
278 sub _retrieve_invoice_object {
279   return undef if !$::form->{id};
280   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
281   return SL::DB::Invoice->new(id => $::form->{id})->load;
282 }
283
284 sub create_links {
285   $main::lxdebug->enter_sub();
286
287   $main::auth->assert('ar_transactions');
288
289   my %params   = @_;
290   my $form     = $main::form;
291   my %myconfig = %main::myconfig;
292
293   $form->create_links("AR", \%myconfig, "customer");
294   $form->{invoice_obj} = _retrieve_invoice_object();
295
296   my %saved;
297   if (!$params{dont_save}) {
298     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
299     $saved{duedate} = $form->{duedate} if $form->{duedate};
300     $saved{currency} = $form->{currency} if $form->{currency};
301   }
302
303   IS->get_customer(\%myconfig, \%$form);
304
305   $form->{$_}          = $saved{$_} for keys %saved;
306   $form->{rowcount}    = 1;
307   $form->{AR_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AR} ? $form->{acc_trans}->{AR}->[0]->{chart_id} : $form->{AR_links}->{AR}->[0]->{chart_id};
308
309   # currencies
310   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
311
312   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
313
314   # build the popup menus
315   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
316
317   AR->setup_form($form);
318
319   $form->{locked} =
320     ($form->datetonum($form->{transdate}, \%myconfig) <=
321      $form->datetonum($form->{closedto}, \%myconfig));
322
323   $main::lxdebug->leave_sub();
324 }
325
326 sub form_header {
327   $main::lxdebug->enter_sub();
328
329   $main::auth->assert('ar_transactions');
330
331   my $form     = $main::form;
332   my %myconfig = %main::myconfig;
333   my $locale   = $main::locale;
334   my $cgi      = $::request->{cgi};
335
336   $form->{invoice_obj} = _retrieve_invoice_object();
337
338   my ($title, $readonly, $exchangerate, $rows);
339   my ($notes, $amount, $project);
340
341   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
342
343   $title = $form->{title};
344   # $locale->text('Add Accounts Receivables Transaction')
345   # $locale->text('Edit Accounts Receivables Transaction')
346   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
347
348   $readonly = ($form->{id}) ? "readonly" : "";
349
350   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
351                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
352                       : ($::instance_conf->get_ar_changeable == 1);
353   $readonly = ($form->{radier}) ? "" : $readonly;
354
355   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
356   $form->{exchangerate} = $form->{forex} if $form->{forex};
357
358   # format exchangerate
359   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
360
361   $rows = max 2, $form->numtextrows($form->{notes}, 50);
362
363   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
364
365   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
366                                     "all"       => 0,
367                                     "old_id"    => \@old_project_ids },
368                    "charts"    => { "key"       => "ALL_CHARTS",
369                                     "transdate" => $form->{transdate} },
370                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
371                                     "module"    => "AR" },);
372
373   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
374
375   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
376
377   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
378
379   my (@AR_paid_values, %AR_paid_labels);
380   my $default_ar_amount_chart_id;
381
382   foreach my $item (@{ $form->{ALL_CHARTS} }) {
383     if ($item->{link_split}{AR_amount}) {
384       $default_ar_amount_chart_id //= $item->{id};
385
386     } elsif ($item->{link_split}{AR_paid}) {
387       push(@AR_paid_values, $item->{accno});
388       $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
389     }
390   }
391
392   my $follow_up_vc         = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
393   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
394
395   $::request->layout->add_javascripts("autocomplete_chart.js", "autocomplete_customer.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.File.js", "kivi.RecordTemplate.js");
396
397   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
398   my $first_taxchart;
399
400   my @transactions;
401   for my $i (1 .. $form->{rowcount}) {
402     my $transaction = {
403       amount     => $form->{"amount_$i"},
404       tax        => $form->{"tax_$i"},
405       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
406     };
407
408     my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
409     my $amount_chart_id   = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
410     my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
411
412     foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
413       my $key             = $item->id . "--" . $item->rate;
414       $first_taxchart   //= $item;
415       $default_taxchart   = $item if $item->{is_default};
416       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
417
418       push(@taxchart_values, $key);
419       $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
420     }
421
422     $taxchart_to_use      = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
423     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
424
425     $transaction->{selectAR_amount} =
426         $::request->presenter->chart_picker("AR_amount_chart_id_$i", $amount_chart_id, style => "width: 400px", type => "AR_amount", class => ($form->{initial_focus} eq "row_$i" ? "initial_focus" : ""))
427       . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
428
429     $transaction->{taxchart} =
430       NTI($cgi->popup_menu('-name' => "taxchart_$i",
431                            '-id' => "taxchart_$i",
432                            '-style' => 'width:200px',
433                            '-values' => \@taxchart_values,
434                            '-labels' => \%taxchart_labels,
435                            '-default' => $selected_taxchart));
436
437     push @transactions, $transaction;
438   }
439
440   $form->{invtotal_unformatted} = $form->{invtotal};
441
442   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
443
444   my $now = $form->current_date(\%myconfig);
445
446   my @payments;
447   for my $i (1 .. $form->{paidaccounts}) {
448     my $payment = {
449       paid             => $form->{"paid_$i"},
450       exchangerate     => $form->{"exchangerate_$i"} || '',
451       gldate           => $form->{"gldate_$i"},
452       acc_trans_id     => $form->{"acc_trans_id_$i"},
453       source           => $form->{"source_$i"},
454       memo             => $form->{"memo_$i"},
455       AR_paid          => $form->{"AR_paid_$i"},
456       forex            => $form->{"forex_$i"},
457       datepaid         => $form->{"datepaid_$i"},
458       paid_project_id  => $form->{"paid_project_id_$i"},
459       gldate           => $form->{"gldate_$i"},
460     };
461
462     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
463     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
464
465     $payment->{selectAR_paid} =
466       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
467                            '-id' => "AR_paid_$i",
468                            '-values' => \@AR_paid_values,
469                            '-labels' => \%AR_paid_labels,
470                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
471
472
473
474     $payment->{changeable} =
475         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
476       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
477       :                                                           1;
478
479     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
480     if ($form->date_closed($payment->{"gldate_$i"})) {
481         $payment->{changeable} = 0;
482     }
483
484     push @payments, $payment;
485   }
486
487   my @empty = grep { $_->{paid} eq '' } @payments;
488   @payments = (
489     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
490     @empty,
491   );
492
493   $form->{totalpaid} = sum map { $_->{paid} } @payments;
494
495   my $employees = SL::DB::Manager::Employee->get_all_sorted(
496     where => [
497       or => [
498         (id     => $::form->{employee_id}) x !!$::form->{employee_id},
499         deleted => undef,
500         deleted => 0,
501       ],
502     ],
503   );
504
505   $form->header;
506   print $::form->parse_html_template('ar/form_header', {
507     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
508     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
509     payments             => \@payments,
510     transactions         => \@transactions,
511     project_labels       => \%project_labels,
512     rows                 => $rows,
513     AR_chart_id          => $form->{AR_chart_id},
514     title_str            => $title,
515     follow_up_trans_info => $follow_up_trans_info,
516     today                => DateTime->today,
517     currencies           => scalar(SL::DB::Manager::Currency->get_all_sorted),
518     employees            => $employees,
519   });
520
521   $main::lxdebug->leave_sub();
522 }
523
524 sub form_footer {
525   $main::lxdebug->enter_sub();
526
527   $main::auth->assert('ar_transactions');
528
529   my $form     = $main::form;
530   my %myconfig = %main::myconfig;
531   my $locale   = $main::locale;
532   my $cgi      = $::request->{cgi};
533
534   if ( $form->{id} ) {
535     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
536     if ( @{ $follow_ups} ) {
537       $form->{follow_up_length} = scalar(@{$follow_ups});
538       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
539     }
540   }
541
542   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
543   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
544
545   $form->{is_closed} = $transdate <= $closedto;
546
547   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
548   $form->{show_storno_button} =
549     $form->{id} &&
550     !IS->has_storno(\%myconfig, $form, 'ar') &&
551     !IS->is_storno(\%myconfig, $form, 'ar') &&
552     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
553
554   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
555
556   print $::form->parse_html_template('ar/form_footer');
557
558   $main::lxdebug->leave_sub();
559 }
560
561 sub mark_as_paid {
562   $::auth->assert('ar_transactions');
563
564   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
565
566   $::form->redirect($::locale->text("Marked as paid"));
567 }
568
569 sub show_draft {
570   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
571   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
572   update();
573 }
574
575 sub update {
576   my %params = @_;
577   $main::lxdebug->enter_sub();
578
579   $main::auth->assert('ar_transactions');
580
581   my $form     = $main::form;
582   my %myconfig = %main::myconfig;
583
584   my $display = shift;
585
586   my ($totaltax, $exchangerate);
587
588   $form->{invtotal} = 0;
589
590   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
591
592   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
593     qw(exchangerate creditlimit creditremaining);
594
595   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
596   my $count = 0;
597   my @a     = ();
598
599   for my $i (1 .. $form->{rowcount}) {
600     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
601     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
602       push @a, {};
603       my $j = $#a;
604       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
605
606       my $tmpnetamount;
607       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
608
609       $totaltax += $form->{"tax_$i"};
610       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
611       $count++;
612     }
613   }
614
615   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
616   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
617   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
618
619   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
620   $form->{exchangerate} = $form->{forex} if $form->{forex};
621
622   $form->{invdate} = $form->{transdate};
623
624   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
625     IS->get_customer(\%myconfig, $form);
626   }
627
628   $form->{invtotal} =
629     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
630
631   for my $i (1 .. $form->{paidaccounts}) {
632     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
633       map {
634         $form->{"${_}_$i"} =
635           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
636       } qw(paid exchangerate);
637
638       $form->{totalpaid} += $form->{"paid_$i"};
639
640       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
641       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
642     }
643   }
644
645   $form->{creditremaining} -=
646     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
647      $form->{oldinvtotal});
648   $form->{oldinvtotal}  = $form->{invtotal};
649   $form->{oldtotalpaid} = $form->{totalpaid};
650
651   display_form();
652
653   $main::lxdebug->leave_sub();
654 }
655
656 #
657 # ToDO: fix $closedto and $invdate
658 #
659 sub post_payment {
660   $main::lxdebug->enter_sub();
661
662   $main::auth->assert('ar_transactions');
663
664   my $form     = $main::form;
665   my %myconfig = %main::myconfig;
666   my $locale   = $main::locale;
667
668   $form->mtime_ischanged('ar');
669   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
670
671   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
672
673   for my $i (1 .. $form->{paidaccounts}) {
674
675     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
676       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
677
678       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
679
680       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
681         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
682
683       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
684       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
685       $form->error($locale->text('Cannot post payment for a closed period!'))
686         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
687
688       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
689 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
690         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
691       }
692     }
693   }
694
695   ($form->{AR})      = split /--/, $form->{AR};
696   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
697   if (AR->post_payment(\%myconfig, \%$form)) {
698     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
699     $form->{what_done} = 'invoice';
700     $form->{addition}  = "PAYMENT POSTED";
701     $form->save_history;
702     $form->redirect($locale->text('Payment posted!'))
703   } else {
704     $form->error($locale->text('Cannot post payment!'));
705   };
706
707   $main::lxdebug->leave_sub();
708 }
709
710 sub _post {
711
712   $main::auth->assert('ar_transactions');
713
714   my $form     = $main::form;
715
716   # inline post
717   post(1);
718 }
719
720 sub post {
721   $main::lxdebug->enter_sub();
722
723   $main::auth->assert('ar_transactions');
724
725   my $form     = $main::form;
726   my %myconfig = %main::myconfig;
727   my $locale   = $main::locale;
728
729   my ($inline) = @_;
730
731   $form->mtime_ischanged('ar');
732
733   my ($datepaid);
734
735   # check if there is an invoice number, invoice and due date
736   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
737   $form->isblank("duedate",   $locale->text('Due Date missing!'));
738   $form->isblank("customer_id", $locale->text('Customer missing!'));
739
740   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
741     $form->{saved_message} = $::locale->text('You have to specify a department.');
742     update();
743     exit;
744   }
745
746   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
747   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
748
749   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
750     if ($form->date_max_future($transdate, \%myconfig));
751
752   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
753
754   $form->error($locale->text('Zero amount posting!'))
755     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
756
757   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
758     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
759
760   delete($form->{AR});
761
762   for my $i (1 .. $form->{paidaccounts}) {
763     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
764       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
765
766       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
767
768       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
769         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
770
771       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
772       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
773       $form->error($locale->text('Cannot post payment for a closed period!'))
774         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
775
776       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
777         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
778         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
779       }
780     }
781   }
782
783   # if oldcustomer ne customer redo form
784   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
785     update();
786     $::dispatcher->end_request;
787   }
788
789   $form->{AR}{receivables} = $form->{ARselected};
790   $form->{storno}          = 0;
791
792   $form->{id} = 0 if $form->{postasnew};
793   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
794
795   # saving the history
796   if(!exists $form->{addition} && $form->{id} ne "") {
797     $form->{snumbers}  = "invnumber_$form->{invnumber}";
798     $form->{what_done} = "invoice";
799     $form->{addition}  = "POSTED";
800     $form->save_history;
801   }
802   # /saving the history
803
804   $form->redirect($locale->text("AR transaction posted.")) unless $inline;
805
806   $main::lxdebug->leave_sub();
807 }
808
809 sub post_as_new {
810   $main::lxdebug->enter_sub();
811
812   $main::auth->assert('ar_transactions');
813
814   my $form     = $main::form;
815   my %myconfig = %main::myconfig;
816
817   $form->{postasnew} = 1;
818   # saving the history
819   if(!exists $form->{addition} && $form->{id} ne "") {
820     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
821     $form->{what_done} = "invoice";
822     $form->{addition}  = "POSTED AS NEW";
823     $form->save_history;
824   }
825   # /saving the history
826   &post;
827
828   $main::lxdebug->leave_sub();
829 }
830
831 sub use_as_new {
832   $main::lxdebug->enter_sub();
833
834   $main::auth->assert('ar_transactions');
835
836   my $form     = $main::form;
837   my %myconfig = %main::myconfig;
838
839   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);
840   $form->{paidaccounts} = 1;
841   $form->{rowcount}--;
842   $form->{invdate} = $form->current_date(\%myconfig);
843   &update;
844
845   $main::lxdebug->leave_sub();
846 }
847
848 sub delete {
849   $main::lxdebug->enter_sub();
850
851   $main::auth->assert('ar_transactions');
852
853   my $form     = $main::form;
854   my $locale   = $main::locale;
855
856   $form->{title} = $locale->text('Confirm!');
857
858   $form->header;
859
860   delete $form->{header};
861
862   print qq|
863 <form method=post action=$form->{script}>
864 |;
865
866   foreach my $key (keys %$form) {
867     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
868     $form->{$key} =~ s/\"/&quot;/g;
869     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
870   }
871
872   print qq|
873 <h2 class=confirm>$form->{title}</h2>
874
875 <h4>|
876     . $locale->text('Are you sure you want to delete Transaction')
877     . qq| $form->{invnumber}</h4>
878
879 <input name=action class=submit type=submit value="|
880     . $locale->text('Yes') . qq|">
881 </form>
882 |;
883
884   $main::lxdebug->leave_sub();
885 }
886
887 sub yes {
888   $main::lxdebug->enter_sub();
889
890   $main::auth->assert('ar_transactions');
891
892   my $form     = $main::form;
893   my %myconfig = %main::myconfig;
894   my $locale   = $main::locale;
895
896   if (AR->delete_transaction(\%myconfig, \%$form)) {
897     # saving the history
898     if(!exists $form->{addition}) {
899       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
900       $form->{what_done} = "invoice";
901       $form->{addition}  = "DELETED";
902       $form->save_history;
903     }
904     # /saving the history
905     $form->redirect($locale->text('Transaction deleted!'));
906   }
907   $form->error($locale->text('Cannot delete transaction!'));
908
909   $main::lxdebug->leave_sub();
910 }
911
912 sub setup_ar_search_action_bar {
913   my %params = @_;
914
915   for my $bar ($::request->layout->get('actionbar')) {
916     $bar->add(
917       action => [
918         $::locale->text('Search'),
919         submit    => [ '#form' ],
920         accesskey => 'enter',
921       ],
922     );
923   }
924 }
925
926 sub setup_ar_transactions_action_bar {
927   my %params = @_;
928
929   for my $bar ($::request->layout->get('actionbar')) {
930     $bar->add(
931       action => [
932         $::locale->text('Print'),
933         call     => [ 'kivi.MassInvoiceCreatePrint.showMassPrintOptionsOrDownloadDirectly' ],
934         disabled => !$params{num_rows} ? $::locale->text('The report doesn\'t contain entries.') : undef,
935       ],
936
937       combobox => [
938         action => [ $::locale->text('Create new') ],
939         action => [
940           $::locale->text('AR Transaction'),
941           submit => [ '#create_new_form', { action => 'ar_transaction' } ],
942         ],
943         action => [
944           $::locale->text('Sales Invoice'),
945           submit => [ '#create_new_form', { action => 'sales_invoice' } ],
946         ],
947       ], # end of combobox "Create new"
948     );
949   }
950 }
951
952 sub search {
953   $main::lxdebug->enter_sub();
954
955   $main::auth->assert('invoice_edit');
956
957   my $form     = $main::form;
958   my %myconfig = %main::myconfig;
959   my $locale   = $main::locale;
960   my $cgi      = $::request->{cgi};
961
962   $form->{title}    = $locale->text('AR Transactions');
963
964   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
965   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
966   $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business->get_all_sorted;
967
968   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
969   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
970    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
971                                                                               'include_prefix' => 'l_',
972                                                                               'include_value'  => 'Y');
973
974   # constants and subs for template
975   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
976
977   $::request->layout->add_javascripts("autocomplete_project.js");
978
979   setup_ar_search_action_bar();
980
981   $form->header;
982   print $form->parse_html_template('ar/search', { %myconfig });
983
984   $main::lxdebug->leave_sub();
985 }
986
987 sub create_subtotal_row {
988   $main::lxdebug->enter_sub();
989
990   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
991
992   my $form     = $main::form;
993   my %myconfig = %main::myconfig;
994
995   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
996
997   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
998
999   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1000
1001   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1002
1003   $main::lxdebug->leave_sub();
1004
1005   return $row;
1006 }
1007
1008 sub ar_transactions {
1009   $main::lxdebug->enter_sub();
1010
1011   $main::auth->assert('invoice_edit');
1012
1013   my $form     = $main::form;
1014   my %myconfig = %main::myconfig;
1015   my $locale   = $main::locale;
1016
1017   my ($callback, $href, @columns);
1018
1019   report_generator_set_default_sort('transdate', 1);
1020
1021   AR->ar_transactions(\%myconfig, \%$form);
1022
1023   $form->{title} = $locale->text('AR Transactions');
1024
1025   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1026
1027   @columns =
1028     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
1029        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
1030        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
1031        payment_terms charts customertype direct_debit dunning_description department);
1032
1033   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
1034   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
1035   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
1036
1037   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
1038   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
1039
1040   my @hidden_variables = map { "l_${_}" } @columns;
1041   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
1042                                            employee_id salesman_id business_id parts_partnumber parts_description department_id);
1043   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
1044
1045   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
1046
1047   my %column_defs = (
1048     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
1049     'transdate'               => { 'text' => $locale->text('Date'), },
1050     'id'                      => { 'text' => $locale->text('ID'), },
1051     'type'                    => { 'text' => $locale->text('Type'), },
1052     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1053     'ordnumber'               => { 'text' => $locale->text('Order'), },
1054     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
1055     'name'                    => { 'text' => $locale->text('Customer'), },
1056     'netamount'               => { 'text' => $locale->text('Amount'), },
1057     'tax'                     => { 'text' => $locale->text('Tax'), },
1058     'amount'                  => { 'text' => $locale->text('Total'), },
1059     'paid'                    => { 'text' => $locale->text('Paid'), },
1060     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1061     'due'                     => { 'text' => $locale->text('Amount Due'), },
1062     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1063     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1064     'notes'                   => { 'text' => $locale->text('Notes'), },
1065     'salesman'                => { 'text' => $locale->text('Salesperson'), },
1066     'employee'                => { 'text' => $locale->text('Employee'), },
1067     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
1068     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
1069     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1070     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
1071     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
1072     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
1073     'country'                 => { 'text' => $locale->text('Country'), },
1074     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1075     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1076     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1077     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1078     'customertype'            => { 'text' => $locale->text('Customer type'), },
1079     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1080     'department'              => { 'text' => $locale->text('Department'), },
1081     dunning_description       => { 'text' => $locale->text('Dunning level'), },
1082     %column_defs_cvars,
1083   );
1084
1085   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1086     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1087     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1088   }
1089
1090   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1091
1092   $form->{"l_type"} = "Y";
1093   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1094
1095   $column_defs{ids}->{visible} = 'HTML';
1096
1097   $report->set_columns(%column_defs);
1098   $report->set_column_order(@columns);
1099
1100   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1101
1102   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1103
1104   CVar->add_custom_variables_to_report('module'         => 'CT',
1105                                        'trans_id_field' => 'customer_id',
1106                                        'configs'        => $ct_cvar_configs,
1107                                        'column_defs'    => \%column_defs,
1108                                        'data'           => $form->{AR});
1109
1110   my @options;
1111   if ($form->{customer}) {
1112     push @options, $locale->text('Customer') . " : $form->{customer}";
1113   }
1114   if ($form->{cp_name}) {
1115     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1116   }
1117
1118   if ($form->{department_id}) {
1119     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
1120     push @options, $locale->text('Department') . " : " . $department->description;
1121   }
1122   if ($form->{invnumber}) {
1123     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1124   }
1125   if ($form->{ordnumber}) {
1126     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1127   }
1128   if ($form->{cusordnumber}) {
1129     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1130   }
1131   if ($form->{notes}) {
1132     push @options, $locale->text('Notes') . " : $form->{notes}";
1133   }
1134   if ($form->{transaction_description}) {
1135     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1136   }
1137   if ($form->{parts_partnumber}) {
1138     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1139   }
1140   if ($form->{parts_description}) {
1141     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1142   }
1143   if ($form->{transdatefrom}) {
1144     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1145   }
1146   if ($form->{transdateto}) {
1147     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1148   }
1149   if ($form->{open}) {
1150     push @options, $locale->text('Open');
1151   }
1152   if ($form->{employee_id}) {
1153     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1154     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1155   }
1156   if ($form->{salesman_id}) {
1157     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1158     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1159   }
1160   if ($form->{closed}) {
1161     push @options, $locale->text('Closed');
1162   }
1163
1164   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1165
1166   $report->set_options('top_info_text'        => join("\n", @options),
1167                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1168                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1169                        'output_format'        => 'HTML',
1170                        'title'                => $form->{title},
1171                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1172     );
1173   $report->set_options_from_form();
1174   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1175
1176   # add sort and escape callback, this one we use for the add sub
1177   $form->{callback} = $href .= "&sort=$form->{sort}";
1178
1179   # escape callback for href
1180   $callback = $form->escape($href);
1181
1182   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1183
1184   my %totals    = map { $_ => 0 } @subtotal_columns;
1185   my %subtotals = map { $_ => 0 } @subtotal_columns;
1186
1187   my $idx = 0;
1188
1189   foreach my $ar (@{ $form->{AR} }) {
1190     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1191     $ar->{due} = $ar->{amount} - $ar->{paid};
1192
1193     map { $subtotals{$_} += $ar->{$_};
1194           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1195
1196     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1197     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1198
1199     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1200     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1201
1202     $ar->{type} =
1203       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1204       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1205       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1206       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1207                           $locale->text("AR Transaction (abbreviation)");
1208
1209     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1210
1211     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1212
1213     my $row = { };
1214
1215     foreach my $column (@columns) {
1216       $row->{$column} = {
1217         'data'  => $ar->{$column},
1218         'align' => $column_alignment{$column},
1219       };
1220     }
1221
1222     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1223       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1224
1225     $row->{ids} = {
1226       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1227       valign   => 'center',
1228       align    => 'center',
1229     };
1230
1231     my $row_set = [ $row ];
1232
1233     if (($form->{l_subtotal} eq 'Y')
1234         && (($idx == (scalar @{ $form->{AR} } - 1))
1235             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1236       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1237     }
1238
1239     $report->add_data($row_set);
1240
1241     $idx++;
1242   }
1243
1244   $report->add_separator();
1245   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1246
1247   $::request->layout->add_javascripts('kivi.MassInvoiceCreatePrint.js');
1248   setup_ar_transactions_action_bar(num_rows => scalar(@{ $form->{AR} }));
1249
1250   $report->generate_with_headers(action_bar => 1);
1251
1252   $main::lxdebug->leave_sub();
1253 }
1254
1255 sub storno {
1256   $main::lxdebug->enter_sub();
1257
1258   $main::auth->assert('ar_transactions');
1259
1260   my $form     = $main::form;
1261   my %myconfig = %main::myconfig;
1262   my $locale   = $main::locale;
1263
1264   # don't cancel cancelled transactions
1265   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1266     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1267     $form->error($locale->text("Transaction has already been cancelled!"));
1268   }
1269
1270   AR->storno($form, \%myconfig, $form->{id});
1271
1272   # saving the history
1273   if(!exists $form->{addition} && $form->{id} ne "") {
1274     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1275     $form->{addition}  = "STORNO";
1276     $form->{what_done} = "invoice";
1277     $form->save_history;
1278   }
1279   # /saving the history
1280
1281   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1282
1283   $main::lxdebug->leave_sub();
1284 }
1285
1286 1;