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., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  28 #======================================================================
 
  30 # Accounts Receivables
 
  32 #======================================================================
 
  34 use POSIX qw(strftime);
 
  35 use List::Util qw(sum first max);
 
  36 use List::UtilsBy qw(sort_by);
 
  44 use SL::ReportGenerator;
 
  46 require "bin/mozilla/arap.pl";
 
  47 require "bin/mozilla/common.pl";
 
  48 require "bin/mozilla/reportgenerator.pl";
 
  53 # this is for our long dates
 
  54 # $locale->text('January')
 
  55 # $locale->text('February')
 
  56 # $locale->text('March')
 
  57 # $locale->text('April')
 
  58 # $locale->text('May ')
 
  59 # $locale->text('June')
 
  60 # $locale->text('July')
 
  61 # $locale->text('August')
 
  62 # $locale->text('September')
 
  63 # $locale->text('October')
 
  64 # $locale->text('November')
 
  65 # $locale->text('December')
 
  67 # this is for our short month
 
  68 # $locale->text('Jan')
 
  69 # $locale->text('Feb')
 
  70 # $locale->text('Mar')
 
  71 # $locale->text('Apr')
 
  72 # $locale->text('May')
 
  73 # $locale->text('Jun')
 
  74 # $locale->text('Jul')
 
  75 # $locale->text('Aug')
 
  76 # $locale->text('Sep')
 
  77 # $locale->text('Oct')
 
  78 # $locale->text('Nov')
 
  79 # $locale->text('Dec')
 
  82   $main::lxdebug->enter_sub();
 
  84   $main::auth->assert('general_ledger');
 
  86   my $form     = $main::form;
 
  87   my %myconfig = %main::myconfig;
 
  90   if(!exists $form->{addition} && ($form->{id} ne "")) {
 
  91     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
 
  92     $form->{addition} = "ADDED";
 
  97   $form->{title}    = "Add";
 
  98   $form->{callback} = "ar.pl?action=add" unless $form->{callback};
 
 100   AR->get_transdate(\%myconfig, $form);
 
 101   $form->{initial_transdate} = $form->{transdate};
 
 102   create_links(dont_save => 1);
 
 103   $form->{transdate} = $form->{initial_transdate};
 
 105   $main::lxdebug->leave_sub();
 
 109   $main::lxdebug->enter_sub();
 
 111   $main::auth->assert('general_ledger');
 
 113   my $form     = $main::form;
 
 115   # show history button
 
 116   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 117   #/show hhistory button
 
 118   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
 
 119   $form->{title} = "Edit";
 
 124   $main::lxdebug->leave_sub();
 
 128   $main::lxdebug->enter_sub();
 
 130   $main::auth->assert('general_ledger');
 
 132   my $form     = $main::form;
 
 137   $main::lxdebug->leave_sub();
 
 140 sub _retrieve_invoice_object {
 
 141   return undef if !$::form->{id};
 
 142   return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
 
 143   return SL::DB::Invoice->new(id => $::form->{id})->load;
 
 147   $main::lxdebug->enter_sub();
 
 149   $main::auth->assert('general_ledger');
 
 152   my $form     = $main::form;
 
 153   my %myconfig = %main::myconfig;
 
 155   $form->create_links("AR", \%myconfig, "customer");
 
 156   $form->{invoice_obj} = _retrieve_invoice_object();
 
 159   if (!$params{dont_save}) {
 
 160     %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
 
 161     $saved{duedate} = $form->{duedate} if $form->{duedate};
 
 164   IS->get_customer(\%myconfig, \%$form);
 
 166   $form->{$_}          = $saved{$_} for keys %saved;
 
 167   $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
 
 168   $form->{rowcount}    = 1;
 
 171   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 173   map { $form->{selectcurrency} .= "<option>$_\n" } $form->get_all_currencies(\%myconfig);
 
 176   if (@{ $form->{all_customer} || [] }) {
 
 177     $form->{customer} = "$form->{customer}--$form->{customer_id}";
 
 178     map { $form->{selectcustomer} .= "<option>$_->{name}--$_->{id}\n" }
 
 179       (@{ $form->{all_customer} });
 
 183   if (@{ $form->{all_departments} || [] }) {
 
 184     $form->{selectdepartment} = "<option>\n";
 
 185     $form->{department}       = "$form->{department}--$form->{department_id}";
 
 188       $form->{selectdepartment} .=
 
 189         "<option>$_->{description}--$_->{id}\n"
 
 190     } (@{ $form->{all_departments} || [] });
 
 193   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 196   if (@{ $form->{all_employees} || [] }) {
 
 197     $form->{selectemployee} = "";
 
 198     map { $form->{selectemployee} .= "<option>$_->{name}--$_->{id}\n" }
 
 199       (@{ $form->{all_employees} || [] });
 
 202   # build the popup menus
 
 203   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
 
 205   AR->setup_form($form);
 
 208     ($form->datetonum($form->{transdate}, \%myconfig) <=
 
 209      $form->datetonum($form->{closedto}, \%myconfig));
 
 211   $main::lxdebug->leave_sub();
 
 215   $main::lxdebug->enter_sub();
 
 217   $main::auth->assert('general_ledger');
 
 219   my $form     = $main::form;
 
 220   my %myconfig = %main::myconfig;
 
 221   my $locale   = $main::locale;
 
 222   my $cgi      = $::request->{cgi};
 
 224   $form->{invoice_obj} = _retrieve_invoice_object();
 
 226   my ($title, $readonly, $exchangerate, $rows);
 
 227   my ($notes, $department, $customer, $employee, $amount, $project);
 
 231   $title = $form->{title};
 
 232   # $locale->text('Add Accounts Receivables Transaction')
 
 233   # $locale->text('Edit Accounts Receivables Transaction')
 
 234   $form->{title} = $locale->text("$title Accounts Receivables Transaction");
 
 236   $form->{javascript} = qq|<script type="text/javascript">
 
 238   function setTaxkey(accno, row) {
 
 239     var taxkey = accno.options[accno.selectedIndex].value;
 
 240     var reg = /--([0-9]*)/;
 
 241     var found = reg.exec(taxkey);
 
 242     var index = found[1];
 
 243     index = parseInt(index);
 
 244     var tax = 'taxchart_' + row;
 
 245     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
 
 246       var reg2 = new RegExp("^"+ index, "");
 
 247       if (reg2.exec(document.getElementById(tax).options[i].value)) {
 
 248         document.getElementById(tax).options[i].selected = true;
 
 255   # show history button js
 
 256   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 257   #/show history button js
 
 258   $readonly = ($form->{id}) ? "readonly" : "";
 
 260   $form->{radier} = ($::instance_conf->get_ar_changeable == 2)
 
 261                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 262                       : ($::instance_conf->get_ar_changeable == 1);
 
 263   $readonly = ($form->{radier}) ? "" : $readonly;
 
 265   # set option selected
 
 266   foreach my $item (qw(customer currency department employee)) {
 
 267     $form->{"select$item"} =~ s/ selected//;
 
 268     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
 
 271   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 272   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 274   $rows = max 2, $form->numtextrows($form->{notes}, 50);
 
 276   my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
 
 278   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
 
 280                                     "old_id"    => \@old_project_ids },
 
 281                    "charts"    => { "key"       => "ALL_CHARTS",
 
 282                                     "transdate" => $form->{transdate} },
 
 283                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
 
 284                                     "module"    => "AR" },);
 
 286   $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
 
 288   my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
 
 290   my (@AR_amount_values);
 
 292   my (@AR_paid_values);
 
 297   foreach my $item (@{ $form->{ALL_CHARTS} }) {
 
 298     if ($item->{link_split}{AR_amount}) {
 
 299       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
 
 300       my $key = "$item->{accno}--$item->{tax_id}";
 
 301       push(@AR_amount_values, $key);
 
 302     } elsif ($item->{link_split}{AR}) {
 
 303       push(@AR_values, $item->{accno});
 
 304     } elsif ($item->{link_split}{AR_paid}) {
 
 305       push(@AR_paid_values, $item->{accno});
 
 308     # weirdness for AR_amount
 
 309     $chart_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
 
 310     $chart_labels{"$item->{accno}--$item->{tax_id}"} = "$item->{accno}--$item->{description}";
 
 312     $charts{$item->{accno}} = $item;
 
 315   my %taxchart_labels = ();
 
 316   my @taxchart_values = ();
 
 318   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
 
 319     my $key = "$item->{id}--$item->{rate}";
 
 320     $taxchart_init = $key if ($taxchart_init eq $item->{id});
 
 321     push(@taxchart_values, $key);
 
 322     $taxchart_labels{$key} = "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
 
 323     $taxcharts{$item->{id}} = $item;
 
 326   my $follow_up_vc         =  $form->{customer};
 
 327   $follow_up_vc            =~ s/--.*?//;
 
 328   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
 
 330   $form->{javascript} .=
 
 331     qq|<script type="text/javascript" src="js/show_vc_details.js"></script>| .
 
 332     qq|<script type="text/javascript" src="js/follow_up.js"></script>| .
 
 333     qq|<script type="text/javascript" src="js/kivi.Draft.js"></script>|;
 
 335 #  $amount  = $locale->text('Amount');
 
 336 #  $project = $locale->text('Project');
 
 339   for my $i (1 .. $form->{rowcount}) {
 
 341       amount     => $form->{"amount_$i"},
 
 342       tax        => $form->{"tax_$i"},
 
 343       project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
 
 346     my $selected_accno_full;
 
 347     my ($accno_row) = split(/--/, $form->{"AR_amount_$i"});
 
 348     my $item = $charts{$accno_row};
 
 349     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
 
 351     my $selected_taxchart = $form->{"taxchart_$i"};
 
 352     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
 
 353     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AR_amount_$i"});
 
 355     if ($previous_accno &&
 
 356         ($previous_accno eq $selected_accno) &&
 
 357         ($previous_tax_id ne $selected_tax_id)) {
 
 358       my $item = $taxcharts{$selected_tax_id};
 
 359       $selected_taxchart = "$item->{id}--$item->{rate}";
 
 362     if (!$form->{"taxchart_$i"}) {
 
 363       if ($form->{"AR_amount_$i"} =~ m/.--./) {
 
 364         $selected_taxchart = join '--', map { ($_->{id}, $_->{rate}) } first { $_->{id} == $item->{tax_id} } @{ $form->{ALL_TAXCHARTS} };
 
 366         $selected_taxchart = $taxchart_init;
 
 370     $transaction->{selectAR_amount} =
 
 371       NTI($cgi->popup_menu('-name' => "AR_amount_$i",
 
 372                            '-id' => "AR_amount_$i",
 
 373                            '-style' => 'width:400px',
 
 374                            '-onChange' => "setTaxkey(this, $i)",
 
 375                            '-values' => \@AR_amount_values,
 
 376                            '-labels' => \%chart_labels,
 
 377                            '-default' => $selected_accno_full))
 
 378       . $cgi->hidden('-name' => "previous_AR_amount_$i",
 
 379                      '-default' => $selected_accno_full);
 
 381     $transaction->{taxchart} =
 
 382       NTI($cgi->popup_menu('-name' => "taxchart_$i",
 
 383                            '-id' => "taxchart_$i",
 
 384                            '-style' => 'width:200px',
 
 385                            '-values' => \@taxchart_values,
 
 386                            '-labels' => \%taxchart_labels,
 
 387                            '-default' => $selected_taxchart));
 
 389     push @transactions, $transaction;
 
 392   $form->{invtotal_unformatted} = $form->{invtotal};
 
 395     NTI($cgi->popup_menu('-name' => "ARselected", '-id' => "ARselected",
 
 396                          '-style' => 'width:400px',
 
 397                          '-values' => \@AR_values, '-labels' => \%chart_labels,
 
 398                          '-default' => $form->{ARselected}));
 
 401   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 403   my $now = $form->current_date(\%myconfig);
 
 406   for my $i (1 .. $form->{paidaccounts}) {
 
 408       paid             => $form->{"paid_$i"},
 
 409       exchangerate     => $form->{"exchangerate_$i"} || '',
 
 410       gldate           => $form->{"gldate_$i"},
 
 411       acc_trans_id     => $form->{"acc_trans_id_$i"},
 
 412       source           => $form->{"source_$i"},
 
 413       memo             => $form->{"memo_$i"},
 
 414       AR_paid          => $form->{"AR_paid_$i"},
 
 415       forex            => $form->{"forex_$i"},
 
 416       datepaid         => $form->{"datepaid_$i"},
 
 417       paid_project_id  => $form->{"paid_project_id_$i"},
 
 418       gldate           => $form->{"gldate_$i"},
 
 421     # default account for current assets (i.e. 1801 - SKR04) if no account is selected
 
 422     $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 424     $payment->{selectAR_paid} =
 
 425       NTI($cgi->popup_menu('-name' => "AR_paid_$i",
 
 426                            '-id' => "AR_paid_$i",
 
 427                            '-values' => \@AR_paid_values,
 
 428                            '-labels' => \%chart_labels,
 
 429                            '-default' => $payment->{AR_paid} || $form->{accno_arap}));
 
 433     $payment->{changeable} =
 
 434         SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
 
 435       : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
 
 438     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 439     if ($form->date_closed($payment->{"gldate_$i"})) {
 
 440         $payment->{changeable} = 0;
 
 443     push @payments, $payment;
 
 446   my @empty = grep { $_->{paid} eq '' } @payments;
 
 448     (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
 
 452   $form->{totalpaid} = sum map { $_->{paid} } @payments;
 
 455   print $::form->parse_html_template('ar/form_header', {
 
 456     paid_missing         => $::form->{invtotal} - $::form->{totalpaid},
 
 457     show_exch            => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
 
 458     payments             => \@payments,
 
 459     transactions         => \@transactions,
 
 460     project_labels       => \%project_labels,
 
 462     ARselected           => $ARselected,
 
 464     follow_up_trans_info => $follow_up_trans_info,
 
 465     today                => DateTime->today,
 
 468   $main::lxdebug->leave_sub();
 
 472   $main::lxdebug->enter_sub();
 
 474   $main::auth->assert('general_ledger');
 
 476   my $form     = $main::form;
 
 477   my %myconfig = %main::myconfig;
 
 478   my $locale   = $main::locale;
 
 479   my $cgi      = $::request->{cgi};
 
 482     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
 
 483     if ( @{ $follow_ups} ) {
 
 484       $form->{follow_up_length} = scalar(@{$follow_ups});
 
 485       $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
 
 489   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 490   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 492   $form->{is_closed} = $transdate <= $closedto;
 
 494   # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
 
 495   $form->{show_storno_button} =
 
 497     !IS->has_storno(\%myconfig, $form, 'ar') &&
 
 498     !IS->is_storno(\%myconfig, $form, 'ar') &&
 
 499     ($form->{totalpaid} == 0 || $form->{totalpaid} eq "");
 
 501   $form->{show_mark_as_paid_button} = $form->{id} && $::instance_conf->get_ar_show_mark_as_paid();
 
 503   print $::form->parse_html_template('ar/form_footer');
 
 505   $main::lxdebug->leave_sub();
 
 509   $main::lxdebug->enter_sub();
 
 511   $main::auth->assert('general_ledger');
 
 513   my $form     = $main::form;
 
 514   my %myconfig = %main::myconfig;
 
 516   &mark_as_paid_common(\%myconfig,"ar");
 
 518   $main::lxdebug->leave_sub();
 
 522   $main::lxdebug->enter_sub();
 
 524   $main::auth->assert('general_ledger');
 
 526   my $form     = $main::form;
 
 527   my %myconfig = %main::myconfig;
 
 531   my ($totaltax, $exchangerate);
 
 533   $form->{invtotal} = 0;
 
 535   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
 
 537   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 538     qw(exchangerate creditlimit creditremaining);
 
 540   my @flds  = qw(amount AR_amount projectnumber oldprojectnumber project_id);
 
 544   for my $i (1 .. $form->{rowcount}) {
 
 545     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
 
 546     if ($form->{"amount_$i"}) {
 
 549       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
 
 552       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
 
 554       $totaltax += $form->{"tax_$i"};
 
 555       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 560   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
 
 561   $form->{rowcount} = $count + 1;
 
 562   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
 
 564   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
 
 565   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 567   $form->{invdate} = $form->{transdate};
 
 569   my %saved_variables = map +( $_ => $form->{$_} ), qw(AR AR_amount_1 taxchart_1 customer_id notes);
 
 571   &check_name("customer");
 
 573   $form->{AR} = $saved_variables{AR};
 
 574   if ($saved_variables{AR_amount_1} =~ m/.--./) {
 
 575     map { $form->{$_} = $saved_variables{$_} } qw(AR_amount_1 taxchart_1);
 
 577     delete $form->{taxchart_1};
 
 581     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
 
 583   for my $i (1 .. $form->{paidaccounts}) {
 
 584     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 587           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
 588       } qw(paid exchangerate);
 
 590       $form->{totalpaid} += $form->{"paid_$i"};
 
 592       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 593       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 597   $form->{creditremaining} -=
 
 598     ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
 
 599      $form->{oldinvtotal});
 
 600   $form->{oldinvtotal}  = $form->{invtotal};
 
 601   $form->{oldtotalpaid} = $form->{totalpaid};
 
 605   $main::lxdebug->leave_sub();
 
 609 # ToDO: fix $closedto and $invdate
 
 612   $main::lxdebug->enter_sub();
 
 614   $main::auth->assert('general_ledger');
 
 616   my $form     = $main::form;
 
 617   my %myconfig = %main::myconfig;
 
 618   my $locale   = $main::locale;
 
 620   $form->mtime_ischanged('ar');
 
 621   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 623   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 625   for my $i (1 .. $form->{paidaccounts}) {
 
 627     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 628       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 630       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 632       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 633         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 635       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 636       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 637       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 638         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 640       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 641 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
 
 642         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 647   ($form->{AR})      = split /--/, $form->{AR};
 
 648   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
 
 649   if (AR->post_payment(\%myconfig, \%$form)) {
 
 650     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 651     $form->{what_done} = 'invoice';
 
 652     $form->{addition}  = "PAYMENT POSTED";
 
 654     $form->redirect($locale->text('Payment posted!'))
 
 656     $form->error($locale->text('Cannot post payment!'));
 
 659   $main::lxdebug->leave_sub();
 
 664   $main::auth->assert('general_ledger');
 
 666   my $form     = $main::form;
 
 673   $main::lxdebug->enter_sub();
 
 675   $main::auth->assert('general_ledger');
 
 677   my $form     = $main::form;
 
 678   my %myconfig = %main::myconfig;
 
 679   my $locale   = $main::locale;
 
 683   $form->mtime_ischanged('ar');
 
 687   # check if there is an invoice number, invoice and due date
 
 688   $form->isblank("transdate", $locale->text('Invoice Date missing!'));
 
 689   $form->isblank("duedate",   $locale->text('Due Date missing!'));
 
 690   $form->isblank("customer",  $locale->text('Customer missing!'));
 
 692   if ($myconfig{mandatory_departments} && !$form->{department}) {
 
 693     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 698   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
 
 699   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
 
 701   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 702     if ($form->date_max_future($transdate, \%myconfig));
 
 704   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
 
 706   $form->error($locale->text('Zero amount posting!'))
 
 707     unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
 
 709   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 710     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
 
 714   for my $i (1 .. $form->{paidaccounts}) {
 
 715     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 716       $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 718       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 720       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 721         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 723       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 724       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 725       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 726         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 728       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
 
 729         $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
 
 730         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 735   # if oldcustomer ne customer redo form
 
 736   my ($customer) = split /--/, $form->{customer};
 
 737   if ($form->{oldcustomer} ne "$customer--$form->{customer_id}") {
 
 739     $::dispatcher->end_request;
 
 742   $form->{AR}{receivables} = $form->{ARselected};
 
 745   $form->{id} = 0 if $form->{postasnew};
 
 746   $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
 
 749   if(!exists $form->{addition} && $form->{id} ne "") {
 
 750     $form->{snumbers}  = "invnumber_$form->{invnumber}";
 
 751     $form->{what_done} = "invoice";
 
 752     $form->{addition}  = "POSTED";
 
 755   # /saving the history
 
 757   $form->redirect($locale->text('Transaction posted!')) unless $inline;
 
 759   $main::lxdebug->leave_sub();
 
 763   $main::lxdebug->enter_sub();
 
 765   $main::auth->assert('general_ledger');
 
 767   my $form     = $main::form;
 
 768   my %myconfig = %main::myconfig;
 
 770   $form->{postasnew} = 1;
 
 772   if(!exists $form->{addition} && $form->{id} ne "") {
 
 773     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 774     $form->{what_done} = "invoice";
 
 775     $form->{addition}  = "POSTED AS NEW";
 
 778   # /saving the history
 
 781   $main::lxdebug->leave_sub();
 
 785   $main::lxdebug->enter_sub();
 
 787   $main::auth->assert('general_ledger');
 
 789   my $form     = $main::form;
 
 790   my %myconfig = %main::myconfig;
 
 792   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);
 
 793   $form->{paidaccounts} = 1;
 
 795   $form->{invdate} = $form->current_date(\%myconfig);
 
 798   $main::lxdebug->leave_sub();
 
 802   $main::lxdebug->enter_sub();
 
 804   $main::auth->assert('general_ledger');
 
 806   my $form     = $main::form;
 
 807   my $locale   = $main::locale;
 
 809   $form->{title} = $locale->text('Confirm!');
 
 813   delete $form->{header};
 
 816 <form method=post action=$form->{script}>
 
 819   foreach my $key (keys %$form) {
 
 820     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 821     $form->{$key} =~ s/\"/"/g;
 
 822     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 826 <h2 class=confirm>$form->{title}</h2>
 
 829     . $locale->text('Are you sure you want to delete Transaction')
 
 830     . qq| $form->{invnumber}</h4>
 
 832 <input name=action class=submit type=submit value="|
 
 833     . $locale->text('Yes') . qq|">
 
 837   $main::lxdebug->leave_sub();
 
 841   $main::lxdebug->enter_sub();
 
 843   $main::auth->assert('general_ledger');
 
 845   my $form     = $main::form;
 
 846   my %myconfig = %main::myconfig;
 
 847   my $locale   = $main::locale;
 
 849   if (AR->delete_transaction(\%myconfig, \%$form)) {
 
 851     if(!exists $form->{addition}) {
 
 852       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 853       $form->{what_done} = "invoice";
 
 854       $form->{addition}  = "DELETED";
 
 857     # /saving the history
 
 858     $form->redirect($locale->text('Transaction deleted!'));
 
 860   $form->error($locale->text('Cannot delete transaction!'));
 
 862   $main::lxdebug->leave_sub();
 
 866   $main::lxdebug->enter_sub();
 
 868   $main::auth->assert('invoice_edit');
 
 870   my $form     = $main::form;
 
 871   my %myconfig = %main::myconfig;
 
 872   my $locale   = $main::locale;
 
 873   my $cgi      = $::request->{cgi};
 
 875   # setup customer selection
 
 876   $form->all_vc(\%myconfig, "customer", "AR");
 
 878   $form->{title}    = $locale->text('AR Transactions');
 
 880   # Auch in Rechnungsübersicht nach Kundentyp filtern - jan
 
 881   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS", "all" => 1 },
 
 882                    "departments"    => "ALL_DEPARTMENTS",
 
 883                    "customers"      => "ALL_VC",
 
 884                    "business_types" => "ALL_BUSINESS_TYPES");
 
 885   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
 
 886   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
 
 888   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
 
 889   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
 
 890    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
 
 891                                                                               'include_prefix' => 'l_',
 
 892                                                                               'include_value'  => 'Y');
 
 894   # constants and subs for template
 
 895   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 898   print $form->parse_html_template('ar/search', { %myconfig });
 
 900   $main::lxdebug->leave_sub();
 
 903 sub create_subtotal_row {
 
 904   $main::lxdebug->enter_sub();
 
 906   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
 
 908   my $form     = $main::form;
 
 909   my %myconfig = %main::myconfig;
 
 911   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
 
 913   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
 
 915   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
 
 917   map { $totals->{$_} = 0 } @{ $subtotal_columns };
 
 919   $main::lxdebug->leave_sub();
 
 924 sub ar_transactions {
 
 925   $main::lxdebug->enter_sub();
 
 927   $main::auth->assert('invoice_edit');
 
 929   my $form     = $main::form;
 
 930   my %myconfig = %main::myconfig;
 
 931   my $locale   = $main::locale;
 
 933   my ($callback, $href, @columns);
 
 935   ($form->{customer}, $form->{customer_id}) = split(/--/, $form->{customer});
 
 937   report_generator_set_default_sort('transdate', 1);
 
 939   AR->ar_transactions(\%myconfig, \%$form);
 
 941   $form->{title} = $locale->text('AR Transactions');
 
 943   my $report = SL::ReportGenerator->new(\%myconfig, $form);
 
 946     qw(ids transdate id type invnumber ordnumber cusordnumber name netamount tax amount paid
 
 947        datepaid due duedate transaction_description notes salesman employee shippingpoint shipvia
 
 948        marge_total marge_percent globalprojectnumber customernumber country ustid taxzone payment_terms charts customertype direct_debit dunning_description);
 
 950   my $ct_cvar_configs                 = CVar->get_configs('module' => 'CT');
 
 951   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
 
 952   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
 
 954   my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
 
 955   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
 
 957   my @hidden_variables = map { "l_${_}" } @columns;
 
 958   push @hidden_variables, "l_subtotal", qw(open closed customer invnumber ordnumber cusordnumber transaction_description notes project_id transdatefrom transdateto duedatefrom duedateto
 
 959                                            employee_id salesman_id business_id parts_partnumber parts_description);
 
 960   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
 
 962   $href = build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
 
 965     'ids'                     => { raw_header_data => $::request->presenter->checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
 
 966     'transdate'               => { 'text' => $locale->text('Date'), },
 
 967     'id'                      => { 'text' => $locale->text('ID'), },
 
 968     'type'                    => { 'text' => $locale->text('Type'), },
 
 969     'invnumber'               => { 'text' => $locale->text('Invoice'), },
 
 970     'ordnumber'               => { 'text' => $locale->text('Order'), },
 
 971     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
 
 972     'name'                    => { 'text' => $locale->text('Customer'), },
 
 973     'netamount'               => { 'text' => $locale->text('Amount'), },
 
 974     'tax'                     => { 'text' => $locale->text('Tax'), },
 
 975     'amount'                  => { 'text' => $locale->text('Total'), },
 
 976     'paid'                    => { 'text' => $locale->text('Paid'), },
 
 977     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
 
 978     'due'                     => { 'text' => $locale->text('Amount Due'), },
 
 979     'duedate'                 => { 'text' => $locale->text('Due Date'), },
 
 980     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
 
 981     'notes'                   => { 'text' => $locale->text('Notes'), },
 
 982     'salesman'                => { 'text' => $locale->text('Salesperson'), },
 
 983     'employee'                => { 'text' => $locale->text('Employee'), },
 
 984     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
 
 985     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
 
 986     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
 
 987     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
 
 988     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
 
 989     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
 
 990     'country'                 => { 'text' => $locale->text('Country'), },
 
 991     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
 
 992     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
 
 993     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
 
 994     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
 
 995     'customertype'            => { 'text' => $locale->text('Customer type'), },
 
 996     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
 
 997     dunning_description       => { 'text' => $locale->text('Dunning level'), },
 
1001   foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
 
1002     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
 
1003     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
 
1006   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
 
1008   $form->{"l_type"} = "Y";
 
1009   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
 
1011   $column_defs{ids}->{visible} = 'HTML';
 
1013   $report->set_columns(%column_defs);
 
1014   $report->set_column_order(@columns);
 
1016   $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
 
1018   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
 
1020   CVar->add_custom_variables_to_report('module'         => 'CT',
 
1021                                        'trans_id_field' => 'customer_id',
 
1022                                        'configs'        => $ct_cvar_configs,
 
1023                                        'column_defs'    => \%column_defs,
 
1024                                        'data'           => $form->{AR});
 
1027   if ($form->{customer}) {
 
1028     push @options, $locale->text('Customer') . " : $form->{customer}";
 
1030   if ($form->{cp_name}) {
 
1031     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
 
1033   if ($form->{department}) {
 
1034     my ($department) = split /--/, $form->{department};
 
1035     push @options, $locale->text('Department') . " : $department";
 
1037   if ($form->{department_id}) {
 
1038     push @options, $locale->text('Department Id') . " : $form->{department_id}";
 
1040   if ($form->{invnumber}) {
 
1041     push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
 
1043   if ($form->{ordnumber}) {
 
1044     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
 
1046   if ($form->{cusordnumber}) {
 
1047     push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
 
1049   if ($form->{notes}) {
 
1050     push @options, $locale->text('Notes') . " : $form->{notes}";
 
1052   if ($form->{transaction_description}) {
 
1053     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
 
1055   if ($form->{parts_partnumber}) {
 
1056     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
 
1058   if ($form->{parts_description}) {
 
1059     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
 
1061   if ($form->{transdatefrom}) {
 
1062     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
 
1064   if ($form->{transdateto}) {
 
1065     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
 
1067   if ($form->{open}) {
 
1068     push @options, $locale->text('Open');
 
1070   if ($form->{employee_id}) {
 
1071     my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
 
1072     push @options, $locale->text('Employee') . ' : ' . $employee->name;
 
1074   if ($form->{salesman_id}) {
 
1075     my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
 
1076     push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
 
1078   if ($form->{closed}) {
 
1079     push @options, $locale->text('Closed');
 
1082   $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
 
1084   $report->set_options('top_info_text'        => join("\n", @options),
 
1085                        'raw_top_info_text'    => $form->parse_html_template('ar/ar_transactions_header'),
 
1086                        'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
 
1087                        'output_format'        => 'HTML',
 
1088                        'title'                => $form->{title},
 
1089                        'attachment_basename'  => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
 
1091   $report->set_options_from_form();
 
1092   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
 
1094   # add sort and escape callback, this one we use for the add sub
 
1095   $form->{callback} = $href .= "&sort=$form->{sort}";
 
1097   # escape callback for href
 
1098   $callback = $form->escape($href);
 
1100   my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
 
1102   my %totals    = map { $_ => 0 } @subtotal_columns;
 
1103   my %subtotals = map { $_ => 0 } @subtotal_columns;
 
1107   foreach my $ar (@{ $form->{AR} }) {
 
1108     $ar->{tax} = $ar->{amount} - $ar->{netamount};
 
1109     $ar->{due} = $ar->{amount} - $ar->{paid};
 
1111     map { $subtotals{$_} += $ar->{$_};
 
1112           $totals{$_}    += $ar->{$_} } @subtotal_columns;
 
1114     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
 
1115     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
 
1117     map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
 
1119     my $is_storno  = $ar->{storno} &&  $ar->{storno_id};
 
1120     my $has_storno = $ar->{storno} && !$ar->{storno_id};
 
1123       $has_storno       ? $locale->text("Invoice with Storno (abbreviation)") :
 
1124       $is_storno        ? $locale->text("Storno (one letter abbreviation)") :
 
1125       $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
 
1126       $ar->{invoice}    ? $locale->text("Invoice (one letter abbreviation)") :
 
1127                           $locale->text("AR Transaction (abbreviation)");
 
1129     $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
 
1133     foreach my $column (@columns) {
 
1135         'data'  => $ar->{$column},
 
1136         'align' => $column_alignment{$column},
 
1140     $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
 
1141       . "&id=" . E($ar->{id}) . "&callback=${callback}";
 
1144       raw_data =>  $::request->presenter->checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
 
1149     my $row_set = [ $row ];
 
1151     if (($form->{l_subtotal} eq 'Y')
 
1152         && (($idx == (scalar @{ $form->{AR} } - 1))
 
1153             || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
 
1154       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
 
1157     $report->add_data($row_set);
 
1162   $report->add_separator();
 
1163   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
 
1165   $report->generate_with_headers();
 
1167   $main::lxdebug->leave_sub();
 
1171   $main::lxdebug->enter_sub();
 
1173   $main::auth->assert('general_ledger');
 
1175   my $form     = $main::form;
 
1176   my %myconfig = %main::myconfig;
 
1177   my $locale   = $main::locale;
 
1179   # don't cancel cancelled transactions
 
1180   if (IS->has_storno(\%myconfig, $form, 'ar')) {
 
1181     $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
 
1182     $form->error($locale->text("Transaction has already been cancelled!"));
 
1185   AR->storno($form, \%myconfig, $form->{id});
 
1187   # saving the history
 
1188   if(!exists $form->{addition} && $form->{id} ne "") {
 
1189     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1190     $form->{addition}  = "STORNO";
 
1191     $form->{what_done} = "invoice";
 
1192     $form->save_history;
 
1194   # /saving the history
 
1196   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
 
1198   $main::lxdebug->leave_sub();