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