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., 51 Franklin Street, Fifth Floor, Boston,
 
  29 #======================================================================
 
  31 # Inventory invoicing module
 
  33 #======================================================================
 
  38 use SL::Helper::UserPreferences::DisplayPreferences;
 
  39 use SL::MoreCommon qw(restore_form save_form);
 
  44 use List::MoreUtils qw(any uniq);
 
  45 use List::Util qw(max sum);
 
  46 use List::UtilsBy qw(sort_by);
 
  47 use English qw(-no_match_vars);
 
  49 use SL::DB::BankTransactionAccTrans;
 
  52 use SL::DB::Department;
 
  54 use SL::DB::PaymentTerm;
 
  56 require "bin/mozilla/common.pl";
 
  57 require "bin/mozilla/io.pl";
 
  65 sub _may_view_or_edit_this_invoice {
 
  66   return 1 if  $::auth->assert('invoice_edit', 1);       # may edit all invoices
 
  67   return 0 if !$::form->{id};                            # creating new invoices isn't allowed without invoice_edit
 
  68   return 1 if  $::auth->assert('sales_invoice_view', 1); # viewing is allowed with this right
 
  69   return 0 if !$::form->{globalproject_id};              # existing records without a project ID are not allowed
 
  70   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
 
  74   my $cache = $::request->cache('is.pl::_assert_access');
 
  76   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
 
  77   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
 
  81   $main::lxdebug->enter_sub();
 
  83   my $form     = $main::form;
 
  84   my $locale   = $main::locale;
 
  86   $main::auth->assert('invoice_edit');
 
  88   $form->{show_details} = $::myconfig{show_form_details};
 
  90   if ($form->{type} eq "credit_note") {
 
  91     $form->{title} = $locale->text('Add Credit Note');
 
  93     if ($form->{storno}) {
 
  94       $form->{title} = $locale->text('Add Storno Credit Note');
 
  97   } elsif ($form->{type} eq "invoice_for_advance_payment") {
 
  98     $form->{title} = $locale->text('Add Invoice for Advance Payment');
 
 100   } elsif ($form->{type} eq "final_invoice") {
 
 101     $form->{title} = $locale->text('Add Final Invoice');
 
 104     $form->{title} = $locale->text('Add Sales Invoice');
 
 109   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
 
 111   invoice_links(is_new => 1);
 
 115   $main::lxdebug->leave_sub();
 
 119   $main::lxdebug->enter_sub();
 
 121   # Delay access check to after the invoice's been loaded in
 
 122   # "invoice_links" so that project-specific invoice rights can be
 
 125   my $form     = $main::form;
 
 126   my $locale   = $main::locale;
 
 128   $form->{show_details}                = $::myconfig{show_form_details};
 
 129   $form->{taxincluded_changed_by_user} = 1;
 
 131   # show history button
 
 132   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 134   my ($language_id, $printer_id);
 
 135   if ($form->{print_and_post}) {
 
 136     $form->{action}   = "print";
 
 137     $form->{resubmit} = 1;
 
 138     $language_id = $form->{language_id};
 
 139     $printer_id = $form->{printer_id};
 
 143   if ($form->{type} eq "credit_note") {
 
 144     $form->{title} = $locale->text('Edit Credit Note');
 
 145     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
 
 147   } elsif ($form->{type} eq "invoice_for_advance_payment") {
 
 148     $form->{title} = $locale->text('Edit Invoice for Advance Payment');
 
 149     $form->{title} = $locale->text('Edit Storno Invoice for Advance Payment') if $form->{storno};
 
 151   } elsif ($form->{type} eq "final_invoice") {
 
 152     $form->{title} = $locale->text('Edit Final Invoice');
 
 155     $form->{title} = $locale->text('Edit Sales Invoice');
 
 156     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
 
 160   if ($form->{print_and_post}) {
 
 161     $form->{language_id} = $language_id;
 
 162     $form->{printer_id} = $printer_id;
 
 167   $main::lxdebug->leave_sub();
 
 171   $main::lxdebug->enter_sub();
 
 173   # Delay access check to after the invoice's been loaded so that
 
 174   # project-specific invoice rights can be evaluated.
 
 177   my $form     = $main::form;
 
 178   my %myconfig = %main::myconfig;
 
 180   $form->{vc} = 'customer';
 
 183   $form->create_links("AR", \%myconfig, "customer");
 
 187   my $editing = $form->{id};
 
 189   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
 
 190                         taxincluded currency cp_id intnotes id shipto_id
 
 193   IS->get_customer(\%myconfig, \%$form);
 
 195   $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
 
 197   $form->restore_vars(qw(id));
 
 199   IS->retrieve_invoice(\%myconfig, \%$form);
 
 200   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
 
 201                          cp_id shipto_id delivery_term_id));
 
 202   $form->restore_vars(qw(taxincluded)) if $form->{id};
 
 203   $form->restore_vars(qw(salesman_id)) if $editing;
 
 205   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 208   $form->{forex} = $form->{exchangerate};
 
 209   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 211   foreach my $key (keys %{ $form->{AR_links} }) {
 
 212     foreach my $ref (@{ $form->{AR_links}{$key} }) {
 
 213       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
 
 216     if ($key eq "AR_paid") {
 
 217       next unless $form->{acc_trans}{$key};
 
 218       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 219         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 221         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 223         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
 
 224         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 225         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 226         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 227         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
 
 228         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 229         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 231         $form->{paidaccounts} = $i;
 
 234       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
 
 238   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
 
 240   $form->{AR} = $form->{AR_1} unless $form->{id};
 
 242   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
 
 243                   <= $form->datetonum($form->{closedto}, \%myconfig));
 
 245   $main::lxdebug->leave_sub();
 
 248 sub prepare_invoice {
 
 249   $main::lxdebug->enter_sub();
 
 253   my $form     = $main::form;
 
 254   my %myconfig = %main::myconfig;
 
 256   if ($form->{type} eq "credit_note") {
 
 257     $form->{type}     = "credit_note";
 
 258     $form->{formname} = "credit_note";
 
 260   } elsif ($form->{type} eq "invoice_for_advance_payment") {
 
 261     $form->{type}     = "invoice_for_advance_payment";
 
 262     $form->{formname} = "invoice_for_advance_payment";
 
 264   } elsif ($form->{type} eq "final_invoice") {
 
 265     $form->{type}     = "final_invoice";
 
 266     $form->{formname} = "final_invoice";
 
 268   } elsif ($form->{formname} eq "proforma" ) {
 
 269     $form->{type}     = "invoice";
 
 272     $form->{type}     = "invoice";
 
 273     $form->{formname} = "invoice";
 
 280     foreach my $ref (@{ $form->{invoice_details} }) {
 
 283       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
 
 285       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
 
 286       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 288       my $decimalplaces        = ($dec > 2) ? $dec : 2;
 
 290       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 291       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
 
 292       $dec_qty                 = length $dec_qty;
 
 294       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
 
 296       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
 
 298       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
 
 300       $form->{rowcount}        = $i;
 
 304   $main::lxdebug->leave_sub();
 
 307 sub setup_is_action_bar {
 
 310   my $change_never            = $::instance_conf->get_is_changeable == 0;
 
 311   my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
 
 312   my $payments_balanced       = ($::form->{oldtotalpaid} == 0);
 
 313   my $has_storno              = ($::form->{storno} && !$::form->{storno_id});
 
 314   my $may_edit_create         = $::auth->assert('invoice_edit', 1);
 
 315   my $factur_x_enabled        = $tmpl_var->{invoice_obj} && $tmpl_var->{invoice_obj}->customer->create_zugferd_invoices_for_this_customer;
 
 316   my ($is_linked_bank_transaction, $warn_unlinked_delivery_order);
 
 318         && SL::DB::Default->get->payments_changeable != 0
 
 319         && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
 
 321       $is_linked_bank_transaction = 1;
 
 323   if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
 
 324     $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
 
 327   my $has_further_invoice_for_advance_payment;
 
 328   if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
 
 329     my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
 
 330     my $lr          = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
 
 331     $has_further_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
 
 334   my $has_final_invoice;
 
 335   if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
 
 336     my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
 
 337     my $lr          = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
 
 338     $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->invoice_type} @$lr;
 
 341   my $is_invoice_for_advance_payment_from_order;
 
 342   if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
 
 343     my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
 
 344     my $lr          = $invoice_obj->linked_records(direction => 'from', from => ['Order']);
 
 345     $is_invoice_for_advance_payment_from_order = scalar @$lr >= 1;
 
 348   for my $bar ($::request->layout->get('actionbar')) {
 
 352         submit    => [ '#form', { action => "update" } ],
 
 353         disabled  => !$may_edit_create ? t8('You must not change this invoice.')
 
 354                    : $form->{locked}   ? t8('The billing period has already been locked.')
 
 356         id        => 'update_button',
 
 357         accesskey => 'enter',
 
 363           submit   => [ '#form', { action => "post" } ],
 
 364           checks   => [ 'kivi.validate_form' ],
 
 365           confirm  => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
 
 366           disabled => !$may_edit_create                         ? t8('You must not change this invoice.')
 
 367                     : $form->{locked}                           ? t8('The billing period has already been locked.')
 
 368                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
 
 369                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
 370                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
 371                     : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
 376           submit   => [ '#form', { action => "post_payment" } ],
 
 377           checks   => [ 'kivi.validate_form' ],
 
 378           disabled => !$may_edit_create           ? t8('You must not change this invoice.')
 
 379                     : !$form->{id}                ? t8('This invoice has not been posted yet.')
 
 380                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
 382           only_if  => $form->{type} ne "invoice_for_advance_payment",
 
 384         action => [ t8('Mark as paid'),
 
 385           submit   => [ '#form', { action => "mark_as_paid" } ],
 
 386           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
 387           disabled => !$may_edit_create ? t8('You must not change this invoice.')
 
 388                     : !$form->{id}      ? t8('This invoice has not been posted yet.')
 
 390           only_if  => ($::instance_conf->get_is_show_mark_as_paid && $form->{type} ne "invoice_for_advance_payment") || $form->{type} eq 'final_invoice',
 
 392       ], # end of combobox "Post"
 
 395         action => [ t8('Storno'),
 
 396           submit   => [ '#form', { action => "storno" } ],
 
 397           confirm  => t8('Do you really want to cancel this invoice?'),
 
 398           checks   => [ 'kivi.validate_form' ],
 
 399           disabled => !$may_edit_create   ? t8('You must not change this invoice.')
 
 400                     : !$form->{id}        ? t8('This invoice has not been posted yet.')
 
 401                     : $form->{storno}     ? t8('Cannot storno storno invoice!')
 
 402                     : $form->{locked}     ? t8('The billing period has already been locked.')
 
 403                     : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
 
 406         action => [ t8('Delete'),
 
 407           submit   => [ '#form', { action => "delete" } ],
 
 408           confirm  => t8('Do you really want to delete this object?'),
 
 409           checks   => [ 'kivi.validate_form' ],
 
 410           disabled => !$may_edit_create        ? t8('You must not change this invoice.')
 
 411                     : !$form->{id}             ? t8('This invoice has not been posted yet.')
 
 412                     : $form->{locked}          ? t8('The billing period has already been locked.')
 
 413                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
 
 414                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
 
 415                     : $has_storno              ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
 
 418       ], # end of combobox "Storno"
 
 423         action => [ t8('Workflow') ],
 
 426           submit   => [ '#form', { action => "use_as_new" } ],
 
 427           checks   => [ 'kivi.validate_form' ],
 
 428           disabled => !$may_edit_create ? t8('You must not change this invoice.')
 
 429                     : !$form->{id}      ? t8('This invoice has not been posted yet.')
 
 433           t8('Further Invoice for Advance Payment'),
 
 434           submit   => [ '#form', { action => "further_invoice_for_advance_payment" } ],
 
 435           checks   => [ 'kivi.validate_form' ],
 
 436           disabled => !$may_edit_create                          ? t8('You must not change this invoice.')
 
 437                     : !$form->{id}                               ? t8('This invoice has not been posted yet.')
 
 438                     : $has_further_invoice_for_advance_payment   ? t8('This invoice has already a further invoice for advanced payment.')
 
 439                     : $has_final_invoice                         ? t8('This invoice has already a final invoice.')
 
 440                     : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
 
 442           only_if  => $form->{type} eq "invoice_for_advance_payment",
 
 446           submit   => [ '#form', { action => "final_invoice" } ],
 
 447           checks   => [ 'kivi.validate_form' ],
 
 448           disabled => !$may_edit_create                          ? t8('You must not change this invoice.')
 
 449                     : !$form->{id}                               ? t8('This invoice has not been posted yet.')
 
 450                     : $has_further_invoice_for_advance_payment   ? t8('This invoice has a further invoice for advanced payment.')
 
 451                     : $has_final_invoice                         ? t8('This invoice has already a final invoice.')
 
 452                     : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
 
 454           only_if  => $form->{type} eq "invoice_for_advance_payment",
 
 458           submit   => [ '#form', { action => "credit_note" } ],
 
 459           checks   => [ 'kivi.validate_form' ],
 
 460           disabled => !$may_edit_create              ? t8('You must not change this invoice.')
 
 461                     : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
 
 462                     : !$form->{id}                   ? t8('This invoice has not been posted yet.')
 
 463                     : $form->{storno}                ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
 
 468           submit   => [ '#form', { action => "order" } ],
 
 469           checks   => [ 'kivi.validate_form' ],
 
 470           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 472       ], # end of combobox "Workflow"
 
 475         action => [ t8('Export') ],
 
 477           ($form->{id} ? t8('Print') : t8('Preview')),
 
 478           call     => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
 
 479           checks   => [ 'kivi.validate_form' ],
 
 480           disabled => !$may_edit_create               ? t8('You must not print this invoice.')
 
 481                     : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
 
 484         action => [ t8('Print and Post'),
 
 485           call     => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
 
 486           checks   => [ 'kivi.validate_form' ],
 
 487           confirm  => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
 
 488           disabled => !$may_edit_create                         ? t8('You must not change this invoice.')
 
 489                     : $form->{locked}                           ? t8('The billing period has already been locked.')
 
 490                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
 
 491                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
 492                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
 493                     : $is_linked_bank_transaction               ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
 
 496         action => [ t8('E Mail'),
 
 497           call     => [ 'kivi.SalesPurchase.show_email_dialog' ],
 
 498           checks   => [ 'kivi.validate_form' ],
 
 499           disabled => !$may_edit_create       ? t8('You must not print this invoice.')
 
 500                     : !$form->{id}            ? t8('This invoice has not been posted yet.')
 
 501                     : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
 
 504         action => [ t8('Factur-X/ZUGFeRD'),
 
 505           submit   => [ '#form', { action => "download_factur_x_xml" } ],
 
 506           checks   => [ 'kivi.validate_form' ],
 
 507           disabled => !$may_edit_create  ? t8('You must not print this invoice.')
 
 508                     : !$form->{id}       ? t8('This invoice has not been posted yet.')
 
 509                     : !$factur_x_enabled ? t8('Creating Factur-X/ZUGFeRD invoices is not enabled for this customer.')
 
 512       ], # end of combobox "Export"
 
 515         action => [ t8('more') ],
 
 518           call     => [ 'set_history_window', $form->{id} * 1, 'glid' ],
 
 519           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 523           call     => [ 'follow_up_window' ],
 
 524           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 528           call     => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
 
 529           disabled => !$may_edit_create ? t8('You must not change this invoice.')
 
 530                     :  $form->{id}      ? t8('This invoice has already been posted.')
 
 531                     : $form->{locked}   ? t8('The billing period has already been locked.')
 
 534       ], # end of combobox "more"
 
 537   $::request->layout->add_javascripts('kivi.Validator.js');
 
 541   $main::lxdebug->enter_sub();
 
 545   my $form     = $main::form;
 
 546   my %myconfig = %main::myconfig;
 
 547   my $locale   = $main::locale;
 
 548   my $cgi      = $::request->{cgi};
 
 553   $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
 
 554   $TMPL_VAR{invoice_obj}  = SL::DB::Invoice->load_cached($form->{id})           if $form->{id};
 
 556   # only print, no mail
 
 557   $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
 
 559   my $current_employee   = SL::DB::Manager::Employee->current;
 
 560   $form->{employee_id}   = $form->{old_employee_id} if $form->{old_employee_id};
 
 561   $form->{salesman_id}   = $form->{old_salesman_id} if $form->{old_salesman_id};
 
 562   $form->{employee_id} ||= $current_employee->id;
 
 563   $form->{salesman_id} ||= $current_employee->id;
 
 565   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 567   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
 
 568                    "currencies"    => "ALL_CURRENCIES",
 
 569                    "price_factors" => "ALL_PRICE_FACTORS");
 
 571   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
 
 572   $form->{ALL_LANGUAGES}   = SL::DB::Manager::Language->get_all_sorted;
 
 575   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
 
 576   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
 
 578   if ($::instance_conf->get_customer_projects_only_in_sales) {
 
 581         customer_id          => $::form->{customer_id},
 
 582         billable_customer_id => $::form->{customer_id},
 
 587       and => [ active => 1, @customer_cond ],
 
 591   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
 
 592   $form->{ALL_PROJECTS}            = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
 
 593   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
 
 594   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
 
 595   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
 
 596     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
 
 598   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
 
 600       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
 
 603         cp_id    => $::form->{cp_id} * 1
 
 608   # currencies and exchangerate
 
 609   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
 
 610   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
 
 611   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
 
 612   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
 
 613   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
 
 614                                                       '-values' => \@values, '-labels' => \%labels,
 
 615                                                       '-onchange' => "document.getElementById('update_button').click();"
 
 616                                      )) if scalar @values;
 
 617   push @custom_hiddens, "forex";
 
 618   push @custom_hiddens, "exchangerate" if $form->{forex};
 
 620   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
 
 621   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
 
 623 # set option selected
 
 624   foreach my $item (qw(AR)) {
 
 625     $form->{"select$item"} =~ s/ selected//;
 
 626     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
 
 629   $TMPL_VAR{is_type_normal_invoice}                 = $form->{type} eq "invoice";
 
 630   $TMPL_VAR{is_type_credit_note}                    = $form->{type}   eq "credit_note";
 
 631   $TMPL_VAR{is_format_html}                         = $form->{format} eq 'html';
 
 632   $TMPL_VAR{dateformat}                             = $myconfig{dateformat};
 
 633   $TMPL_VAR{numberformat}                           = $myconfig{numberformat};
 
 634   $TMPL_VAR{longdescription_dialog_size_percentage} = SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
 
 637   $TMPL_VAR{HIDDENS} = [qw(
 
 638     id type queued printed emailed vc discount
 
 639     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
 
 640     max_dunning_level dunning_amount dunning_description
 
 641     taxaccounts cursor_fokus
 
 642     convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
 
 646   map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
 
 648   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor/ckeditor ckeditor/adapters/jquery kivi.io client_js));
 
 650   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
 
 651   $form->{duedate}             = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
 
 653   setup_is_action_bar(\%TMPL_VAR);
 
 657   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
 
 659   $main::lxdebug->leave_sub();
 
 663   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
 
 665     grep { $_->{paid} != 0 }
 
 668       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 669     } (1..$::form->{paidaccounts});
 
 671   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 673   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 675   foreach my $idx (1 .. scalar(@payments)) {
 
 676     my $payment = $payments[$idx - 1];
 
 677     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 682   $main::lxdebug->enter_sub();
 
 686   my $form     = $main::form;
 
 687   my %myconfig = %main::myconfig;
 
 688   my $locale   = $main::locale;
 
 690   $form->{invtotal}    = $form->{invsubtotal};
 
 692   # tax, total and subtotal calculations
 
 693   my ($tax, $subtotal);
 
 694   $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
 
 696   if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
 
 697     my $customer = SL::DB::Customer->load_cached($form->{customer_id});
 
 698     $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
 
 701   foreach my $item (@{ $form->{taxaccounts_array} }) {
 
 702     if ($form->{"${item}_base"}) {
 
 703       if ($form->{taxincluded}) {
 
 704         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
 
 705                                                                                  / (1 + $form->{"${item}_rate"})), 2);
 
 706         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
 
 708         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
 
 709         $form->{invtotal} += $form->{"${item}_total"};
 
 714   my $grossamount = $form->{invtotal};
 
 715   $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
 
 716   $form->{rounding} = $form->round_amount(
 
 717     $form->{invtotal} - $form->round_amount($grossamount, 2),
 
 723     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
 
 724     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
 
 731   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 732   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
 
 734   # Standard Konto für Umlaufvermögen
 
 735   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 737   for my $i (1 .. $form->{paidaccounts}) {
 
 738     $form->{"changeable_$i"} = 1;
 
 739     if (SL::DB::Default->get->payments_changeable == 0) {
 
 741       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 742     } elsif (SL::DB::Default->get->payments_changeable == 2) {
 
 744       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
 
 745                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
 
 748     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
 
 749     if ($form->date_closed($form->{"gldate_$i"})) {
 
 750       $form->{"changeable_$i"} = 0;
 
 753     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
 
 754     if (!$form->{"AR_paid_$i"}) {
 
 755       $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
 
 757       $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
 
 760     $totalpaid += $form->{"paid_$i"};
 
 763   $form->{oldinvtotal} = $form->{invtotal};
 
 765   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
 
 767   my $shipto_cvars       = SL::DB::Shipto->new->cvars_by_config;
 
 768   foreach my $var (@{ $shipto_cvars }) {
 
 769     my $name = "shiptocvar_" . $var->config->name;
 
 770     $var->value($form->{$name}) if exists $form->{$name};
 
 773   print $form->parse_html_template('is/form_footer', {
 
 774     is_type_normal_invoice              => ($form->{type} eq "invoice"),
 
 775     is_type_credit_note                 => ($form->{type} eq "credit_note"),
 
 776     totalpaid                           => $totalpaid,
 
 777     paid_missing                        => $form->{invtotal} - $totalpaid,
 
 778     print_options                       => setup_sales_purchase_print_options(),
 
 779     show_storno                         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
 
 780     show_delete                         => ($::instance_conf->get_is_changeable == 2)
 
 781                                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 782                                              : ($::instance_conf->get_is_changeable == 1),
 
 783     today                               => DateTime->today,
 
 784     vc_obj                              => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
 
 785     shipto_cvars                        => $shipto_cvars,
 
 787 ##print $form->parse_html_template('is/_payments'); # parser
 
 788 ##print $form->parse_html_template('webdav/_list'); # parser
 
 790   $main::lxdebug->leave_sub();
 
 794   $::auth->assert('invoice_edit');
 
 796   SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
 
 798   $::form->redirect($::locale->text("Marked as paid"));
 
 802   # unless no lazy implementation of save draft without invdate
 
 803   # set the current date like in version <= 3.4.1
 
 804   $::form->{invdate}   = DateTime->today->to_lxoffice;
 
 809   $main::lxdebug->enter_sub();
 
 813   my $form     = $main::form;
 
 814   my %myconfig = %main::myconfig;
 
 816   my ($recursive_call) = @_;
 
 818   $form->{print_and_post} = 0         if $form->{second_run};
 
 819   my $taxincluded         = $form->{taxincluded} ? "checked" : '';
 
 822   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
 823     $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
 
 825     IS->get_customer(\%myconfig, $form);
 
 826     $::form->{billing_address_id} = $::form->{default_billing_address_id};
 
 829   $form->{taxincluded} ||= $taxincluded;
 
 831   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
 
 832     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
 
 834   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
 835   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 837   for my $i (1 .. $form->{paidaccounts}) {
 
 838     next unless $form->{"paid_$i"};
 
 839     map { $form->{"${_}_$i"}   = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
 
 840     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 841     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 844   my $i            = $form->{rowcount};
 
 845   my $exchangerate = $form->{exchangerate} || 1;
 
 847   # if last row empty, check the form otherwise retrieve new item
 
 848   if (   ($form->{"partnumber_$i"} eq "")
 
 849       && ($form->{"description_$i"} eq "")
 
 850       && ($form->{"partsgroup_$i"}  eq "")) {
 
 852     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 857     IS->retrieve_item(\%myconfig, \%$form);
 
 859     my $rows = scalar @{ $form->{item_list} };
 
 861     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
 
 862     $form->{"discount_$i"} ||= $form->{customer_discount};
 
 865       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 866       if( !$form->{"qty_$i"} ) {
 
 867         $form->{"qty_$i"} = 1;
 
 872         select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
 
 873         $::dispatcher->end_request;
 
 877         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 879         map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
 
 880         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
 
 882         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
 
 883         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
 
 885         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
 
 887         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 888         my $decimalplaces = max 2, length $1;
 
 891           $form->{"sellprice_$i"} = $sellprice;
 
 893           my $record        = _make_record();
 
 894           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
 
 895           my $best_price    = $price_source->best_price;
 
 896           my $best_discount = $price_source->best_discount;
 
 899             $::form->{"sellprice_$i"}           = $best_price->price;
 
 900             $::form->{"active_price_source_$i"} = $best_price->source;
 
 902           if ($best_discount) {
 
 903             $::form->{"discount_$i"}               = $best_discount->discount;
 
 904             $::form->{"active_discount_source_$i"} = $best_discount->source;
 
 907           # if there is an exchange rate adjust sellprice
 
 908           $form->{"sellprice_$i"} /= $exchangerate;
 
 911         $form->{"listprice_$i"} /= $exchangerate;
 
 913         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
 
 914         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
 
 915         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
 
 916         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
 
 918         $form->{creditremaining} -= $amount;
 
 920         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
 
 922         $form->{"qty_$i"}      = $form->format_amount(\%myconfig, $form->{"qty_$i"});
 
 923         $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
 
 930       # ok, so this is a new part
 
 931       # ask if it is a part or service item
 
 933       if (   $form->{"partsgroup_$i"}
 
 934           && ($form->{"partnumber_$i" } eq "")
 
 935           && ($form->{"description_$i"} eq "")) {
 
 937         $form->{"discount_$i"} = "";
 
 941         $form->{"id_$i"}   = 0;
 
 946   $main::lxdebug->leave_sub();
 
 950   $main::lxdebug->enter_sub();
 
 952   my $form     = $main::form;
 
 953   my %myconfig = %main::myconfig;
 
 954   my $locale   = $main::locale;
 
 956   $main::auth->assert('invoice_edit');
 
 958   $form->mtime_ischanged('ar') ;
 
 959   my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
 
 961   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 962   for my $i (1 .. $form->{paidaccounts}) {
 
 963     if ($form->{"paid_$i"}) {
 
 964       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 966       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 969       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 970         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 971           if ($invdate == $datepaid);
 
 972         $form->isblank("exchangerate_$i",
 
 973                        $locale->text('Exchangerate for payment missing!'));
 
 975       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 976         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 978       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 979       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 980       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 981         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 985   ($form->{AR})      = split /--/, $form->{AR};
 
 986   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
 
 988   if ( IS->post_payment(\%myconfig, \%$form) ) {
 
 989     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 990     $form->{what_done} = 'invoice';
 
 991     $form->{addition}  = "PAYMENT POSTED";
 
 993     $form->redirect($locale->text('Payment posted!'))
 
 995    $form->error($locale->text('Cannot post payment!'));
 
 998   $main::lxdebug->leave_sub();
 
1002   $main::lxdebug->enter_sub();
 
1004   my $form     = $main::form;
 
1005   my %myconfig = %main::myconfig;
 
1006   my $locale   = $main::locale;
 
1008   $main::auth->assert('invoice_edit');
 
1009   $form->mtime_ischanged('ar');
 
1011   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
1012   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
 
1013   $form->isblank("customer_id", $locale->text('Customer missing!'));
 
1014   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
1015         if ($form->date_closed($form->{"invdate"}, \%myconfig));
 
1017   $form->{invnumber} =~ s/^\s*//g;
 
1018   $form->{invnumber} =~ s/\s*$//g;
 
1020   # if oldcustomer ne customer redo form
 
1021   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
 
1023     $::dispatcher->end_request;
 
1026   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
1027     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
1032   if ($form->{second_run}) {
 
1033     $form->{print_and_post} = 0;
 
1036   remove_emptied_rows();
 
1039   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
 
1040   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
 
1042   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
1043     if ($form->date_max_future($invdate, \%myconfig));
 
1044   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
1045     if ($invdate <= $closedto);
 
1047   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
1048     if ($form->{currency} ne $form->{defaultcurrency});
 
1049   # advance payment allows only one tax
 
1050   if ($form->{type} eq 'invoice_for_advance_payment') {
 
1051     my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
 
1052     $form->error($locale->text('Cannot post invoice for advance payment with more than one tax'))
 
1053       if (scalar @current_taxaccounts > 1);
 
1054     $form->error($locale->text('Cannot post invoice for advance payment with taxincluded'))
 
1055       if ($form->{taxincluded});
 
1058   for my $i (1 .. $form->{paidaccounts}) {
 
1059     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
1060       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
1062       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
1064       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
1065         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
1067       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
1068       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
1069       $form->error($locale->text('Cannot post payment for a closed period!'))
 
1070         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
1072       if ($form->{currency} ne $form->{defaultcurrency}) {
 
1073         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
1074           if ($invdate == $datepaid);
 
1075         $form->isblank("exchangerate_$i",
 
1076                        $locale->text('Exchangerate for payment missing!'));
 
1081   ($form->{AR})        = split /--/, $form->{AR};
 
1082   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
 
1083   $form->{storno}    ||= 0;
 
1085   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
 
1087   $form->{id} = 0 if $form->{postasnew};
 
1089   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
 
1090   if ($form->{postasnew}) {
 
1091     if ($form->{type} eq "credit_note") {
 
1092       undef($form->{cnnumber});
 
1094       undef($form->{invnumber});
 
1100   my $terms        = get_payment_terms_for_invoice();
 
1101   $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
 
1103   # If transfer_out is requested, get rose db handle and do post and
 
1104   # transfer out in one transaction. Otherwise just post the invoice.
 
1105   if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
 
1106     require SL::DB::Inventory;
 
1107     my $rose_db = SL::DB::Inventory->new->db;
 
1110     if (!$rose_db->with_transaction(sub {
 
1112         if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
 
1113           push @errors, $locale->text('Cannot post invoice!');
 
1114           die 'posting error';
 
1116         my $err = IS->transfer_out(\%$form, $rose_db->dbh);
 
1118           push @errors, @{ $err };
 
1119           die 'transfer error';
 
1124         push @errors, $EVAL_ERROR;
 
1125         $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
 
1130       push @errors, $rose_db->error;
 
1131       $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
 
1134     if (!IS->post_invoice(\%myconfig, \%$form)) {
 
1135       $form->error($locale->text('Cannot post invoice!'));
 
1139   if(!exists $form->{addition}) {
 
1140     $form->{snumbers}  =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
 
1141     $form->{what_done} = 'invoice';
 
1142     $form->{addition}  = $form->{print_and_post} ? "PRINTED AND POSTED" :
 
1143                          $form->{storno}         ? "STORNO"             :
 
1145     $form->save_history;
 
1148   if (!$form->{no_redirect_after_post}) {
 
1149     $form->{action} = 'edit';
 
1150     $form->{script} = 'is.pl';
 
1151     $form->{callback} = build_std_url(qw(action edit id callback saved_message));
 
1152     $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
 
1155   $main::lxdebug->leave_sub();
 
1158 sub print_and_post {
 
1159   $main::lxdebug->enter_sub();
 
1161   my $form     = $main::form;
 
1163   $main::auth->assert('invoice_edit');
 
1165   my $old_form                    = Form->new;
 
1166   $form->{no_redirect_after_post} = 1;
 
1167   $form->{print_and_post}         = 1;
 
1171   $main::lxdebug->leave_sub();
 
1176   $main::lxdebug->enter_sub();
 
1178   my $form     = $main::form;
 
1179   my %myconfig = %main::myconfig;
 
1181   $main::auth->assert('invoice_edit');
 
1183   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)};
 
1184   $form->{rowcount}--;
 
1185   $form->{paidaccounts} = 1;
 
1186   $form->{invdate}      = $form->current_date(\%myconfig);
 
1187   my $terms             = get_payment_terms_for_invoice();
 
1188   $form->{duedate}      = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
 
1189   $form->{employee_id}  = SL::DB::Manager::Employee->current->id;
 
1190   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
1191   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
1193   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
1195   $form->{useasnew} = 1;
 
1198   $main::lxdebug->leave_sub();
 
1201 sub further_invoice_for_advance_payment {
 
1202   my $form     = $main::form;
 
1203   my %myconfig = %main::myconfig;
 
1205   $main::auth->assert('invoice_edit');
 
1207   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
 
1208   $form->{convert_from_ar_ids} = $form->{id};
 
1210   $form->{rowcount}--;
 
1211   $form->{paidaccounts}        = 1;
 
1212   $form->{invdate}             = $form->current_date(\%myconfig);
 
1213   my $terms                    = get_payment_terms_for_invoice();
 
1214   $form->{duedate}             = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
 
1215   $form->{employee_id}         = SL::DB::Manager::Employee->current->id;
 
1216   $form->{forex}               = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
1217   $form->{exchangerate}        = $form->{forex} if $form->{forex};
 
1219   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
1225   my $form     = $main::form;
 
1226   my %myconfig = %main::myconfig;
 
1228   $main::auth->assert('invoice_edit');
 
1230   my $related_invoices = IS->_get_invoices_for_advance_payment($form->{id});
 
1232   delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
 
1234   $form->{convert_from_ar_ids} = $form->{id};
 
1236   $form->{type}                = 'final_invoice';
 
1237   $form->{title}               = t8('Edit Final Invoice');
 
1238   $form->{paidaccounts}        = 1;
 
1239   $form->{invdate}             = $form->current_date(\%myconfig);
 
1240   my $terms                    = get_payment_terms_for_invoice();
 
1241   $form->{duedate}             = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
 
1242   $form->{employee_id}         = SL::DB::Manager::Employee->current->id;
 
1243   $form->{forex}               = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
1244   $form->{exchangerate}        = $form->{forex} if $form->{forex};
 
1246   foreach my $i (1 .. $form->{"rowcount"}) {
 
1247     delete $form->{"id_$i"};
 
1248     delete $form->{"invoice_id_$i"};
 
1249     delete $form->{"parts_id_$i"};
 
1250     delete $form->{"partnumber_$i"};
 
1251     delete $form->{"description_$i"};
 
1254   remove_emptied_rows(1);
 
1257   foreach my $ri (@$related_invoices) {
 
1258     foreach my $item (@{$ri->items_sorted}) {
 
1260       $form->{"id_$i"}         = $item->parts_id;
 
1261       $form->{"partnumber_$i"} = $item->part->partnumber;
 
1262       $form->{"discount_$i"}   = $item->discount*100.0;
 
1263       $form->{"sellprice_$i"}  = $item->fxsellprice;
 
1264       $form->{$_ . "_" . $i}   = $item->$_       for qw(description longdescription qty price_factor_id unit active_price_source active_discount_source);
 
1266       $form->{$_ . "_" . $i}   = $form->format_amount(\%myconfig, $form->{$_ . "_" . $i}) for qw(qty sellprice discount);
 
1269   $form->{rowcount} = $i;
 
1272   $::dispatcher->end_request;
 
1276   $main::lxdebug->enter_sub();
 
1278   my $form     = $main::form;
 
1279   my %myconfig = %main::myconfig;
 
1280   my $locale   = $main::locale;
 
1282   $main::auth->assert('invoice_edit');
 
1284   if ($form->{storno}) {
 
1285     $form->error($locale->text('Cannot storno storno invoice!'));
 
1288   if (IS->has_storno(\%myconfig, $form, "ar")) {
 
1289     $form->error($locale->text("Invoice has already been storno'd!"));
 
1291   if ($form->datetonum($form->{invdate},  \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
 
1292     $form->error($locale->text('Cannot storno invoice for a closed period!'));
 
1295   # save the history of invoice being stornoed
 
1296   $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
1297   $form->{what_done} = 'invoice';
 
1298   $form->{addition}  = "STORNO";
 
1299   $form->save_history;
 
1301   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
 
1307   # Payments must not be recorded for the new storno invoice.
 
1308   $form->{paidaccounts} = 0;
 
1309   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
 
1311   # record link invoice to storno
 
1312   $form->{convert_from_ar_ids} = $form->{id};
 
1313   $form->{storno_id} = $form->{id};
 
1314   $form->{storno} = 1;
 
1316   $form->{invnumber} = "Storno zu " . $form->{invnumber};
 
1317   $form->{invdate}   = DateTime->today->to_lxoffice;
 
1318   $form->{rowcount}++;
 
1319   # set new ids for storno invoice
 
1320   # set new persistent ids for storno invoice items
 
1321   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
1324   $main::lxdebug->leave_sub();
 
1328   $main::lxdebug->enter_sub();
 
1330   my $form     = $main::form;
 
1332   $main::auth->assert('invoice_edit');
 
1334   $form->{preview} = 1;
 
1335   my $old_form = Form->new;
 
1336   for (keys %$form) { $old_form->{$_} = $form->{$_} }
 
1338   &print_form($old_form);
 
1339   $main::lxdebug->leave_sub();
 
1344   $main::lxdebug->enter_sub();
 
1346   my $form     = $main::form;
 
1347   my %myconfig = %main::myconfig;
 
1348   my $locale   = $main::locale;
 
1350   $main::auth->assert('invoice_edit');
 
1352   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
 
1354     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
 
1356   $form->{convert_from_ar_ids} = $form->{id};
 
1358   $form->{rowcount}--;
 
1361   $form->{title}  = $locale->text('Add Credit Note');
 
1362   $form->{script} = 'is.pl';
 
1364   # Bei Gutschriften bezug zur Rechnungsnummer
 
1365   $form->{invnumber_for_credit_note} = $form->{invnumber};
 
1366   # bo creates the id, reset it
 
1367   map { delete $form->{$_} }
 
1368     qw(id invnumber subject message cc bcc printed emailed queued);
 
1369   $form->{ $form->{vc} } =~ s/--.*//g;
 
1370   $form->{type} = "credit_note";
 
1373   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
 
1375 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
1376 #    qw(creditlimit creditremaining);
 
1378   # set new persistent ids for credit note and link previous invoice id
 
1379   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
1381   my $currency = $form->{currency};
 
1384   $form->{currency}     = $currency;
 
1385   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
1386   $form->{exchangerate} = $form->{forex} || '';
 
1388   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
 
1390   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
 
1391   for my $i (1 .. $form->{paidaccounts}) {
 
1392     delete $form->{"paid_$i"};
 
1393     delete $form->{"source_$i"};
 
1394     delete $form->{"memo_$i"};
 
1395     delete $form->{"datepaid_$i"};
 
1396     delete $form->{"gldate_$i"};
 
1397     delete $form->{"acc_trans_id_$i"};
 
1398     delete $form->{"AR_paid_$i"};
 
1400   $form->{paidaccounts} = 1;
 
1406   $main::lxdebug->leave_sub();
 
1410   $::lxdebug->enter_sub;
 
1416   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
 
1417   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
 
1419   $::form->language_payment(\%::myconfig);
 
1421   Common::webdav_folder($::form);
 
1424   display_row(++$::form->{rowcount});
 
1427   $::lxdebug->leave_sub;
 
1431   $::auth->assert('invoice_edit');
 
1433   if (IS->delete_invoice(\%::myconfig, $::form)) {
 
1434     # saving the history
 
1435     if(!exists $::form->{addition}) {
 
1436       $::form->{snumbers}  = 'invnumber' .'_'. $::form->{invnumber};
 
1437       $::form->{what_done} = 'invoice';
 
1438       $::form->{addition}  = "DELETED";
 
1439       $::form->save_history;
 
1441     # /saving the history
 
1442     $::form->redirect($::locale->text('Invoice deleted!'));
 
1444   $::form->error($::locale->text('Cannot delete invoice!'));
 
1449     print update ship_to storno post_payment use_as_new credit_note
 
1450     delete post order preview post_and_e_mail print_and_post
 
1453     if ($::form->{"action_$action"}) {
 
1459   $::form->error($::locale->text('No action defined.'));