1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  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.
 
  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,
 
  29 #======================================================================
 
  31 # Accounts Receivables
 
  33 #======================================================================
 
  35 use POSIX qw(strftime);
 
  36 use List::Util qw(sum first max);
 
  37 use List::UtilsBy qw(sort_by);
 
  48 use SL::ReportGenerator;
 
  50 require "bin/mozilla/arap.pl";
 
  51 require "bin/mozilla/common.pl";
 
  52 require "bin/mozilla/reportgenerator.pl";
 
  57 # this is for our long dates
 
  58 # $locale->text('January')
 
  59 # $locale->text('February')
 
  60 # $locale->text('March')
 
  61 # $locale->text('April')
 
  62 # $locale->text('May ')
 
  63 # $locale->text('June')
 
  64 # $locale->text('July')
 
  65 # $locale->text('August')
 
  66 # $locale->text('September')
 
  67 # $locale->text('October')
 
  68 # $locale->text('November')
 
  69 # $locale->text('December')
 
  71 # this is for our short month
 
  72 # $locale->text('Jan')
 
  73 # $locale->text('Feb')
 
  74 # $locale->text('Mar')
 
  75 # $locale->text('Apr')
 
  76 # $locale->text('May')
 
  77 # $locale->text('Jun')
 
  78 # $locale->text('Jul')
 
  79 # $locale->text('Aug')
 
  80 # $locale->text('Sep')
 
  81 # $locale->text('Oct')
 
  82 # $locale->text('Nov')
 
  83 # $locale->text('Dec')
 
  86   $main::lxdebug->enter_sub();
 
  88   $main::auth->assert('ar_transactions');
 
  90   my $form     = $main::form;
 
  91   my %myconfig = %main::myconfig;
 
  94   if(!exists $form->{addition} && ($form->{id} ne "")) {
 
  95     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
 
  96     $form->{addition} = "ADDED";
 
 101   $form->{title}    = "Add";
 
 102   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
 
 104   AR->get_transdate(\%myconfig, $form);
 
 105   $form->{initial_transdate} = $form->{transdate};
 
 106   create_links(dont_save => 1);
 
 107   $form->{transdate} = $form->{initial_transdate};
 
 109   if ($form->{customer_id}) {
 
 110     my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
 
 111     $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
 
 115   $main::lxdebug->leave_sub();
 
 119   $main::lxdebug->enter_sub();
 
 121   $main::auth->assert('ar_transactions');
 
 123   my $form     = $main::form;
 
 125   # show history button
 
 126   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 127   #/show hhistory button
 
 128   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
 
 129   $form->{title} = "Edit";
 
 134   $main::lxdebug->leave_sub();
 
 138   $main::lxdebug->enter_sub();
 
 140   $main::auth->assert('ar_transactions');
 
 142   my $form     = $main::form;
 
 147   $main::lxdebug->leave_sub();
 
 150 sub _retrieve_invoice_object {
 
 151   return undef if !$::form->{id};
 
 152   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
 
 153   return SL::DB::Invoice->new(id => $::form->{id})->load;
 
 157   $main::lxdebug->enter_sub();
 
 159   $main::auth->assert('ar_transactions');
 
 162   my $form     = $main::form;
 
 163   my %myconfig = %main::myconfig;
 
 165   $form->create_links("AR", \%myconfig, "customer");
 
 166   $form->{invoice_obj} = _retrieve_invoice_object();
 
 169   if (!$params{dont_save}) {
 
 170     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
 
 171     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 172     $saved{currency} = $form->{currency} if $form->{currency};
 
 175   IS->get_customer(\%myconfig, \%$form);
 
 177   $form->{$_}          = $saved{$_} for keys %saved;
 
 178   $form->{rowcount}    = 1;
 
 179   $form->{AR_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AR} ? $form->{acc_trans}->{AR}->[0]->{chart_id} : $form->{AR_links}->{AR}->[0]->{chart_id};
 
 182   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 184   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
 186   # build the popup menus
 
 187   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 189   AR->setup_form($form);
 
 192     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 193      $form->datetonum($form->{closedto}, \%myconfig));
 
 195   $main::lxdebug->leave_sub();
 
 199   $main::lxdebug->enter_sub();
 
 201   $main::auth->assert('ar_transactions');
 
 203   my $form     = $main::form;
 
 204   my %myconfig = %main::myconfig;
 
 205   my $locale   = $main::locale;
 
 206   my $cgi      = $::request->{cgi};
 
 208   $form->{invoice_obj} = _retrieve_invoice_object();
 
 210   my ($title, $readonly, $exchangerate, $rows);
 
 211   my ($notes, $amount, $project);
 
 213   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
 
 215   $title = $form->{title};
 
 216   # $locale->text('Add Accounts Receivables Transaction')
 
 217   # $locale->text('Edit Accounts Receivables Transaction')
 
 218   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
 
 220   $readonly = ($form->{id}) ? "readonly" : "";
 
 222   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
 
 223                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 224                       : ($::instance_conf->get_ar_changeable == 1);
 
 225   $readonly = ($form->{radier}) ? "" : $readonly;
 
 227   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 228   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 230   # format exchangerate
 
 231   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
 
 233   $rows = max 2, $form->numtextrows($form->{notes}, 50);
 
 235   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
 
 237   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 239                                     "old_id"    => \@old_project_ids },
 
 240                    "charts"    => { "key"       => "ALL_CHARTS",
 
 241                                     "transdate" => $form->{transdate} },
 
 242                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
 
 243                                     "module"    => "AR" },);
 
 245   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
 
 247   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
 
 249   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
 
 251   my (@AR_paid_values, %AR_paid_labels);
 
 252   my $default_ar_amount_chart_id;
 
 254   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 255     if ($item->{link_split}{AR_amount}) {
 
 256       $default_ar_amount_chart_id //= $item->{id};
 
 258     } elsif ($item->{link_split}{AR_paid}) {
 
 259       push(@AR_paid_values, $item->{accno});
 
 260       $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
 
 264   my $follow_up_vc         = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
 
 265   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 267   $::request->layout->add_javascripts("autocomplete_chart.js", "autocomplete_customer.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js");
 
 269   my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
 
 273   for my $i (1 .. $form->{rowcount}) {
 
 275       amount     => $form->{"amount_$i"},
 
 276       tax        => $form->{"tax_$i"},
 
 277       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
 
 280     my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
 
 281     my $amount_chart_id   = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
 
 282     my $chart_has_changed = $::form->{"previous_AR_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AR_amount_chart_id_$i"});
 
 284     foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $transdate) ) {
 
 285       my $key             = $item->id . "--" . $item->rate;
 
 286       $first_taxchart   //= $item;
 
 287       $default_taxchart   = $item if $item->{is_default};
 
 288       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
 
 290       push(@taxchart_values, $key);
 
 291       $taxchart_labels{$key} = $item->taxdescription . " " . $item->rate * 100 . ' %';
 
 294     $taxchart_to_use      = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
 
 295     my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
 
 297     $transaction->{selectAR_amount} =
 
 298         $::request->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" : ""))
 
 299       . $::request->presenter->hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
 
 301     $transaction->{taxchart} =
 
 302       NTI($cgi->popup_menu('-name' => "taxchart_$i",
 
 303                            '-id' => "taxchart_$i",
 
 304                            '-style' => 'width:200px',
 
 305                            '-values' => \@taxchart_values,
 
 306                            '-labels' => \%taxchart_labels,
 
 307                            '-default' => $selected_taxchart));
 
 309     push @transactions, $transaction;
 
 312   $form->{invtotal_unformatted} = $form->{invtotal};
 
 314   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 316   my $now = $form->current_date(\%myconfig);
 
 319   for my $i (1 .. $form->{paidaccounts}) {
 
 321       paid             => $form->{"paid_$i"},
 
 322       exchangerate     => $form->{"exchangerate_$i"} || '',
 
 323       gldate           => $form->{"gldate_$i"},
 
 324       acc_trans_id     => $form->{"acc_trans_id_$i"},
 
 325       source           => $form->{"source_$i"},
 
 326       memo             => $form->{"memo_$i"},
 
 327       AR_paid          => $form->{"AR_paid_$i"},
 
 328       forex            => $form->{"forex_$i"},
 
 329       datepaid         => $form->{"datepaid_$i"},
 
 330       paid_project_id  => $form->{"paid_project_id_$i"},
 
 331       gldate           => $form->{"gldate_$i"},
 
 334     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
 
 335     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 337     $payment->{selectAR_paid} =
 
 338       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
 
 339                            '-id' => "AR_paid_$i",
 
 340                            '-values' => \@AR_paid_values,
 
 341                            '-labels' => \%AR_paid_labels,
 
 342                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
 
 346     $payment->{changeable} =
 
 347         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
 
 348       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
 
 351     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 352     if ($form->date_closed($payment->{"gldate_$i"})) {
 
 353         $payment->{changeable} = 0;
 
 356     push @payments, $payment;
 
 359   my @empty = grep { $_->{paid} eq '' } @payments;
 
 361     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
 
 365   $form->{totalpaid} = sum map { $_->{paid} } @payments;
 
 367   my $employees = SL::DB::Manager::Employee->get_all_sorted(
 
 370         (id     => $::form->{employee_id}) x !!$::form->{employee_id},
 
 378   print $::form->parse_html_template('ar/form_header', {
 
 379     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
 
 380     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
 
 381     payments             => \@payments,
 
 382     transactions         => \@transactions,
 
 383     project_labels       => \%project_labels,
 
 385     AR_chart_id          => $form->{AR_chart_id},
 
 387     follow_up_trans_info => $follow_up_trans_info,
 
 388     today                => DateTime->today,
 
 389     currencies           => scalar(SL::DB::Manager::Currency->get_all_sorted),
 
 390     employees            => $employees,
 
 393   $main::lxdebug->leave_sub();
 
 397   $main::lxdebug->enter_sub();
 
 399   $main::auth->assert('ar_transactions');
 
 401   my $form     = $main::form;
 
 402   my %myconfig = %main::myconfig;
 
 403   my $locale   = $main::locale;
 
 404   my $cgi      = $::request->{cgi};
 
 407     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
 
 408     if ( @{ $follow_ups} ) {
 
 409       $form->{follow_up_length} = scalar(@{$follow_ups});
 
 410       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
 
 414   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 415   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 417   $form->{is_closed} = $transdate <= $closedto;
 
 419   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
 
 420   $form->{show_storno_button} =
 
 422     !IS->has_storno(\%myconfig, $form, 'ar') &&
 
 423     !IS->is_storno(\%myconfig, $form, 'ar') &&
 
 424     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
 
 426   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
 
 428   print $::form->parse_html_template('ar/form_footer');
 
 430   $main::lxdebug->leave_sub();
 
 434   $::auth->assert('ar_transactions');
 
 436   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
 
 438   $::form->redirect($::locale->text("Marked as paid"));
 
 442   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
 
 443   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
 
 448   $main::lxdebug->enter_sub();
 
 450   $main::auth->assert('ar_transactions');
 
 452   my $form     = $main::form;
 
 453   my %myconfig = %main::myconfig;
 
 457   my ($totaltax, $exchangerate);
 
 459   $form->{invtotal} = 0;
 
 461   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 463   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 464     qw(exchangerate creditlimit creditremaining);
 
 466   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
 
 470   for my $i (1 .. $form->{rowcount}) {
 
 471     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 472     if ($form->{"amount_$i"}) {
 
 475       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 478       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 480       $totaltax += $form->{"tax_$i"};
 
 481       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 486   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 487   $form->{rowcount} = $count + 1;
 
 488   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 490   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 491   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 493   $form->{invdate} = $form->{transdate};
 
 495   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 496     IS->get_customer(\%myconfig, $form);
 
 500     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 502   for my $i (1 .. $form->{paidaccounts}) {
 
 503     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 506           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 507       } qw(paid exchangerate);
 
 509       $form->{totalpaid} += $form->{"paid_$i"};
 
 511       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 512       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 516   $form->{creditremaining} -=
 
 517     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
 
 518      $form->{oldinvtotal});
 
 519   $form->{oldinvtotal}  = $form->{invtotal};
 
 520   $form->{oldtotalpaid} = $form->{totalpaid};
 
 524   $main::lxdebug->leave_sub();
 
 528 # ToDO: fix $closedto and $invdate
 
 531   $main::lxdebug->enter_sub();
 
 533   $main::auth->assert('ar_transactions');
 
 535   my $form     = $main::form;
 
 536   my %myconfig = %main::myconfig;
 
 537   my $locale   = $main::locale;
 
 539   $form->mtime_ischanged('ar');
 
 540   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 542   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 544   for my $i (1 .. $form->{paidaccounts}) {
 
 546     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 547       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 549       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 551       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 552         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 554       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 555       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 556       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 557         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 559       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 560 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
 
 561         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 566   ($form->{AR})      = split /--/, $form->{AR};
 
 567   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
 
 568   if (AR->post_payment(\%myconfig, \%$form)) {
 
 569     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 570     $form->{what_done} = 'invoice';
 
 571     $form->{addition}  = "PAYMENT POSTED";
 
 573     $form->redirect($locale->text('Payment posted!'))
 
 575     $form->error($locale->text('Cannot post payment!'));
 
 578   $main::lxdebug->leave_sub();
 
 583   $main::auth->assert('ar_transactions');
 
 585   my $form     = $main::form;
 
 592   $main::lxdebug->enter_sub();
 
 594   $main::auth->assert('ar_transactions');
 
 596   my $form     = $main::form;
 
 597   my %myconfig = %main::myconfig;
 
 598   my $locale   = $main::locale;
 
 602   $form->mtime_ischanged('ar');
 
 606   # check if there is an invoice number, invoice and due date
 
 607   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
 
 608   $form->isblank("duedate",   $locale->text('Due Date missing!'));
 
 609   $form->isblank("customer_id", $locale->text('Customer missing!'));
 
 611   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 612     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 617   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 618   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 620   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 621     if ($form->date_max_future($transdate, \%myconfig));
 
 623   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 625   $form->error($locale->text('Zero amount posting!'))
 
 626     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
 
 628   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 629     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 633   for my $i (1 .. $form->{paidaccounts}) {
 
 634     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 635       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 637       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 639       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 640         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 642       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 643       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 644       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 645         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 647       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 648         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
 
 649         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 654   # if oldcustomer ne customer redo form
 
 655   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 657     $::dispatcher->end_request;
 
 660   $form->{AR}{receivables} = $form->{ARselected};
 
 663   $form->{id} = 0 if $form->{postasnew};
 
 664   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
 
 667   if(!exists $form->{addition} && $form->{id} ne "") {
 
 668     $form->{snumbers}  = "invnumber_$form->{invnumber}";
 
 669     $form->{what_done} = "invoice";
 
 670     $form->{addition}  = "POSTED";
 
 673   # /saving the history
 
 675   $form->redirect($locale->text('Transaction posted!')) unless $inline;
 
 677   $main::lxdebug->leave_sub();
 
 681   $main::lxdebug->enter_sub();
 
 683   $main::auth->assert('ar_transactions');
 
 685   my $form     = $main::form;
 
 686   my %myconfig = %main::myconfig;
 
 688   $form->{postasnew} = 1;
 
 690   if(!exists $form->{addition} && $form->{id} ne "") {
 
 691     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 692     $form->{what_done} = "invoice";
 
 693     $form->{addition}  = "POSTED AS NEW";
 
 696   # /saving the history
 
 699   $main::lxdebug->leave_sub();
 
 703   $main::lxdebug->enter_sub();
 
 705   $main::auth->assert('ar_transactions');
 
 707   my $form     = $main::form;
 
 708   my %myconfig = %main::myconfig;
 
 710   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
 
 711   $form->{paidaccounts} = 1;
 
 713   $form->{invdate} = $form->current_date(\%myconfig);
 
 716   $main::lxdebug->leave_sub();
 
 720   $main::lxdebug->enter_sub();
 
 722   $main::auth->assert('ar_transactions');
 
 724   my $form     = $main::form;
 
 725   my $locale   = $main::locale;
 
 727   $form->{title} = $locale->text('Confirm!');
 
 731   delete $form->{header};
 
 734 <form method=post action=$form->{script}>
 
 737   foreach my $key (keys %$form) {
 
 738     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 739     $form->{$key} =~ s/\"/"/g;
 
 740     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 744 <h2 class=confirm>$form->{title}</h2>
 
 747     . $locale->text('Are you sure you want to delete Transaction')
 
 748     . qq| $form->{invnumber}</h4>
 
 750 <input name=action class=submit type=submit value="|
 
 751     . $locale->text('Yes') . qq|">
 
 755   $main::lxdebug->leave_sub();
 
 759   $main::lxdebug->enter_sub();
 
 761   $main::auth->assert('ar_transactions');
 
 763   my $form     = $main::form;
 
 764   my %myconfig = %main::myconfig;
 
 765   my $locale   = $main::locale;
 
 767   if (AR->delete_transaction(\%myconfig, \%$form)) {
 
 769     if(!exists $form->{addition}) {
 
 770       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 771       $form->{what_done} = "invoice";
 
 772       $form->{addition}  = "DELETED";
 
 775     # /saving the history
 
 776     $form->redirect($locale->text('Transaction deleted!'));
 
 778   $form->error($locale->text('Cannot delete transaction!'));
 
 780   $main::lxdebug->leave_sub();
 
 784   $main::lxdebug->enter_sub();
 
 786   $main::auth->assert('invoice_edit');
 
 788   my $form     = $main::form;
 
 789   my %myconfig = %main::myconfig;
 
 790   my $locale   = $main::locale;
 
 791   my $cgi      = $::request->{cgi};
 
 793   $form->{title}    = $locale->text('AR Transactions');
 
 795   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
 
 796   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 797   $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business->get_all_sorted;
 
 799   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
 
 800   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
 
 801    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
 
 802                                                                               'include_prefix' => 'l_',
 
 803                                                                               'include_value'  => 'Y');
 
 805   # constants and subs for template
 
 806   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 808   $::request->layout->add_javascripts("autocomplete_project.js");
 
 811   print $form->parse_html_template('ar/search', { %myconfig });
 
 813   $main::lxdebug->leave_sub();
 
 816 sub create_subtotal_row {
 
 817   $main::lxdebug->enter_sub();
 
 819   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 821   my $form     = $main::form;
 
 822   my %myconfig = %main::myconfig;
 
 824   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 826   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 828   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 830   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 832   $main::lxdebug->leave_sub();
 
 837 sub ar_transactions {
 
 838   $main::lxdebug->enter_sub();
 
 840   $main::auth->assert('invoice_edit');
 
 842   my $form     = $main::form;
 
 843   my %myconfig = %main::myconfig;
 
 844   my $locale   = $main::locale;
 
 846   my ($callback, $href, @columns);
 
 848   report_generator_set_default_sort('transdate', 1);
 
 850   AR->ar_transactions(\%myconfig, \%$form);
 
 852   $form->{title} = $locale->text('AR Transactions');
 
 854   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
 857     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
 
 858        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
 
 859        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone
 
 860        payment_terms charts customertype direct_debit dunning_description department);
 
 862   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
 
 863   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
 
 864   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
 
 866   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
 
 867   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
 
 869   my @hidden_variables = map { "l_${_}" } @columns;
 
 870   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
 
 871                                            employee_id salesman_id business_id parts_partnumber parts_description department_id);
 
 872   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
 
 874   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
 
 877     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
 
 878     'transdate'               => { 'text' => $locale->text('Date'), },
 
 879     'id'                      => { 'text' => $locale->text('ID'), },
 
 880     'type'                    => { 'text' => $locale->text('Type'), },
 
 881     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
 882     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
 883     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
 
 884     'name'                    => { 'text' => $locale->text('Customer'), },
 
 885     'netamount'               => { 'text' => $locale->text('Amount'), },
 
 886     'tax'                     => { 'text' => $locale->text('Tax'), },
 
 887     'amount'                  => { 'text' => $locale->text('Total'), },
 
 888     'paid'                    => { 'text' => $locale->text('Paid'), },
 
 889     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
 890     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
 891     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
 892     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
 893     'notes'                   => { 'text' => $locale->text('Notes'), },
 
 894     'salesman'                => { 'text' => $locale->text('Salesperson'), },
 
 895     'employee'                => { 'text' => $locale->text('Employee'), },
 
 896     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
 
 897     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
 
 898     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
 899     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
 
 900     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
 
 901     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
 
 902     'country'                 => { 'text' => $locale->text('Country'), },
 
 903     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
 904     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
 
 905     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
 906     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
 
 907     'customertype'            => { 'text' => $locale->text('Customer type'), },
 
 908     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
 909     'department'              => { 'text' => $locale->text('Department'), },
 
 910     dunning_description       => { 'text' => $locale->text('Dunning level'), },
 
 914   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
 
 915     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
 916     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
 919   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
 921   $form->{"l_type"} = "Y";
 
 922   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
 924   $column_defs{ids}->{visible} = 'HTML';
 
 926   $report->set_columns(%column_defs);
 
 927   $report->set_column_order(@columns);
 
 929   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
 
 931   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
 933   CVar->add_custom_variables_to_report('module'         => 'CT',
 
 934                                        'trans_id_field' => 'customer_id',
 
 935                                        'configs'        => $ct_cvar_configs,
 
 936                                        'column_defs'    => \%column_defs,
 
 937                                        'data'           => $form->{AR});
 
 940   if ($form->{customer}) {
 
 941     push @options, $locale->text('Customer') . " : $form->{customer}";
 
 943   if ($form->{cp_name}) {
 
 944     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
 
 947   if ($form->{department_id}) {
 
 948     my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
 
 949     push @options, $locale->text('Department') . " : " . $department->description;
 
 951   if ($form->{invnumber}) {
 
 952     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
 
 954   if ($form->{ordnumber}) {
 
 955     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
 
 957   if ($form->{cusordnumber}) {
 
 958     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
 
 960   if ($form->{notes}) {
 
 961     push @options, $locale->text('Notes') . " : $form->{notes}";
 
 963   if ($form->{transaction_description}) {
 
 964     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
 
 966   if ($form->{parts_partnumber}) {
 
 967     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
 
 969   if ($form->{parts_description}) {
 
 970     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
 
 972   if ($form->{transdatefrom}) {
 
 973     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
 
 975   if ($form->{transdateto}) {
 
 976     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
 
 979     push @options, $locale->text('Open');
 
 981   if ($form->{employee_id}) {
 
 982     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
 
 983     push @options, $locale->text('Employee') . ' : ' . $employee->name;
 
 985   if ($form->{salesman_id}) {
 
 986     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
 
 987     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
 
 989   if ($form->{closed}) {
 
 990     push @options, $locale->text('Closed');
 
 993   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
 
 995   $report->set_options('top_info_text'        => join("\n", @options),
 
 996                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
 
 997                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
 
 998                        'output_format'        => 'HTML',
 
 999                        'title'                => $form->{title},
 
1000                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
 
1002   $report->set_options_from_form();
 
1003   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1005   # add sort and escape callback, this one we use for the add sub
 
1006   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1008   # escape callback for href
 
1009   $callback = $form->escape($href);
 
1011   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
 
1013   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1014   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1018   foreach my $ar (@{ $form->{AR} }) {
 
1019     $ar->{tax} = $ar->{amount} - $ar->{netamount};
 
1020     $ar->{due} = $ar->{amount} - $ar->{paid};
 
1022     map { $subtotals{$_} += $ar->{$_};
 
1023           $totals{$_}    += $ar->{$_} } @subtotal_columns;
 
1025     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
 
1026     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
 
1028     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
 
1029     my $has_storno = $ar->{storno} && !$ar->{storno_id};
 
1032       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
 
1033       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
 
1034       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
 
1035       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
 
1036                           $locale->text("AR Transaction (abbreviation)");
 
1038     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
 
1040     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1044     foreach my $column (@columns) {
 
1046         'data'  => $ar->{$column},
 
1047         'align' => $column_alignment{$column},
 
1051     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
 
1052       . "&id=" . E($ar->{id}) . "&callback=${callback}";
 
1055       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
 
1060     my $row_set = [ $row ];
 
1062     if (($form->{l_subtotal} eq 'Y')
 
1063         && (($idx == (scalar @{ $form->{AR} } - 1))
 
1064             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
 
1065       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1068     $report->add_data($row_set);
 
1073   $report->add_separator();
 
1074   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1076   $report->generate_with_headers();
 
1078   $main::lxdebug->leave_sub();
 
1082   $main::lxdebug->enter_sub();
 
1084   $main::auth->assert('ar_transactions');
 
1086   my $form     = $main::form;
 
1087   my %myconfig = %main::myconfig;
 
1088   my $locale   = $main::locale;
 
1090   # don't cancel cancelled transactions
 
1091   if (IS->has_storno(\%myconfig, $form, 'ar')) {
 
1092     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
 
1093     $form->error($locale->text("Transaction has already been cancelled!"));
 
1096   AR->storno($form, \%myconfig, $form->{id});
 
1098   # saving the history
 
1099   if(!exists $form->{addition} && $form->{id} ne "") {
 
1100     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1101     $form->{addition}  = "STORNO";
 
1102     $form->{what_done} = "invoice";
 
1103     $form->save_history;
 
1105   # /saving the history
 
1107   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1109   $main::lxdebug->leave_sub();