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