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