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