Kreditoren/Debitoren-Buchung zuletzt bebuchtes Konto laden
[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;
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;
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", "autocomplete_customer.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.File.js", "kivi.RecordTemplate.js", "kivi.AR.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     my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
412
413     foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
414       my $key             = $item->id . "--" . $item->rate;
415       $first_taxchart   //= $item;
416       $default_taxchart   = $item if $item->{is_default};
417       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
418
419       push(@taxchart_values, $key);
420       $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
421     }
422
423     $taxchart_to_use      = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
424     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
425
426     $transaction->{selectAR_amount} =
427         $::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" : ""))
428       . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
429
430     $transaction->{taxchart} =
431       NTI($cgi->popup_menu('-name' => "taxchart_$i",
432                            '-id' => "taxchart_$i",
433                            '-style' => 'width:200px',
434                            '-values' => \@taxchart_values,
435                            '-labels' => \%taxchart_labels,
436                            '-default' => $selected_taxchart));
437
438     push @transactions, $transaction;
439   }
440
441   $form->{invtotal_unformatted} = $form->{invtotal};
442
443   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
444
445   my $now = $form->current_date(\%myconfig);
446
447   my @payments;
448   for my $i (1 .. $form->{paidaccounts}) {
449     my $payment = {
450       paid             => $form->{"paid_$i"},
451       exchangerate     => $form->{"exchangerate_$i"} || '',
452       gldate           => $form->{"gldate_$i"},
453       acc_trans_id     => $form->{"acc_trans_id_$i"},
454       source           => $form->{"source_$i"},
455       memo             => $form->{"memo_$i"},
456       AR_paid          => $form->{"AR_paid_$i"},
457       forex            => $form->{"forex_$i"},
458       datepaid         => $form->{"datepaid_$i"},
459       paid_project_id  => $form->{"paid_project_id_$i"},
460       gldate           => $form->{"gldate_$i"},
461     };
462
463     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
464     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
465
466     $payment->{selectAR_paid} =
467       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
468                            '-id' => "AR_paid_$i",
469                            '-values' => \@AR_paid_values,
470                            '-labels' => \%AR_paid_labels,
471                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
472
473
474
475     $payment->{changeable} =
476         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
477       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
478       :                                                           1;
479
480     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
481     if ($form->date_closed($payment->{"gldate_$i"})) {
482         $payment->{changeable} = 0;
483     }
484
485     push @payments, $payment;
486   }
487
488   my @empty = grep { $_->{paid} eq '' } @payments;
489   @payments = (
490     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
491     @empty,
492   );
493
494   $form->{totalpaid} = sum map { $_->{paid} } @payments;
495
496   my $employees = SL::DB::Manager::Employee->get_all_sorted(
497     where => [
498       or => [
499         (id     => $::form->{employee_id}) x !!$::form->{employee_id},
500         deleted => undef,
501         deleted => 0,
502       ],
503     ],
504   );
505
506   setup_ar_form_header_action_bar();
507
508   $form->header;
509   print $::form->parse_html_template('ar/form_header', {
510     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
511     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
512     payments             => \@payments,
513     transactions         => \@transactions,
514     project_labels       => \%project_labels,
515     rows                 => $rows,
516     AR_chart_id          => $form->{AR_chart_id},
517     title_str            => $title,
518     follow_up_trans_info => $follow_up_trans_info,
519     today                => DateTime->today,
520     currencies           => scalar(SL::DB::Manager::Currency->get_all_sorted),
521     employees            => $employees,
522   });
523
524   $main::lxdebug->leave_sub();
525 }
526
527 sub form_footer {
528   $main::lxdebug->enter_sub();
529
530   $main::auth->assert('ar_transactions');
531
532   my $form     = $main::form;
533   my %myconfig = %main::myconfig;
534   my $locale   = $main::locale;
535   my $cgi      = $::request->{cgi};
536
537   if ( $form->{id} ) {
538     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
539     if ( @{ $follow_ups} ) {
540       $form->{follow_up_length} = scalar(@{$follow_ups});
541       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
542     }
543   }
544
545   print $::form->parse_html_template('ar/form_footer');
546
547   $main::lxdebug->leave_sub();
548 }
549
550 sub mark_as_paid {
551   $::auth->assert('ar_transactions');
552
553   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
554   $::form->redirect($::locale->text("Marked as paid"));
555 }
556
557 sub show_draft {
558   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
559   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
560   update();
561 }
562
563 sub update {
564   my %params = @_;
565   $main::lxdebug->enter_sub();
566
567   $main::auth->assert('ar_transactions');
568
569   my $form     = $main::form;
570   my %myconfig = %main::myconfig;
571
572   my $display = shift;
573
574   my ($totaltax, $exchangerate);
575
576   $form->{invtotal} = 0;
577
578   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
579
580   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
581     qw(exchangerate creditlimit creditremaining);
582
583   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
584   my $count = 0;
585   my @a     = ();
586
587   for my $i (1 .. $form->{rowcount}) {
588     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
589     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
590       push @a, {};
591       my $j = $#a;
592       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
593
594       my $tmpnetamount;
595       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
596
597       $totaltax += $form->{"tax_$i"};
598       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
599       $count++;
600     }
601   }
602
603   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
604   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
605   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
606
607   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
608   $form->{exchangerate} = $form->{forex} if $form->{forex};
609
610   $form->{invdate} = $form->{transdate};
611
612   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
613     IS->get_customer(\%myconfig, $form);
614     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
615       my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
616       $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
617     }
618   }
619
620   $form->{invtotal} =
621     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
622
623   for my $i (1 .. $form->{paidaccounts}) {
624     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
625       map {
626         $form->{"${_}_$i"} =
627           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
628       } qw(paid exchangerate);
629
630       $form->{totalpaid} += $form->{"paid_$i"};
631
632       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
633       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
634     }
635   }
636
637   $form->{creditremaining} -=
638     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
639      $form->{oldinvtotal});
640   $form->{oldinvtotal}  = $form->{invtotal};
641   $form->{oldtotalpaid} = $form->{totalpaid};
642
643   display_form();
644
645   $main::lxdebug->leave_sub();
646 }
647
648 #
649 # ToDO: fix $closedto and $invdate
650 #
651 sub post_payment {
652   $main::lxdebug->enter_sub();
653
654   $main::auth->assert('ar_transactions');
655
656   my $form     = $main::form;
657   my %myconfig = %main::myconfig;
658   my $locale   = $main::locale;
659
660   $form->mtime_ischanged('ar');
661   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
662
663   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
664
665   for my $i (1 .. $form->{paidaccounts}) {
666
667     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
668       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
669
670       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
671
672       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
673         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
674
675       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
676       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
677       $form->error($locale->text('Cannot post payment for a closed period!'))
678         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
679
680       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
681 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
682         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
683       }
684     }
685   }
686
687   ($form->{AR})      = split /--/, $form->{AR};
688   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
689   if (AR->post_payment(\%myconfig, \%$form)) {
690     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
691     $form->{what_done} = 'invoice';
692     $form->{addition}  = "PAYMENT POSTED";
693     $form->save_history;
694     $form->redirect($locale->text('Payment posted!'))
695   } else {
696     $form->error($locale->text('Cannot post payment!'));
697   };
698
699   $main::lxdebug->leave_sub();
700 }
701
702 sub _post {
703
704   $main::auth->assert('ar_transactions');
705
706   my $form     = $main::form;
707
708   # inline post
709   post(1);
710 }
711
712 sub post {
713   $main::lxdebug->enter_sub();
714
715   $main::auth->assert('ar_transactions');
716
717   my $form     = $main::form;
718   my %myconfig = %main::myconfig;
719   my $locale   = $main::locale;
720
721   my ($inline) = @_;
722
723   $form->mtime_ischanged('ar');
724
725   my ($datepaid);
726
727   # check if there is an invoice number, invoice and due date
728   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
729   $form->isblank("duedate",   $locale->text('Due Date missing!'));
730   $form->isblank("customer_id", $locale->text('Customer missing!'));
731
732   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
733     $form->{saved_message} = $::locale->text('You have to specify a department.');
734     update();
735     exit;
736   }
737
738   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
739   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
740
741   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
742     if ($form->date_max_future($transdate, \%myconfig));
743
744   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
745
746   $form->error($locale->text('Zero amount posting!'))
747     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
748
749   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
750     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
751
752   delete($form->{AR});
753
754   for my $i (1 .. $form->{paidaccounts}) {
755     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
756       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
757
758       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
759
760       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
761         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
762
763       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
764       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
765       $form->error($locale->text('Cannot post payment for a closed period!'))
766         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
767
768       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
769         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
770         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
771       }
772     }
773   }
774
775   # if oldcustomer ne customer redo form
776   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
777     update();
778     $::dispatcher->end_request;
779   }
780
781   $form->{AR}{receivables} = $form->{ARselected};
782   $form->{storno}          = 0;
783
784   $form->{id} = 0 if $form->{postasnew};
785   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
786
787   # saving the history
788   if(!exists $form->{addition} && $form->{id} ne "") {
789     $form->{snumbers}  = "invnumber_$form->{invnumber}";
790     $form->{what_done} = "invoice";
791     $form->{addition}  = "POSTED";
792     $form->save_history;
793   }
794   # /saving the history
795
796   $form->redirect($locale->text("AR transaction posted.")) unless $inline;
797
798   $main::lxdebug->leave_sub();
799 }
800
801 sub post_as_new {
802   $main::lxdebug->enter_sub();
803
804   $main::auth->assert('ar_transactions');
805
806   my $form     = $main::form;
807   my %myconfig = %main::myconfig;
808
809   $form->{postasnew} = 1;
810   # saving the history
811   if(!exists $form->{addition} && $form->{id} ne "") {
812     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
813     $form->{what_done} = "invoice";
814     $form->{addition}  = "POSTED AS NEW";
815     $form->save_history;
816   }
817   # /saving the history
818   &post;
819
820   $main::lxdebug->leave_sub();
821 }
822
823 sub use_as_new {
824   $main::lxdebug->enter_sub();
825
826   $main::auth->assert('ar_transactions');
827
828   my $form     = $main::form;
829   my %myconfig = %main::myconfig;
830
831   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);
832   $form->{paidaccounts} = 1;
833   $form->{rowcount}--;
834
835   my $today          = DateTime->today_local;
836   $form->{transdate} = $today->to_kivitendo;
837   $form->{duedate}   = $form->{transdate};
838
839   if ($form->{customer_id}) {
840     my $payment_terms = SL::DB::Customer->load_cached($form->{customer_id})->payment;
841     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
842   }
843
844   &update;
845
846   $main::lxdebug->leave_sub();
847 }
848
849 sub delete {
850   $::auth->assert('ar_transactions');
851
852   my $form     = $main::form;
853   my %myconfig = %main::myconfig;
854   my $locale   = $main::locale;
855
856   if (AR->delete_transaction(\%myconfig, \%$form)) {
857     # saving the history
858     if(!exists $form->{addition}) {
859       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
860       $form->{what_done} = "invoice";
861       $form->{addition}  = "DELETED";
862       $form->save_history;
863     }
864     # /saving the history
865     $form->redirect($locale->text('Transaction deleted!'));
866   }
867   $form->error($locale->text('Cannot delete transaction!'));
868 }
869
870 sub setup_ar_search_action_bar {
871   my %params = @_;
872
873   for my $bar ($::request->layout->get('actionbar')) {
874     $bar->add(
875       action => [
876         $::locale->text('Search'),
877         submit    => [ '#form' ],
878         accesskey => 'enter',
879       ],
880     );
881   }
882 }
883
884 sub setup_ar_transactions_action_bar {
885   my %params = @_;
886
887   for my $bar ($::request->layout->get('actionbar')) {
888     $bar->add(
889       action => [
890         $::locale->text('Print'),
891         call     => [ 'kivi.MassInvoiceCreatePrint.showMassPrintOptionsOrDownloadDirectly' ],
892         disabled => !$params{num_rows} ? $::locale->text('The report doesn\'t contain entries.') : undef,
893       ],
894
895       combobox => [
896         action => [ $::locale->text('Create new') ],
897         action => [
898           $::locale->text('AR Transaction'),
899           submit => [ '#create_new_form', { action => 'ar_transaction' } ],
900         ],
901         action => [
902           $::locale->text('Sales Invoice'),
903           submit => [ '#create_new_form', { action => 'sales_invoice' } ],
904         ],
905       ], # end of combobox "Create new"
906     );
907   }
908 }
909
910 sub search {
911   $main::lxdebug->enter_sub();
912
913   $main::auth->assert('invoice_edit');
914
915   my $form     = $main::form;
916   my %myconfig = %main::myconfig;
917   my $locale   = $main::locale;
918   my $cgi      = $::request->{cgi};
919
920   $form->{title} = $locale->text('Invoices, Credit Notes & AR Transactions');
921
922   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
923   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
924   $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business->get_all_sorted;
925
926   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
927   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
928    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
929                                                                               'include_prefix' => 'l_',
930                                                                               'include_value'  => 'Y');
931
932   # constants and subs for template
933   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
934
935   $::request->layout->add_javascripts("autocomplete_project.js");
936
937   setup_ar_search_action_bar();
938
939   $form->header;
940   print $form->parse_html_template('ar/search', { %myconfig });
941
942   $main::lxdebug->leave_sub();
943 }
944
945 sub create_subtotal_row {
946   $main::lxdebug->enter_sub();
947
948   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
949
950   my $form     = $main::form;
951   my %myconfig = %main::myconfig;
952
953   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
954
955   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
956
957   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
958
959   map { $totals->{$_} = 0 } @{ $subtotal_columns };
960
961   $main::lxdebug->leave_sub();
962
963   return $row;
964 }
965
966 sub ar_transactions {
967   $main::lxdebug->enter_sub();
968
969   $main::auth->assert('invoice_edit');
970
971   my $form     = $main::form;
972   my %myconfig = %main::myconfig;
973   my $locale   = $main::locale;
974
975   my ($callback, $href, @columns);
976
977   report_generator_set_default_sort('transdate', 1);
978
979   AR->ar_transactions(\%myconfig, \%$form);
980
981   $form->{title} = $locale->text('Invoices, Credit Notes & AR Transactions');
982
983   my $report = SL::ReportGenerator->new(\%myconfig, $form);
984
985   @columns =
986     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
987        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
988        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
989        payment_terms charts customertype direct_debit dunning_description department);
990
991   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
992   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
993   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
994
995   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
996   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
997
998   my @hidden_variables = map { "l_${_}" } @columns;
999   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
1000                                            employee_id salesman_id business_id parts_partnumber parts_description department_id);
1001   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
1002
1003   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
1004
1005   my %column_defs = (
1006     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
1007     'transdate'               => { 'text' => $locale->text('Date'), },
1008     'id'                      => { 'text' => $locale->text('ID'), },
1009     'type'                    => { 'text' => $locale->text('Type'), },
1010     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1011     'ordnumber'               => { 'text' => $locale->text('Order'), },
1012     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
1013     'name'                    => { 'text' => $locale->text('Customer'), },
1014     'netamount'               => { 'text' => $locale->text('Amount'), },
1015     'tax'                     => { 'text' => $locale->text('Tax'), },
1016     'amount'                  => { 'text' => $locale->text('Total'), },
1017     'paid'                    => { 'text' => $locale->text('Paid'), },
1018     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1019     'due'                     => { 'text' => $locale->text('Amount Due'), },
1020     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1021     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1022     'notes'                   => { 'text' => $locale->text('Notes'), },
1023     'salesman'                => { 'text' => $locale->text('Salesperson'), },
1024     'employee'                => { 'text' => $locale->text('Employee'), },
1025     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
1026     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
1027     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1028     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
1029     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
1030     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
1031     'country'                 => { 'text' => $locale->text('Country'), },
1032     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1033     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1034     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1035     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1036     'customertype'            => { 'text' => $locale->text('Customer type'), },
1037     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1038     'department'              => { 'text' => $locale->text('Department'), },
1039     dunning_description       => { 'text' => $locale->text('Dunning level'), },
1040     %column_defs_cvars,
1041   );
1042
1043   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1044     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1045     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1046   }
1047
1048   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1049
1050   $form->{"l_type"} = "Y";
1051   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1052
1053   $column_defs{ids}->{visible} = 'HTML';
1054
1055   $report->set_columns(%column_defs);
1056   $report->set_column_order(@columns);
1057
1058   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1059
1060   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1061
1062   CVar->add_custom_variables_to_report('module'         => 'CT',
1063                                        'trans_id_field' => 'customer_id',
1064                                        'configs'        => $ct_cvar_configs,
1065                                        'column_defs'    => \%column_defs,
1066                                        'data'           => $form->{AR});
1067
1068   my @options;
1069   if ($form->{customer}) {
1070     push @options, $locale->text('Customer') . " : $form->{customer}";
1071   }
1072   if ($form->{cp_name}) {
1073     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1074   }
1075
1076   if ($form->{department_id}) {
1077     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
1078     push @options, $locale->text('Department') . " : " . $department->description;
1079   }
1080   if ($form->{invnumber}) {
1081     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1082   }
1083   if ($form->{ordnumber}) {
1084     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1085   }
1086   if ($form->{cusordnumber}) {
1087     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1088   }
1089   if ($form->{notes}) {
1090     push @options, $locale->text('Notes') . " : $form->{notes}";
1091   }
1092   if ($form->{transaction_description}) {
1093     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1094   }
1095   if ($form->{parts_partnumber}) {
1096     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1097   }
1098   if ($form->{parts_description}) {
1099     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1100   }
1101   if ($form->{transdatefrom}) {
1102     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1103   }
1104   if ($form->{transdateto}) {
1105     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1106   }
1107   if ($form->{open}) {
1108     push @options, $locale->text('Open');
1109   }
1110   if ($form->{employee_id}) {
1111     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1112     push @options, $locale->text('Employee') . ' : ' . $employee->name;
1113   }
1114   if ($form->{salesman_id}) {
1115     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1116     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1117   }
1118   if ($form->{closed}) {
1119     push @options, $locale->text('Closed');
1120   }
1121
1122   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1123
1124   $report->set_options('top_info_text'        => join("\n", @options),
1125                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
1126                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1127                        'output_format'        => 'HTML',
1128                        'title'                => $form->{title},
1129                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1130     );
1131   $report->set_options_from_form();
1132   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1133
1134   # add sort and escape callback, this one we use for the add sub
1135   $form->{callback} = $href .= "&sort=$form->{sort}";
1136
1137   # escape callback for href
1138   $callback = $form->escape($href);
1139
1140   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1141
1142   my %totals    = map { $_ => 0 } @subtotal_columns;
1143   my %subtotals = map { $_ => 0 } @subtotal_columns;
1144
1145   my $idx = 0;
1146
1147   foreach my $ar (@{ $form->{AR} }) {
1148     $ar->{tax} = $ar->{amount} - $ar->{netamount};
1149     $ar->{due} = $ar->{amount} - $ar->{paid};
1150
1151     map { $subtotals{$_} += $ar->{$_};
1152           $totals{$_}    += $ar->{$_} } @subtotal_columns;
1153
1154     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1155     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1156
1157     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
1158     my $has_storno = $ar->{storno} && !$ar->{storno_id};
1159
1160     $ar->{type} =
1161       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
1162       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
1163       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1164       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
1165                           $locale->text("AR Transaction (abbreviation)");
1166
1167     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1168
1169     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1170
1171     my $row = { };
1172
1173     foreach my $column (@columns) {
1174       $row->{$column} = {
1175         'data'  => $ar->{$column},
1176         'align' => $column_alignment{$column},
1177       };
1178     }
1179
1180     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1181       . "&id=" . E($ar->{id}) . "&callback=${callback}";
1182
1183     $row->{ids} = {
1184       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1185       valign   => 'center',
1186       align    => 'center',
1187     };
1188
1189     my $row_set = [ $row ];
1190
1191     if (($form->{l_subtotal} eq 'Y')
1192         && (($idx == (scalar @{ $form->{AR} } - 1))
1193             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1194       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1195     }
1196
1197     $report->add_data($row_set);
1198
1199     $idx++;
1200   }
1201
1202   $report->add_separator();
1203   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1204
1205   $::request->layout->add_javascripts('kivi.MassInvoiceCreatePrint.js');
1206   setup_ar_transactions_action_bar(num_rows => scalar(@{ $form->{AR} }));
1207
1208   $report->generate_with_headers();
1209
1210   $main::lxdebug->leave_sub();
1211 }
1212
1213 sub storno {
1214   $main::lxdebug->enter_sub();
1215
1216   $main::auth->assert('ar_transactions');
1217
1218   my $form     = $main::form;
1219   my %myconfig = %main::myconfig;
1220   my $locale   = $main::locale;
1221
1222   # don't cancel cancelled transactions
1223   if (IS->has_storno(\%myconfig, $form, 'ar')) {
1224     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1225     $form->error($locale->text("Transaction has already been cancelled!"));
1226   }
1227
1228   AR->storno($form, \%myconfig, $form->{id});
1229
1230   # saving the history
1231   if(!exists $form->{addition} && $form->{id} ne "") {
1232     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1233     $form->{addition}  = "STORNO";
1234     $form->{what_done} = "invoice";
1235     $form->save_history;
1236   }
1237   # /saving the history
1238
1239   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1240
1241   $main::lxdebug->leave_sub();
1242 }
1243
1244 sub setup_ar_form_header_action_bar {
1245   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
1246   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
1247   my $is_closed               = $transdate <= $closedto;
1248
1249   my $change_never            = $::instance_conf->get_ar_changeable == 0;
1250   my $change_on_same_day_only = $::instance_conf->get_ar_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1251
1252   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ar', $::form->{id});
1253   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ar');
1254
1255   for my $bar ($::request->layout->get('actionbar')) {
1256     $bar->add(
1257       action => [
1258         t8('Update'),
1259         submit    => [ '#form', { action => "update" } ],
1260         id        => 'update_button',
1261         accesskey => 'enter',
1262       ],
1263
1264       combobox => [
1265         action => [
1266           t8('Post'),
1267           submit   => [ '#form', { action => "post" } ],
1268           checks   => [ 'kivi.AR.check_fields_before_posting' ],
1269           disabled => $is_closed                                  ? t8('The billing period has already been locked.')
1270                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
1271                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
1272                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1273                     :                                               undef,
1274         ],
1275         action => [
1276           t8('Post Payment'),
1277           submit   => [ '#form', { action => "post_payment" } ],
1278           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1279         ],
1280         action => [ t8('Mark as paid'),
1281           submit   => [ '#form', { action => "mark_as_paid" } ],
1282           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1283           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1284           only_if  => $::instance_conf->get_is_show_mark_as_paid,
1285         ],
1286       ], # end of combobox "Post"
1287
1288       combobox => [
1289         action => [ t8('Storno'),
1290           submit   => [ '#form', { action => "storno" } ],
1291           checks   => [ 'kivi.AR.check_fields_before_posting' ],
1292           confirm  => t8('Do you really want to cancel this invoice?'),
1293           disabled => !$::form->{id}         ? t8('This invoice has not been posted yet.')
1294                       : $has_storno          ? t8('This invoice has been canceled already.')
1295                       : $is_storno           ? t8('Reversal invoices cannot be canceled.')
1296                       : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1297                       :                        undef,
1298         ],
1299         action => [ t8('Delete'),
1300           submit   => [ '#form', { action => "delete" } ],
1301           confirm  => t8('Do you really want to delete this object?'),
1302           disabled => !$::form->{id}           ? t8('This invoice has not been posted yet.')
1303                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
1304                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1305                     : $is_closed               ? t8('The billing period has already been locked.')
1306                     :                            undef,
1307         ],
1308       ], # end of combobox "Storno"
1309
1310       'separator',
1311
1312       combobox => [
1313         action => [ t8('Workflow') ],
1314         action => [
1315           t8('Use As New'),
1316           submit   => [ '#form', { action => "use_as_new" } ],
1317           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1318         ],
1319       ], # end of combobox "Workflow"
1320
1321       combobox => [
1322         action => [ t8('more') ],
1323         action => [
1324           t8('History'),
1325           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1326           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1327         ],
1328         action => [
1329           t8('Follow-Up'),
1330           call     => [ 'follow_up_window' ],
1331           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1332         ],
1333         action => [
1334           t8('Record templates'),
1335           call => [ 'kivi.RecordTemplate.popup', 'ar_transaction' ],
1336         ],
1337         action => [
1338           t8('Drafts'),
1339           call     => [ 'kivi.Draft.popup', 'ar', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1340           disabled => $::form->{id} ? t8('This invoice has already been posted.')
1341                     : $is_closed    ? t8('The billing period has already been locked.')
1342                     :                 undef,
1343         ],
1344       ], # end of combobox "more"
1345     );
1346   }
1347 }
1348
1349 1;