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