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