1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (c) 1998-2002
 
  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 # Inventory invoicing module
 
  32 #======================================================================
 
  40 use List::MoreUtils qw(uniq);
 
  41 use List::Util qw(max sum);
 
  42 use List::UtilsBy qw(sort_by);
 
  43 use English qw(-no_match_vars);
 
  47 use SL::DB::PaymentTerm;
 
  49 require "bin/mozilla/io.pl";
 
  50 require "bin/mozilla/arap.pl";
 
  51 require "bin/mozilla/drafts.pl";
 
  60   $main::lxdebug->enter_sub();
 
  62   my $form     = $main::form;
 
  63   my $locale   = $main::locale;
 
  65   $main::auth->assert('invoice_edit');
 
  67   return $main::lxdebug->leave_sub() if (load_draft_maybe());
 
  69   if ($form->{type} eq "credit_note") {
 
  70     $form->{title} = $locale->text('Add Credit Note');
 
  72     if ($form->{storno}) {
 
  73       $form->{title} = $locale->text('Add Storno Credit Note');
 
  76     $form->{title} = $locale->text('Add Sales Invoice');
 
  81   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
 
  87   $main::lxdebug->leave_sub();
 
  91   $main::lxdebug->enter_sub();
 
  93   my $form     = $main::form;
 
  94   my $locale   = $main::locale;
 
  96   $main::auth->assert('invoice_edit');
 
  98   $form->{taxincluded_changed_by_user} = 1;
 
 100   # show history button
 
 101   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 103   my ($language_id, $printer_id);
 
 104   if ($form->{print_and_post}) {
 
 105     $form->{action}   = "print";
 
 106     $form->{resubmit} = 1;
 
 107     $language_id = $form->{language_id};
 
 108     $printer_id = $form->{printer_id};
 
 112   if ($form->{type} eq "credit_note") {
 
 113     $form->{title} = $locale->text('Edit Credit Note');
 
 114     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
 
 116     $form->{title} = $locale->text('Edit Sales Invoice');
 
 117     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
 
 121   if ($form->{print_and_post}) {
 
 122     $form->{language_id} = $language_id;
 
 123     $form->{printer_id} = $printer_id;
 
 128   $main::lxdebug->leave_sub();
 
 132   $main::lxdebug->enter_sub();
 
 134   my $form     = $main::form;
 
 135   my %myconfig = %main::myconfig;
 
 137   $main::auth->assert('invoice_edit');
 
 139   $form->{vc} = 'customer';
 
 142   $form->create_links("AR", \%myconfig, "customer");
 
 144   if ($form->{all_customer}) {
 
 145     unless ($form->{customer_id}) {
 
 146       $form->{customer_id} = $form->{all_customer}->[0]->{id};
 
 147       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
 
 151   my $editing = $form->{id};
 
 153   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
 
 154                         taxincluded currency cp_id intnotes id shipto_id
 
 157   IS->get_customer(\%myconfig, \%$form);
 
 159   #quote all_customer Bug 133
 
 160   foreach my $ref (@{ $form->{all_customer} }) {
 
 161     $ref->{name} = $form->quote($ref->{name});
 
 164   $form->restore_vars(qw(id));
 
 166   IS->retrieve_invoice(\%myconfig, \%$form);
 
 167   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
 
 168                          cp_id shipto_id delivery_term_id));
 
 169   $form->restore_vars(qw(taxincluded)) if $form->{id};
 
 170   $form->restore_vars(qw(salesman_id)) if $editing;
 
 173   # build vendor/customer drop down compatibility... don't ask
 
 174   if (@{ $form->{"all_customer"} }) {
 
 175     $form->{"selectcustomer"} = 1;
 
 176     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
 
 179   $form->{"oldcustomer"}  = $form->{customer};
 
 181   if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
 
 182     $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
 
 186 #  $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
 
 187 #  $form->{selectcustomer} = 1;
 
 189   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 192   $form->{forex} = $form->{exchangerate};
 
 193   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 195   foreach my $key (keys %{ $form->{AR_links} }) {
 
 196     foreach my $ref (@{ $form->{AR_links}{$key} }) {
 
 197       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
 
 200     if ($key eq "AR_paid") {
 
 201       next unless $form->{acc_trans}{$key};
 
 202       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 203         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 205         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 207         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
 
 208         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 209         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 210         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 211         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
 
 212         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 213         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 215         $form->{paidaccounts} = $i;
 
 218       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
 
 222   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
 
 224   $form->{AR} = $form->{AR_1} unless $form->{id};
 
 226   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
 
 227                   <= $form->datetonum($form->{closedto}, \%myconfig));
 
 229   $main::lxdebug->leave_sub();
 
 232 sub prepare_invoice {
 
 233   $main::lxdebug->enter_sub();
 
 235   my $form     = $main::form;
 
 236   my %myconfig = %main::myconfig;
 
 238   $main::auth->assert('invoice_edit');
 
 240   if ($form->{type} eq "credit_note") {
 
 241     $form->{type}     = "credit_note";
 
 242     $form->{formname} = "credit_note";
 
 244     $form->{type}     = "invoice";
 
 245     $form->{formname} = "invoice";
 
 252     foreach my $ref (@{ $form->{invoice_details} }) {
 
 255       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
 
 257       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
 
 258       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 260       my $decimalplaces        = ($dec > 2) ? $dec : 2;
 
 262       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 263       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
 
 264       $dec_qty                 = length $dec_qty;
 
 266       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
 
 268       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
 
 270       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
 
 272       $form->{rowcount}        = $i;
 
 276   $main::lxdebug->leave_sub();
 
 280   $main::lxdebug->enter_sub();
 
 282   my $form     = $main::form;
 
 283   my %myconfig = %main::myconfig;
 
 284   my $locale   = $main::locale;
 
 285   my $cgi      = $::request->{cgi};
 
 287   $main::auth->assert('invoice_edit');
 
 293     require SL::DB::Invoice;
 
 294     $TMPL_VAR{invoice_obj} = SL::DB::Invoice->new(id => $form->{id})->load;
 
 296   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
 
 297   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
 
 299   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 301   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
 
 302                    "currencies"    => "ALL_CURRENCIES",
 
 303                    "customers"     => "ALL_CUSTOMERS",
 
 304                    "departments"   => "all_departments",
 
 305                    "price_factors" => "ALL_PRICE_FACTORS");
 
 308   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
 
 309   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
 
 311   if ($::instance_conf->get_customer_projects_only_in_sales) {
 
 314         customer_id          => $::form->{customer_id},
 
 315         billable_customer_id => $::form->{customer_id},
 
 320       and => [ active => 1, @customer_cond ],
 
 324   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
 
 325   $form->{ALL_PROJECTS}            = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
 
 326   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
 
 327   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
 
 328   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
 
 329     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
 
 331   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
 
 333       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
 
 336         cp_id    => $::form->{cp_id} * 1
 
 340   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
 
 343   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 344   $TMPL_VAR{vclimit} = $myconfig{vclimit};
 
 345   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
 
 346   push @custom_hiddens, "customer_id";
 
 347   push @custom_hiddens, "oldcustomer";
 
 348   push @custom_hiddens, "selectcustomer";
 
 350   # currencies and exchangerate
 
 351   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
 
 352   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
 
 353   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
 
 354   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
 
 355   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
 
 356                                                       '-values' => \@values, '-labels' => \%labels,
 
 357                                                       '-onchange' => "document.getElementById('update_button').click();"
 
 358                                      )) if scalar @values;
 
 359   push @custom_hiddens, "forex";
 
 360   push @custom_hiddens, "exchangerate" if $form->{forex};
 
 362   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
 
 363   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
 
 365   my $follow_up_vc         =  $form->{customer};
 
 366   $follow_up_vc            =~ s/--\d*\s*$//;
 
 367   $TMPL_VAR{customer_name} = $follow_up_vc;
 
 369 # set option selected
 
 370   foreach my $item (qw(AR)) {
 
 371     $form->{"select$item"} =~ s/ selected//;
 
 372     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
 
 375   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
 
 376   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
 
 377   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
 
 378   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
 
 381   $TMPL_VAR{HIDDENS} = [qw(
 
 382     id action type media format queued printed emailed title vc discount
 
 383     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
 
 384     max_dunning_level dunning_amount dunning_description
 
 385     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
 
 386     shiptoemail shiptodepartment_1 shiptodepartment_2  shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
 
 387     convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
 
 391   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
 
 393   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
 
 395   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
 
 396   $form->{duedate}             = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
 
 400   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
 
 402   $main::lxdebug->leave_sub();
 
 406   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
 
 408     grep { $_->{paid} != 0 }
 
 411       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 412     } (1..$::form->{paidaccounts});
 
 414   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 416   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 418   foreach my $idx (1 .. scalar(@payments)) {
 
 419     my $payment = $payments[$idx - 1];
 
 420     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 425   $main::lxdebug->enter_sub();
 
 427   my $form     = $main::form;
 
 428   my %myconfig = %main::myconfig;
 
 429   my $locale   = $main::locale;
 
 431   $main::auth->assert('invoice_edit');
 
 433   $form->{invtotal}    = $form->{invsubtotal};
 
 436   $form->{rows} = max 2,
 
 437     $form->numtextrows($form->{notes},    26, 8),
 
 438     $form->numtextrows($form->{intnotes}, 35, 8);
 
 441   # tax, total and subtotal calculations
 
 442   my ($tax, $subtotal);
 
 443   $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
 
 445   if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
 
 446     my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
 
 447     $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
 
 450   foreach my $item (@{ $form->{taxaccounts_array} }) {
 
 451     if ($form->{"${item}_base"}) {
 
 452       if ($form->{taxincluded}) {
 
 453         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
 
 454                                                                                  / (1 + $form->{"${item}_rate"})), 2);
 
 455         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
 
 457         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
 
 458         $form->{invtotal} += $form->{"${item}_total"};
 
 465     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
 
 466     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
 
 473   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 474   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
 
 476   # Standard Konto für Umlaufvermögen
 
 477   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 479   for my $i (1 .. $form->{paidaccounts}) {
 
 480     $form->{"changeable_$i"} = 1;
 
 481     if (SL::DB::Default->get->payments_changeable == 0) {
 
 483       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 484     } elsif (SL::DB::Default->get->payments_changeable == 2) {
 
 486       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
 
 487                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
 
 490     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
 
 491     if (!$form->{"AR_paid_$i"}) {
 
 492       $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
 
 494       $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
 
 497     $totalpaid += $form->{"paid_$i"};
 
 500   $form->{oldinvtotal} = $form->{invtotal};
 
 502   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
 
 504   print $form->parse_html_template('is/form_footer', {
 
 505     is_type_credit_note => ($form->{type} eq "credit_note"),
 
 506     totalpaid           => $totalpaid,
 
 507     paid_missing        => $form->{invtotal} - $totalpaid,
 
 508     print_options       => print_options(inline => 1),
 
 509     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
 
 510     show_delete         => ($::instance_conf->get_is_changeable == 2)
 
 511                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 512                              : ($::instance_conf->get_is_changeable == 1),
 
 513     today               => DateTime->today,
 
 515 ##print $form->parse_html_template('is/_payments'); # parser
 
 516 ##print $form->parse_html_template('webdav/_list'); # parser
 
 518   $main::lxdebug->leave_sub();
 
 522   $main::lxdebug->enter_sub();
 
 524   my $form     = $main::form;
 
 525   my %myconfig = %main::myconfig;
 
 527   $main::auth->assert('invoice_edit');
 
 529   &mark_as_paid_common(\%myconfig,"ar");
 
 531   $main::lxdebug->leave_sub();
 
 535   $main::lxdebug->enter_sub();
 
 537   my $form     = $main::form;
 
 538   my %myconfig = %main::myconfig;
 
 540   $main::auth->assert('invoice_edit');
 
 542   my ($recursive_call) = @_;
 
 544   $form->{print_and_post} = 0         if $form->{second_run};
 
 545   my $taxincluded         = $form->{taxincluded} ? "checked" : '';
 
 548   &check_name("customer");
 
 550   $form->{taxincluded} ||= $taxincluded;
 
 552   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
 
 553     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
 
 555   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
 556   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 558   for my $i (1 .. $form->{paidaccounts}) {
 
 559     next unless $form->{"paid_$i"};
 
 560     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
 
 561     if (!$form->{"forex_$i"}) {   #read exchangerate from input field (not hidden)
 
 562       $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 564     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 565     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 568   my $i            = $form->{rowcount};
 
 569   my $exchangerate = $form->{exchangerate} || 1;
 
 571   # if last row empty, check the form otherwise retrieve new item
 
 572   if (   ($form->{"partnumber_$i"} eq "")
 
 573       && ($form->{"description_$i"} eq "")
 
 574       && ($form->{"partsgroup_$i"}  eq "")) {
 
 576     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 581     IS->retrieve_item(\%myconfig, \%$form);
 
 583     my $rows = scalar @{ $form->{item_list} };
 
 585     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
 
 586     $form->{"discount_$i"} ||= $form->{customer_discount};
 
 589       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 590       if( !$form->{"qty_$i"} ) {
 
 591         $form->{"qty_$i"} = 1;
 
 596         select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
 
 601         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 603         map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
 
 604         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
 
 606         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
 
 607         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
 
 609         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
 
 611         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 612         my $decimalplaces = max 2, length $1;
 
 615           $form->{"sellprice_$i"} = $sellprice;
 
 617           my $record        = _make_record();
 
 618           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
 
 619           my $best_price    = $price_source->best_price;
 
 620           my $best_discount = $price_source->best_discount;
 
 623             $::form->{"sellprice_$i"}           = $best_price->price;
 
 624             $::form->{"active_price_source_$i"} = $best_price->source;
 
 626           if ($best_discount) {
 
 627             $::form->{"discount_$i"}               = $best_discount->discount;
 
 628             $::form->{"active_discount_source_$i"} = $best_discount->source;
 
 631           # if there is an exchange rate adjust sellprice
 
 632           $form->{"sellprice_$i"} /= $exchangerate;
 
 635         $form->{"listprice_$i"} /= $exchangerate;
 
 637         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
 
 638         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
 
 639         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
 
 640         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
 
 642         $form->{creditremaining} -= $amount;
 
 644         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
 
 646         $form->{"qty_$i"}      = $form->format_amount(\%myconfig, $form->{"qty_$i"});
 
 647         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
 
 654       # ok, so this is a new part
 
 655       # ask if it is a part or service item
 
 657       if (   $form->{"partsgroup_$i"}
 
 658           && ($form->{"partsnumber_$i"} eq "")
 
 659           && ($form->{"description_$i"} eq "")) {
 
 661         $form->{"discount_$i"} = "";
 
 665         $form->{"id_$i"}   = 0;
 
 670   $main::lxdebug->leave_sub();
 
 674   $main::lxdebug->enter_sub();
 
 676   my $form     = $main::form;
 
 677   my %myconfig = %main::myconfig;
 
 678   my $locale   = $main::locale;
 
 680   $main::auth->assert('invoice_edit');
 
 682   $form->mtime_ischanged('ar') ;
 
 683   my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
 
 685   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 686   for my $i (1 .. $form->{paidaccounts}) {
 
 687     if ($form->{"paid_$i"}) {
 
 688       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 690       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 693       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 694         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 695           if ($invdate == $datepaid);
 
 696         $form->isblank("exchangerate_$i",
 
 697                        $locale->text('Exchangerate for payment missing!'));
 
 701   # Abgeschlossene Zeiträume nur für den letzten (aktuellen) Zahlungseingang prüfen
 
 702   # Details s.a. Bug 1502
 
 703   # Das Problem ist jetzt, dass man Zahlungseingänge nachträglich ändern kann
 
 704   # Wobei dies für Installationen die sowieso nicht mit Bücherkontrolle arbeiten keinen
 
 705   # keinen Unterschied macht.
 
 706   # Optimal wäre, wenn gegen einen Zeitstempel des Zahlungsfelds geprüft würde ...
 
 707   # Das Problem hierbei ist, dass in IS.pm post_invoice IMMER alle Zahlungseingänge aus $form
 
 708   # erneut gespeichert werden. Prinzipiell wäre es besser NUR die Änderungen des Rechnungs-
 
 709   # belegs (neue Zahlung aber nichts anderes) zu speichern ...
 
 710   # Vielleicht könnte man ähnlich wie bei Rechnung löschen verfahren
 
 711   $form->error($locale->text('Cannot post payment for a closed period!'))
 
 712     if ($form->date_closed($form->{"datepaid_$form->{paidaccounts}"}, \%myconfig));
 
 714   ($form->{AR})      = split /--/, $form->{AR};
 
 715   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
 
 717   if ( IS->post_payment(\%myconfig, \%$form) ) {
 
 718     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 719     $form->{what_done} = 'invoice';
 
 720     $form->{addition}  = "PAYMENT POSTED";
 
 722     $form->redirect($locale->text('Payment posted!'))
 
 724    $form->error($locale->text('Cannot post payment!'));
 
 727   $main::lxdebug->leave_sub();
 
 731   $main::lxdebug->enter_sub();
 
 733   my $form     = $main::form;
 
 734   my %myconfig = %main::myconfig;
 
 735   my $locale   = $main::locale;
 
 737   $main::auth->assert('invoice_edit');
 
 738   $form->mtime_ischanged('ar');
 
 740   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 741   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
 
 742   $form->isblank("customer", $locale->text('Customer missing!'));
 
 743   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
 744         if ($form->date_closed($form->{"invdate"}, \%myconfig));
 
 746   $form->{invnumber} =~ s/^\s*//g;
 
 747   $form->{invnumber} =~ s/\s*$//g;
 
 749   # if oldcustomer ne customer redo form
 
 750   if (&check_name('customer')) {
 
 755   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 756     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 761   if ($form->{second_run}) {
 
 762     $form->{print_and_post} = 0;
 
 765   remove_emptied_rows();
 
 768   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
 
 769   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
 
 771   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 772     if ($form->date_max_future($invdate, \%myconfig));
 
 773   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
 774     if ($invdate <= $closedto);
 
 776   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 777     if ($form->{currency} ne $form->{defaultcurrency});
 
 779   for my $i (1 .. $form->{paidaccounts}) {
 
 780     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 781       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 783       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 785       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 786         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
 
 788       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 789         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 790           if ($invdate == $datepaid);
 
 791         $form->isblank("exchangerate_$i",
 
 792                        $locale->text('Exchangerate for payment missing!'));
 
 797   ($form->{AR})        = split /--/, $form->{AR};
 
 798   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
 
 799   $form->{storno}    ||= 0;
 
 801   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
 
 803   $form->{id} = 0 if $form->{postasnew};
 
 805   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
 
 806   if ($form->{postasnew}) {
 
 807     if ($form->{type} eq "credit_note") {
 
 808       undef($form->{cnnumber});
 
 810       undef($form->{invnumber});
 
 816   my $terms        = get_payment_terms_for_invoice();
 
 817   $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
 
 819   # If transfer_out is requested, get rose db handle and do post and
 
 820   # transfer out in one transaction. Otherwise just post the invoice.
 
 821   if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
 
 822     require SL::DB::Inventory;
 
 823     my $rose_db = SL::DB::Inventory->new->db;
 
 826     if (!$rose_db->with_transaction(sub {
 
 828         if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
 
 829           push @errors, $locale->text('Cannot post invoice!');
 
 832         my $err = IS->transfer_out(\%$form, $rose_db->dbh);
 
 834           push @errors, @{ $err };
 
 835           die 'transfer error';
 
 840         push @errors, $EVAL_ERROR;
 
 841         die 'transaction error';
 
 846       push @errors, $rose_db->error;
 
 847       $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
 
 850     if (!IS->post_invoice(\%myconfig, \%$form)) {
 
 851       $form->error($locale->text('Cannot post invoice!'));
 
 855   remove_draft() if $form->{remove_draft};
 
 857   if(!exists $form->{addition}) {
 
 858     $form->{snumbers}  =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
 
 859     $form->{what_done} = 'invoice';
 
 860     $form->{addition}  = $form->{print_and_post} ? "PRINTED AND POSTED" :
 
 861                          $form->{storno}         ? "STORNO"             :
 
 866   if (!$form->{no_redirect_after_post}) {
 
 867     $form->{action} = 'edit';
 
 868     $form->{script} = 'is.pl';
 
 869     $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
 
 870     $form->{callback} = build_std_url(qw(action edit id callback saved_message));
 
 874   $main::lxdebug->leave_sub();
 
 878   $main::lxdebug->enter_sub();
 
 880   my $form     = $main::form;
 
 882   $main::auth->assert('invoice_edit');
 
 884   my $old_form                    = Form->new;
 
 885   $form->{no_redirect_after_post} = 1;
 
 886   $form->{print_and_post}         = 1;
 
 890   $main::lxdebug->leave_sub();
 
 895   $main::lxdebug->enter_sub();
 
 897   my $form     = $main::form;
 
 898   my %myconfig = %main::myconfig;
 
 900   $main::auth->assert('invoice_edit');
 
 902   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
 
 904   $form->{paidaccounts} = 1;
 
 905   $form->{invdate}      = $form->current_date(\%myconfig);
 
 906   my $terms             = get_payment_terms_for_invoice();
 
 907   $form->{duedate}      = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
 
 908   $form->{employee_id}  = SL::DB::Manager::Employee->current->id;
 
 909   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
 910   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 912   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
 914   $form->{useasnew} = 1;
 
 917   $main::lxdebug->leave_sub();
 
 921   $main::lxdebug->enter_sub();
 
 923   my $form     = $main::form;
 
 924   my %myconfig = %main::myconfig;
 
 925   my $locale   = $main::locale;
 
 927   $main::auth->assert('invoice_edit');
 
 929   if ($form->{storno}) {
 
 930     $form->error($locale->text('Cannot storno storno invoice!'));
 
 933   if (IS->has_storno(\%myconfig, $form, "ar")) {
 
 934     $form->error($locale->text("Invoice has already been storno'd!"));
 
 936   if ($form->datetonum($form->{invdate},  \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
 
 937     $form->error($locale->text('Cannot storno invoice for a closed period!'));
 
 940   # save the history of invoice being stornoed
 
 941   $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 942   $form->{what_done} = 'invoice';
 
 943   $form->{addition}  = "STORNO";
 
 946   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
 
 952   # Payments must not be recorded for the new storno invoice.
 
 953   $form->{paidaccounts} = 0;
 
 954   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
 
 956   $form->{storno_id} = $form->{id};
 
 959   $form->{invnumber} = "Storno zu " . $form->{invnumber};
 
 960   $form->{invdate}   = DateTime->today->to_lxoffice;
 
 962   # set new ids for storno invoice
 
 963   delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
 966   $main::lxdebug->leave_sub();
 
 970   $main::lxdebug->enter_sub();
 
 972   my $form     = $main::form;
 
 974   $main::auth->assert('invoice_edit');
 
 976   $form->{preview} = 1;
 
 977   my $old_form = Form->new;
 
 978   for (keys %$form) { $old_form->{$_} = $form->{$_} }
 
 980   &print_form($old_form);
 
 981   $main::lxdebug->leave_sub();
 
 986   $main::lxdebug->enter_sub();
 
 988   my $form     = $main::form;
 
 989   my $locale   = $main::locale;
 
 991   $main::auth->assert('invoice_edit');
 
 993   if ($form->{second_run}) {
 
 994     $form->{print_and_post} = 0;
 
 999 <form method="post" action="$form->{script}">
 
1002   # delete action variable
 
1003   map { delete $form->{$_} } qw(action header);
 
1005   foreach my $key (keys %$form) {
 
1006     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
1007     $form->{$key} =~ s/\"/"/g;
 
1008     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
 
1012 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
 
1015     . $locale->text('Are you sure you want to delete Invoice Number')
 
1016     . qq| $form->{invnumber}
 
1020 <input name="action" class="submit" type="submit" value="|
 
1021     . $locale->text('Yes') . qq|">
 
1025   $main::lxdebug->leave_sub();
 
1029   $main::lxdebug->enter_sub();
 
1031   my $form     = $main::form;
 
1032   my %myconfig = %main::myconfig;
 
1033   my $locale   = $main::locale;
 
1035   $main::auth->assert('invoice_edit');
 
1037   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
 
1039     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
 
1041   $form->{convert_from_ar_ids} = $form->{id};
 
1043   $form->{rowcount}--;
 
1046   $form->{title}  = $locale->text('Add Credit Note');
 
1047   $form->{script} = 'is.pl';
 
1049   # Bei Gutschriften bezug zur Rechnungsnummer
 
1050   $form->{invnumber_for_credit_note} = $form->{invnumber};
 
1051   # bo creates the id, reset it
 
1052   map { delete $form->{$_} }
 
1053     qw(id invnumber subject message cc bcc printed emailed queued);
 
1054   $form->{ $form->{vc} } =~ s/--.*//g;
 
1055   $form->{type} = "credit_note";
 
1058   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
 
1060 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
1061 #    qw(creditlimit creditremaining);
 
1063   # set new persistent ids for credit note and link previous invoice id
 
1064   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
1066   my $currency = $form->{currency};
 
1069   $form->{currency}     = $currency;
 
1070   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
1071   $form->{exchangerate} = $form->{forex} || '';
 
1073   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
 
1075   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
 
1076   for my $i (1 .. $form->{paidaccounts}) {
 
1077     delete $form->{"paid_$i"};
 
1078     delete $form->{"source_$i"};
 
1079     delete $form->{"memo_$i"};
 
1080     delete $form->{"datepaid_$i"};
 
1081     delete $form->{"gldate_$i"};
 
1082     delete $form->{"acc_trans_id_$i"};
 
1083     delete $form->{"AR_paid_$i"};
 
1085   $form->{paidaccounts} = 1;
 
1092   $main::lxdebug->leave_sub();
 
1096   $::lxdebug->enter_sub;
 
1098   $::auth->assert('invoice_edit');
 
1102   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
 
1103   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
 
1105   $::form->language_payment(\%::myconfig);
 
1107   Common::webdav_folder($::form);
 
1110   display_row(++$::form->{rowcount});
 
1113   $::lxdebug->leave_sub;
 
1117   $main::lxdebug->enter_sub();
 
1119   my $form     = $main::form;
 
1120   my %myconfig = %main::myconfig;
 
1121   my $locale   = $main::locale;
 
1123   $main::auth->assert('invoice_edit');
 
1125   if (IS->delete_invoice(\%myconfig, \%$form)) {
 
1126     # saving the history
 
1127     if(!exists $form->{addition}) {
 
1128       $form->{snumbers}  = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
 
1129       $form->{what_done} = 'invoice';
 
1130       $form->{addition}  = "DELETED";
 
1131       $form->save_history;
 
1133     # /saving the history
 
1134     $form->redirect($locale->text('Invoice deleted!'));
 
1136   $form->error($locale->text('Cannot delete invoice!'));
 
1138   $main::lxdebug->leave_sub();
 
1141 sub post_and_e_mail {
 
1146   $main::lxdebug->enter_sub();
 
1148   my $form     = $main::form;
 
1150   $main::auth->assert('invoice_edit');
 
1153     $form->{no_redirect_after_post} = 1;
 
1155     my $saved_form = save_form();
 
1159     restore_form($saved_form, 0, qw(id invnumber));
 
1164   $main::lxdebug->leave_sub();