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