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);
 
  46 require "bin/mozilla/io.pl";
 
  47 require "bin/mozilla/invoice_io.pl";
 
  48 require "bin/mozilla/arap.pl";
 
  49 require "bin/mozilla/drafts.pl";
 
  58   $main::lxdebug->enter_sub();
 
  60   my $form     = $main::form;
 
  61   my $locale   = $main::locale;
 
  63   $main::auth->assert('invoice_edit');
 
  65   return $main::lxdebug->leave_sub() if (load_draft_maybe());
 
  67   if ($form->{type} eq "credit_note") {
 
  68     $form->{title} = $locale->text('Add Credit Note');
 
  70     if ($form->{storno}) {
 
  71       $form->{title} = $locale->text('Add Storno Credit Note');
 
  74     $form->{title} = $locale->text('Add Sales Invoice');
 
  79   $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
 
  85   $main::lxdebug->leave_sub();
 
  89   $main::lxdebug->enter_sub();
 
  91   my $form     = $main::form;
 
  92   my $locale   = $main::locale;
 
  94   $main::auth->assert('invoice_edit');
 
  96   $form->{taxincluded_changed_by_user} = 1;
 
  99   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
 
 100   #/show hhistory button
 
 102   my ($language_id, $printer_id);
 
 103   if ($form->{print_and_post}) {
 
 104     $form->{action}   = "print";
 
 105     $form->{resubmit} = 1;
 
 106     $language_id = $form->{language_id};
 
 107     $printer_id = $form->{printer_id};
 
 111   if ($form->{type} eq "credit_note") {
 
 112     $form->{title} = $locale->text('Edit Credit Note');
 
 113     $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
 
 115     $form->{title} = $locale->text('Edit Sales Invoice');
 
 116     $form->{title} = $locale->text('Edit Storno Invoice')     if $form->{storno};
 
 120   if ($form->{print_and_post}) {
 
 121     $form->{language_id} = $language_id;
 
 122     $form->{printer_id} = $printer_id;
 
 127   $main::lxdebug->leave_sub();
 
 131   $main::lxdebug->enter_sub();
 
 133   my $form     = $main::form;
 
 134   my %myconfig = %main::myconfig;
 
 136   $main::auth->assert('invoice_edit');
 
 138   $form->{vc} = 'customer';
 
 141   $form->{webdav}   = $::instance_conf->get_webdav;
 
 143   $form->create_links("AR", \%myconfig, "customer");
 
 145   if ($form->{all_customer}) {
 
 146     unless ($form->{customer_id}) {
 
 147       $form->{customer_id} = $form->{all_customer}->[0]->{id};
 
 148       $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
 
 152   my $editing = $form->{id};
 
 154   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
 
 155                         taxincluded currency cp_id intnotes id shipto_id
 
 158   $form->{shipto} = 1 if $editing || $form->{convert_from_oe_ids} || $form->{convert_from_do_ids};
 
 159   IS->get_customer(\%myconfig, \%$form);
 
 161   #quote all_customer Bug 133
 
 162   foreach my $ref (@{ $form->{all_customer} }) {
 
 163     $ref->{name} = $form->quote($ref->{name});
 
 166   $form->restore_vars(qw(id));
 
 168   IS->retrieve_invoice(\%myconfig, \%$form);
 
 169   $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
 
 170                          cp_id shipto_id delivery_term_id));
 
 171   $form->restore_vars(qw(taxincluded)) if $form->{id};
 
 172   $form->restore_vars(qw(salesman_id)) if $editing;
 
 175   # build vendor/customer drop down comatibility... don't ask
 
 176   if (@{ $form->{"all_customer"} }) {
 
 177     $form->{"selectcustomer"} = 1;
 
 178     $form->{customer}         = qq|$form->{customer}--$form->{"customer_id"}|;
 
 181   $form->{"oldcustomer"}  = $form->{customer};
 
 183   if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
 
 184     $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
 
 188 #  $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
 
 189 #  $form->{selectcustomer} = 1;
 
 191   $form->{employee} = "$form->{employee}--$form->{employee_id}";
 
 194   $form->{forex} = $form->{exchangerate};
 
 195   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 197   foreach my $key (keys %{ $form->{AR_links} }) {
 
 198     foreach my $ref (@{ $form->{AR_links}{$key} }) {
 
 199       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
 
 202     if ($key eq "AR_paid") {
 
 203       next unless $form->{acc_trans}{$key};
 
 204       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 205         $form->{"AR_paid_$i"}      = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 207         $form->{"acc_trans_id_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 209         $form->{"paid_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
 
 210         $form->{"datepaid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 211         $form->{"gldate_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 212         $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 213         $form->{"forex_$i"}        = $form->{"exchangerate_$i"};
 
 214         $form->{"source_$i"}       = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 215         $form->{"memo_$i"}         = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 217         $form->{paidaccounts} = $i;
 
 220       $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
 
 224   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
 
 226   $form->{AR} = $form->{AR_1} unless $form->{id};
 
 228   $form->{locked} = ($form->datetonum($form->{invdate},  \%myconfig)
 
 229                   <= $form->datetonum($form->{closedto}, \%myconfig));
 
 231   $main::lxdebug->leave_sub();
 
 234 sub prepare_invoice {
 
 235   $main::lxdebug->enter_sub();
 
 237   my $form     = $main::form;
 
 238   my %myconfig = %main::myconfig;
 
 240   $main::auth->assert('invoice_edit');
 
 242   if ($form->{type} eq "credit_note") {
 
 243     $form->{type}     = "credit_note";
 
 244     $form->{formname} = "credit_note";
 
 246     $form->{type}     = "invoice";
 
 247     $form->{formname} = "invoice";
 
 254     foreach my $ref (@{ $form->{invoice_details} }) {
 
 257       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
 
 259       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
 
 260       my ($dec)                = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 262       my $decimalplaces        = ($dec > 2) ? $dec : 2;
 
 264       $form->{"sellprice_$i"}  = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 265       (my $dec_qty)            = ($form->{"qty_$i"} =~ /\.(\d+)/);
 
 266       $dec_qty                 = length $dec_qty;
 
 268       $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
 
 270       $form->{"qty_$i"}        = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
 
 272       $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
 
 274       $form->{rowcount}        = $i;
 
 278     # get pricegroups for parts
 
 279     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 281     # Problem: set_pricegroup resets the sellprice of old invoices to the price
 
 282     # currently defined in the pricegroup, which is a problem if the price has
 
 283     # changed, as the old invoice gets the new price
 
 284     # set_pricegroup must never be called, when an old invoice is initially loaded
 
 286     # set_pricegroup($_) for 1 .. $form->{rowcount};
 
 288   $main::lxdebug->leave_sub();
 
 292   $main::lxdebug->enter_sub();
 
 294   my $form     = $main::form;
 
 295   my %myconfig = %main::myconfig;
 
 296   my $locale   = $main::locale;
 
 297   my $cgi      = $::request->{cgi};
 
 299   $main::auth->assert('invoice_edit');
 
 304   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
 
 305   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
 
 307   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 309   $form->get_lists("taxzones"      => "ALL_TAXZONES",
 
 310                    "currencies"    => "ALL_CURRENCIES",
 
 311                    "customers"     => "ALL_CUSTOMERS",
 
 312                    "departments"   => "all_departments",
 
 313                    "price_factors" => "ALL_PRICE_FACTORS");
 
 316   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
 
 317   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
 
 319   if ($::instance_conf->get_customer_projects_only_in_sales) {
 
 322         customer_id          => $::form->{customer_id},
 
 323         billable_customer_id => $::form->{customer_id},
 
 328       and => [ active => 1, @customer_cond ],
 
 332   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all(query => \@conditions);
 
 333   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
 
 334   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
 
 335   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
 
 336     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
 
 338   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
 
 340       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
 
 343         cp_id    => $::form->{cp_id} * 1
 
 347   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
 
 350   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 351   $TMPL_VAR{vclimit} = $myconfig{vclimit};
 
 352   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
 
 353   push @custom_hiddens, "customer_id";
 
 354   push @custom_hiddens, "oldcustomer";
 
 355   push @custom_hiddens, "selectcustomer";
 
 357   # currencies and exchangerate
 
 358   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
 
 359   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
 
 360   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
 
 361   $form->{show_exchangerate}   = $form->{currency} ne $form->{defaultcurrency};
 
 362   $TMPL_VAR{currencies}        = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
 
 363                                                       '-values' => \@values, '-labels' => \%labels,
 
 364                                                       '-onchange' => "document.getElementById('update_button').click();"
 
 365                                      )) if scalar @values;
 
 366   push @custom_hiddens, "forex";
 
 367   push @custom_hiddens, "exchangerate" if $form->{forex};
 
 369   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
 
 370   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
 
 372   my $follow_up_vc         =  $form->{customer};
 
 373   $follow_up_vc            =~ s/--\d*\s*$//;
 
 374   $TMPL_VAR{customer_name} = $follow_up_vc;
 
 376 # set option selected
 
 377   foreach my $item (qw(AR)) {
 
 378     $form->{"select$item"} =~ s/ selected//;
 
 379     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
 
 382   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
 
 383   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
 
 384   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
 
 385   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
 
 388   $TMPL_VAR{HIDDENS} = [qw(
 
 389     id action type media format queued printed emailed title vc discount
 
 390     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
 
 391     max_dunning_level dunning_amount
 
 392     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
 
 393     shiptoemail shiptodepartment_1 shiptodepartment_2  shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
 
 394     convert_from_do_ids convert_from_oe_ids
 
 397   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
 
 399   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery));
 
 403   print $form->parse_html_template("is/form_header", \%TMPL_VAR);
 
 405   $main::lxdebug->leave_sub();
 
 409   $main::lxdebug->enter_sub();
 
 411   my $form     = $main::form;
 
 412   my %myconfig = %main::myconfig;
 
 413   my $locale   = $main::locale;
 
 415   $main::auth->assert('invoice_edit');
 
 417   $form->{invtotal}    = $form->{invsubtotal};
 
 420   $form->{rows} = max 2,
 
 421     $form->numtextrows($form->{notes},    26, 8),
 
 422     $form->numtextrows($form->{intnotes}, 35, 8);
 
 425   # tax, total and subtotal calculations
 
 426   my ($tax, $subtotal);
 
 427   $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
 
 429   if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
 
 430     my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
 
 431     $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
 
 434   foreach my $item (@{ $form->{taxaccounts_array} }) {
 
 435     if ($form->{"${item}_base"}) {
 
 436       if ($form->{taxincluded}) {
 
 437         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
 
 438                                                                                  / (1 + $form->{"${item}_rate"})), 2);
 
 439         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
 
 441         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
 
 442         $form->{invtotal} += $form->{"${item}_total"};
 
 449     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
 
 450     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
 
 455   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 456   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
 
 458   # Standard Konto für Umlaufvermögen
 
 459   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 461   for my $i (1 .. $form->{paidaccounts}) {
 
 462     $form->{"changeable_$i"} = 1;
 
 463     if (SL::DB::Default->get->payments_changeable == 0) {
 
 465       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 466     } elsif (SL::DB::Default->get->payments_changeable == 2) {
 
 468       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
 
 469                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
 
 472     $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
 
 473     if (!$form->{"AR_paid_$i"}) {
 
 474       $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
 
 476       $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
 
 479     $totalpaid += $form->{"paid_$i"};
 
 482   $form->{oldinvtotal} = $form->{invtotal};
 
 484   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
 
 486   print $form->parse_html_template('is/form_footer', {
 
 487     is_type_credit_note => ($form->{type} eq "credit_note"),
 
 488     totalpaid           => $totalpaid,
 
 489     paid_missing        => $form->{invtotal} - $totalpaid,
 
 490     print_options       => print_options(inline => 1),
 
 491     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
 
 492     show_delete         => ($::instance_conf->get_is_changeable == 2)
 
 493                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 494                              : ($::instance_conf->get_is_changeable == 1),
 
 496 ##print $form->parse_html_template('is/_payments'); # parser
 
 497 ##print $form->parse_html_template('webdav/_list'); # parser
 
 499   $main::lxdebug->leave_sub();
 
 503   $main::lxdebug->enter_sub();
 
 505   my $form     = $main::form;
 
 506   my %myconfig = %main::myconfig;
 
 508   $main::auth->assert('invoice_edit');
 
 510   &mark_as_paid_common(\%myconfig,"ar");
 
 512   $main::lxdebug->leave_sub();
 
 516   $main::lxdebug->enter_sub();
 
 518   my $form     = $main::form;
 
 519   my %myconfig = %main::myconfig;
 
 521   $main::auth->assert('invoice_edit');
 
 523   my ($recursive_call) = @_;
 
 525   $form->{print_and_post} = 0         if $form->{second_run};
 
 526   my $taxincluded         = $form->{taxincluded} ? "checked" : '';
 
 529   &check_name("customer");
 
 531   $form->{taxincluded} ||= $taxincluded;
 
 533   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
 
 534     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
 
 536   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
 537   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 539   for my $i (1 .. $form->{paidaccounts}) {
 
 540     next unless $form->{"paid_$i"};
 
 541     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
 
 542     if (!$form->{"forex_$i"}) {   #read exchangerate from input field (not hidden)
 
 543       $form->{exchangerate} = $form->{"exchangerate_$i"};
 
 545     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
 
 546     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 549   my $i            = $form->{rowcount};
 
 550   my $exchangerate = $form->{exchangerate} || 1;
 
 552   # if last row empty, check the form otherwise retrieve new item
 
 553   if (   ($form->{"partnumber_$i"} eq "")
 
 554       && ($form->{"description_$i"} eq "")
 
 555       && ($form->{"partsgroup_$i"}  eq "")) {
 
 557     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 562     IS->retrieve_item(\%myconfig, \%$form);
 
 564     my $rows = scalar @{ $form->{item_list} };
 
 566     # Falls kein Kundenrabatt vorhanden ist, den aktuellen Rabatt nicht mit 0% überschreiben,
 
 567     # da hier der Anwender schon manual einen Wert eingetragen haben könnte (analog zu qty) Bugfix: 1412
 
 568     if ($form->{customer_discount}){
 
 569       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{customer_discount} * 100);
 
 573       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 574       if( !$form->{"qty_$i"} ) {
 
 575         $form->{"qty_$i"} = 1;
 
 580         select_item(mode => 'IS');
 
 585         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 587         map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
 
 588         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
 
 590         $form->{payment_id}    = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
 
 591         $form->{"discount_$i"} = 0                             if $form->{"not_discountable_$i"};
 
 593         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
 
 595         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 596         my $decimalplaces = max 2, length $1;
 
 599           $form->{"sellprice_$i"} = $sellprice;
 
 601           # if there is an exchange rate adjust sellprice
 
 602           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
 
 603           $form->{"sellprice_$i"} /= $exchangerate;
 
 606         $form->{"listprice_$i"} /= $exchangerate;
 
 608         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
 
 609         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
 
 610         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
 
 611         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
 
 613         $form->{creditremaining} -= $amount;
 
 615         map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
 
 617         $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
 
 619         # get pricegroups for parts
 
 620         IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 622         # build up html code for prices_$i
 
 630       # ok, so this is a new part
 
 631       # ask if it is a part or service item
 
 633       if (   $form->{"partsgroup_$i"}
 
 634           && ($form->{"partsnumber_$i"} eq "")
 
 635           && ($form->{"description_$i"} eq "")) {
 
 637         $form->{"discount_$i"} = "";
 
 641         $form->{"id_$i"}   = 0;
 
 646   $main::lxdebug->leave_sub();
 
 650   $main::lxdebug->enter_sub();
 
 652   my $form     = $main::form;
 
 653   my %myconfig = %main::myconfig;
 
 654   my $locale   = $main::locale;
 
 656   $main::auth->assert('invoice_edit');
 
 658   my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
 
 660   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 661   for my $i (1 .. $form->{paidaccounts}) {
 
 662     if ($form->{"paid_$i"}) {
 
 663       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 665       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 668       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 669         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 670           if ($invdate == $datepaid);
 
 671         $form->isblank("exchangerate_$i",
 
 672                        $locale->text('Exchangerate for payment missing!'));
 
 676   # Abgeschlossene Zeiträume nur für den letzten (aktuellen) Zahlungseingang prüfen
 
 677   # Details s.a. Bug 1502
 
 678   # Das Problem ist jetzt, dass man Zahlungseingänge nachträglich ändern kann
 
 679   # Wobei dies für Installationen die sowieso nicht mit Bücherkontrolle arbeiten keinen
 
 680   # keinen Unterschied macht.
 
 681   # Optimal wäre, wenn gegen einen Zeitstempel des Zahlungsfelds geprüft würde ...
 
 682   # Das Problem hierbei ist, dass in IS.pm post_invoice IMMER alle Zahlungseingänge aus $form
 
 683   # erneut gespeichert werden. Prinzipiell wäre es besser NUR die Änderungen des Rechnungs-
 
 684   # belegs (neue Zahlung aber nichts anderes) zu speichern ...
 
 685   # Vielleicht könnte man ähnlich wie bei Rechnung löschen verfahren
 
 686   $form->error($locale->text('Cannot post payment for a closed period!'))
 
 687     if ($form->date_closed($form->{"datepaid_$form->{paidaccounts}"}, \%myconfig));
 
 689   ($form->{AR})      = split /--/, $form->{AR};
 
 690   ($form->{AR_paid}) = split /--/, $form->{AR_paid};
 
 692   $form->redirect($locale->text('Payment posted!'))
 
 693       if (IS->post_payment(\%myconfig, \%$form));
 
 694     $form->error($locale->text('Cannot post payment!'));
 
 697   $main::lxdebug->leave_sub();
 
 701   $main::lxdebug->enter_sub();
 
 703   my $form     = $main::form;
 
 704   my %myconfig = %main::myconfig;
 
 705   my $locale   = $main::locale;
 
 707   $main::auth->assert('invoice_edit');
 
 709   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 710   $form->isblank("invdate",  $locale->text('Invoice Date missing!'));
 
 711   $form->isblank("customer", $locale->text('Customer missing!'));
 
 712   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
 713         if ($form->date_closed($form->{"invdate"}, \%myconfig));
 
 715   $form->{invnumber} =~ s/^\s*//g;
 
 716   $form->{invnumber} =~ s/\s*$//g;
 
 718   # if oldcustomer ne customer redo form
 
 719   if (&check_name('customer')) {
 
 724   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 725     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 730   if ($form->{second_run}) {
 
 731     $form->{print_and_post} = 0;
 
 734   remove_emptied_rows();
 
 737   my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
 
 738   my $invdate  = $form->datetonum($form->{invdate},  \%myconfig);
 
 740   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 741     if ($form->date_max_future($invdate, \%myconfig));
 
 742   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
 743     if ($invdate <= $closedto);
 
 745   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 746     if ($form->{currency} ne $form->{defaultcurrency});
 
 748   for my $i (1 .. $form->{paidaccounts}) {
 
 749     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 750       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 752       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 754       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 755         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
 
 757       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 758         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 759           if ($invdate == $datepaid);
 
 760         $form->isblank("exchangerate_$i",
 
 761                        $locale->text('Exchangerate for payment missing!'));
 
 766   ($form->{AR})        = split /--/, $form->{AR};
 
 767   ($form->{AR_paid})   = split /--/, $form->{AR_paid};
 
 768   $form->{storno}    ||= 0;
 
 770   $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
 
 772   $form->{id} = 0 if $form->{postasnew};
 
 774   # get new invnumber in sequence if no invnumber is given or if posasnew was requested
 
 775   if ($form->{postasnew}) {
 
 776     if ($form->{type} eq "credit_note") {
 
 777       undef($form->{cnnumber});
 
 779       undef($form->{invnumber});
 
 784   $form->error($locale->text('Cannot post invoice!'))
 
 785     unless IS->post_invoice(\%myconfig, \%$form);
 
 786   remove_draft() if $form->{remove_draft};
 
 788   if(!exists $form->{addition}) {
 
 789     $form->{snumbers} =  'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
 
 790     $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
 
 791                         $form->{storno}         ? "STORNO"             :
 
 796   if (!$form->{no_redirect_after_post}) {
 
 797     $form->{action} = 'edit';
 
 798     $form->{script} = 'is.pl';
 
 799     $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
 
 800     $form->{callback} = build_std_url(qw(action edit id saved_message));
 
 804   $main::lxdebug->leave_sub();
 
 808   $main::lxdebug->enter_sub();
 
 810   my $form     = $main::form;
 
 812   $main::auth->assert('invoice_edit');
 
 814   my $old_form                    = new Form;
 
 815   $form->{no_redirect_after_post} = 1;
 
 816   $form->{print_and_post}         = 1;
 
 820   $main::lxdebug->leave_sub();
 
 825   $main::lxdebug->enter_sub();
 
 827   my $form     = $main::form;
 
 828   my %myconfig = %main::myconfig;
 
 830   $main::auth->assert('invoice_edit');
 
 832   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)};
 
 834   $form->{paidaccounts} = 1;
 
 835   $form->{invdate}      = $form->current_date(\%myconfig);
 
 836   $form->{duedate}      = $form->get_duedate(\%myconfig, $form->{invdate}) || $form->{invdate};
 
 837   $form->{employee_id}  = SL::DB::Manager::Employee->current->id;
 
 838   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
 839   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 841   # remember pricegroups for "use as new"
 
 842   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 843   set_pricegroup($_) for 1 .. $form->{rowcount};
 
 847   $main::lxdebug->leave_sub();
 
 851   $main::lxdebug->enter_sub();
 
 853   my $form     = $main::form;
 
 854   my %myconfig = %main::myconfig;
 
 855   my $locale   = $main::locale;
 
 857   $main::auth->assert('invoice_edit');
 
 859   if ($form->{storno}) {
 
 860     $form->error($locale->text('Cannot storno storno invoice!'));
 
 863   if (IS->has_storno(\%myconfig, $form, "ar")) {
 
 864     $form->error($locale->text("Invoice has already been storno'd!"));
 
 866   if ($form->datetonum($form->{invdate},  \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
 
 867     $form->error($locale->text('Cannot storno invoice for a closed period!'));
 
 870   map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
 
 876   # Payments must not be recorded for the new storno invoice.
 
 877   $form->{paidaccounts} = 0;
 
 878   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
 
 880   $form->{storno_id} = $form->{id};
 
 883   $form->{invnumber} = "Storno zu " . $form->{invnumber};
 
 884   $form->{invdate}   = DateTime->today->to_lxoffice;
 
 888   $main::lxdebug->leave_sub();
 
 892   $main::lxdebug->enter_sub();
 
 894   my $form     = $main::form;
 
 896   $main::auth->assert('invoice_edit');
 
 898   $form->{preview} = 1;
 
 899   my $old_form = new Form;
 
 900   for (keys %$form) { $old_form->{$_} = $form->{$_} }
 
 902   &print_form($old_form);
 
 903   $main::lxdebug->leave_sub();
 
 908   $main::lxdebug->enter_sub();
 
 910   my $form     = $main::form;
 
 911   my $locale   = $main::locale;
 
 913   $main::auth->assert('invoice_edit');
 
 915   if ($form->{second_run}) {
 
 916     $form->{print_and_post} = 0;
 
 921 <form method="post" action="$form->{script}">
 
 924   # delete action variable
 
 925   map { delete $form->{$_} } qw(action header);
 
 927   foreach my $key (keys %$form) {
 
 928     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 929     $form->{$key} =~ s/\"/"/g;
 
 930     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
 
 934 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
 
 937     . $locale->text('Are you sure you want to delete Invoice Number')
 
 938     . qq| $form->{invnumber}
 
 942 <input name="action" class="submit" type="submit" value="|
 
 943     . $locale->text('Yes') . qq|">
 
 947   $main::lxdebug->leave_sub();
 
 951   $main::lxdebug->enter_sub();
 
 953   my $form     = $main::form;
 
 954   my %myconfig = %main::myconfig;
 
 955   my $locale   = $main::locale;
 
 957   $main::auth->assert('invoice_edit');
 
 959   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
 
 961     $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
 
 968   $form->{title}  = $locale->text('Add Credit Note');
 
 969   $form->{script} = 'is.pl';
 
 971   # Bei Gutschriften bezug zur Rechnungsnummer
 
 972   $form->{invnumber_for_credit_note} = $form->{invnumber};
 
 973   # bo creates the id, reset it
 
 974   map { delete $form->{$_} }
 
 975     qw(id invnumber subject message cc bcc printed emailed queued);
 
 976   $form->{ $form->{vc} } =~ s/--.*//g;
 
 977   $form->{type} = "credit_note";
 
 980   map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
 
 982 #  map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 983 #    qw(creditlimit creditremaining);
 
 985   for my $i (1 .. $form->{rowcount}) {
 
 986     for (qw(listprice)) {
 
 987       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
 
 991   my $currency = $form->{currency};
 
 994   $form->{currency}     = $currency;
 
 995   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
 
 996   $form->{exchangerate} = $form->{forex} || '';
 
 998   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
 
1000   # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
 
1001   for my $i (1 .. $form->{paidaccounts}) {
 
1002     delete $form->{"paid_$i"};
 
1003     delete $form->{"source_$i"};
 
1004     delete $form->{"memo_$i"};
 
1005     delete $form->{"datepaid_$i"};
 
1006     delete $form->{"gldate_$i"};
 
1007     delete $form->{"acc_trans_id_$i"};
 
1008     delete $form->{"AR_paid_$i"};
 
1010   $form->{paidaccounts} = 1;
 
1017   $main::lxdebug->leave_sub();
 
1021   $main::lxdebug->enter_sub();
 
1023   my $form     = $main::form;
 
1024   my %myconfig = %main::myconfig;
 
1025   my $locale   = $main::locale;
 
1027   $main::auth->assert('invoice_edit');
 
1029   if (IS->delete_invoice(\%myconfig, \%$form)) {
 
1030     # saving the history
 
1031     if(!exists $form->{addition}) {
 
1032       $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
 
1033       $form->{addition} = "DELETED";
 
1034       $form->save_history;
 
1036     # /saving the history
 
1037     $form->redirect($locale->text('Invoice deleted!'));
 
1039   $form->error($locale->text('Cannot delete invoice!'));
 
1041   $main::lxdebug->leave_sub();
 
1044 sub post_and_e_mail {
 
1049   $main::lxdebug->enter_sub();
 
1051   my $form     = $main::form;
 
1053   $main::auth->assert('invoice_edit');
 
1056     $form->{no_redirect_after_post} = 1;
 
1058     my $saved_form = save_form();
 
1062     restore_form($saved_form, 0, qw(id invnumber));
 
1067   $main::lxdebug->leave_sub();