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