1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   6 #############################################################################
 
   7 # Changelog: Wann - Wer - Was
 
   8 # Veraendert 2005-01-05 - Marco Welter <mawe@linux-studio.de> - Neue Optik
 
   9 # 08.11.2008 - information@richardson-bueren.de jb  - Backport von Revision 7339 xplace - E-Mail-Vorlage automatisch auswählen
 
  10 # 02.02.2009 - information@richardson-bueren.de jb - Backport von Revision 8535 xplace - Erweiterung der Waren bei Lieferantenauftrag um den Eintrag Mindestlagerbestand. Offen: Auswahlliste auf Lieferantenaufträge einschränken -> Erledigt 2.2.09 Prüfung wie das Skript heisst (oe.pl) -> das ist nur die halbe Miete, nochmal mb fragen -> mb gefragt und es gibt die variable is_purchase
 
  11 #############################################################################
 
  12 # SQL-Ledger, Accounting
 
  13 # Copyright (c) 1998-2002
 
  15 #  Author: Dieter Simader
 
  16 #   Email: dsimader@sql-ledger.org
 
  17 #     Web: http://www.sql-ledger.org
 
  20 # This program is free software; you can redistribute it and/or modify
 
  21 # it under the terms of the GNU General Public License as published by
 
  22 # the Free Software Foundation; either version 2 of the License, or
 
  23 # (at your option) any later version.
 
  25 # This program is distributed in the hope that it will be useful,
 
  26 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  27 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  28 # GNU General Public License for more details.
 
  29 # You should have received a copy of the GNU General Public License
 
  30 # along with this program; if not, write to the Free Software
 
  31 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
  34 #######################################################################
 
  36 # common routines used in is, ir, oe
 
  38 #######################################################################
 
  42 use List::MoreUtils qw(any uniq apply);
 
  43 use List::Util qw(sum min max first);
 
  44 use List::UtilsBy qw(sort_by uniq_by);
 
  49 use SL::Controller::Base;
 
  51 use SL::Locale::String qw(t8);
 
  56 use SL::Presenter::Part;
 
  57 use SL::Util qw(trim);
 
  63 use SL::DB::DeliveryOrder::TypeData qw();
 
  68 use SL::Helper::CreatePDF;
 
  69 use SL::Helper::Flash;
 
  70 use SL::Helper::PrintOptions;
 
  71 use SL::Helper::ShippedQty;
 
  73 require "bin/mozilla/common.pl";
 
  77 # any custom scripts for this one
 
  78 if (-f "bin/mozilla/custom_io.pl") {
 
  79   eval { require "bin/mozilla/custom_io.pl"; };
 
  81 if (-f "bin/mozilla/$::myconfig{login}_io.pl") {
 
  82   eval { require "bin/mozilla/$::myconfig{login}_io.pl"; };
 
  89 # this is for our long dates
 
  90 # $locale->text('January')
 
  91 # $locale->text('February')
 
  92 # $locale->text('March')
 
  93 # $locale->text('April')
 
  94 # $locale->text('May ')
 
  95 # $locale->text('June')
 
  96 # $locale->text('July')
 
  97 # $locale->text('August')
 
  98 # $locale->text('September')
 
  99 # $locale->text('October')
 
 100 # $locale->text('November')
 
 101 # $locale->text('December')
 
 103 # this is for our short month
 
 104 # $locale->text('Jan')
 
 105 # $locale->text('Feb')
 
 106 # $locale->text('Mar')
 
 107 # $locale->text('Apr')
 
 108 # $locale->text('May')
 
 109 # $locale->text('Jun')
 
 110 # $locale->text('Jul')
 
 111 # $locale->text('Aug')
 
 112 # $locale->text('Sep')
 
 113 # $locale->text('Oct')
 
 114 # $locale->text('Nov')
 
 115 # $locale->text('Dec')
 
 121   $main::auth->assert('part_service_assembly_edit   | vendor_invoice_edit       | sales_order_edit    | invoice_edit |' .
 
 122                 'request_quotation_edit       | sales_quotation_edit      | purchase_order_edit | ' .
 
 123                 'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details');
 
 126 ########################################
 
 127 # Eintrag fuer Version 2.2.0 geaendert #
 
 128 # neue Optik im Rechnungsformular      #
 
 129 ########################################
 
 131   $main::lxdebug->enter_sub();
 
 133   my $form     = $main::form;
 
 134   my %myconfig = %main::myconfig;
 
 135   my $locale   = $main::locale;
 
 136   my $cgi      = $::request->{cgi};
 
 140   my ($stock_in_out, $stock_in_out_title);
 
 142   my $defaults = AM->get_defaults();
 
 143   $form->{show_weight} = $defaults->{show_weight};
 
 144   $form->{weightunit} = $defaults->{weightunit};
 
 146   my $is_purchase        = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
 
 147   my $is_delivery_order  = $form->{type} =~ /_delivery_order$/;
 
 148   my $is_quotation       = $form->{type} =~ /_quotation$/;
 
 149   my $is_invoice         = $form->{type} =~ /invoice/;
 
 150   my $is_credit_note     = $form->{type} =~ /credit_note/;
 
 151   my $is_s_p_order       = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
 
 152   my $show_ship_missing  = $is_s_p_order && $::instance_conf->get_sales_purchase_order_ship_missing_column;
 
 153   my $show_marge         = (!$is_purchase || $is_invoice || $is_credit_note) && !$is_delivery_order;
 
 155   if ($is_delivery_order) {
 
 156     if ($form->{type} eq 'sales_delivery_order') {
 
 157       $stock_in_out_title = $locale->text('Release From Stock');
 
 158       $stock_in_out       = 'out';
 
 160       $stock_in_out_title = $locale->text('Transfer To Stock');
 
 161       $stock_in_out       = 'in';
 
 164     retrieve_partunits();
 
 168   my @header_sort = qw(
 
 169     runningnumber partnumber type_and_classific description ship ship_missing qty price_factor
 
 170     unit weight price_source sellprice discount linetotal
 
 174     serialnr projectnr reqdate subtotal marge listprice lastcost onhand
 
 176   # serialnr is important for delivery_orders
 
 177   if ($form->{type} eq 'sales_delivery_order') {
 
 178     splice @row2_sort, 0, 1;
 
 179     splice @header_sort, 4, 0, "serialnr";
 
 183     runningnumber => { width => 5,     value => $locale->text('No.'),                  display => 1, },
 
 184     partnumber    => { width => 8,     value => $locale->text('Number'),               display => 1, },
 
 186                   => { width => 2,     value => $locale->text('Type'),                 display => 1, },
 
 187     description   => { width => 30,    value => $locale->text('Part Description'),     display => 1, },
 
 188     ship          => { width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
 
 189     ship_missing  => { width => 5,     value => $locale->text('Not delivered'),        display => $show_ship_missing, },
 
 190     qty           => { width => 5,     value => $locale->text('Qty'),                  display => 1, },
 
 191     price_factor  => { width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
 
 192     unit          => { width => 5,     value => $locale->text('Unit'),                 display => 1, },
 
 193     weight        => { width => 5,     value => $locale->text('Weight'),               display => $defaults->{show_weight}, },
 
 194     serialnr      => { width => 10,    value => $locale->text('Serial No.'),           display => !$is_quotation },
 
 195     projectnr     => { width => 10,    value => $locale->text('Project'),              display => 1, },
 
 196     price_source  => { width => 5,     value => $locale->text('Price Source'),         display => !$is_delivery_order, },
 
 197     sellprice     => { width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
 
 198     discount      => { width => 5,     value => $locale->text('Discount'),             display => !$is_delivery_order, },
 
 199     linetotal     => { width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
 
 200     bin           => { width => 10,    value => $locale->text('Bin'),                  display => 0, },
 
 201     stock_in_out  => { width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
 
 202     reqdate       => {                 value => $locale->text('Reqdate'),              display => $is_s_p_order || $is_delivery_order || $is_invoice, },
 
 203     subtotal      => {                 value => $locale->text('Subtotal'),             display => 1, },
 
 204     marge         => {                 value => $locale->text('Ertrag'),               display => $show_marge, },
 
 205     listprice     => {                 value => $locale->text('LP'),                   display => $show_marge, },
 
 206     lastcost      => {                 value => $locale->text('EK'),                   display => $show_marge, },
 
 207     onhand        => {                 value => $locale->text('On Hand'),              display => 1, },
 
 209   my @HEADER = map { $column_def{$_} } @header_sort;
 
 212   my $all_units       = AM->retrieve_units(\%myconfig, $form);
 
 214   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 217   $form->{invsubtotal} = 0;
 
 218   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
 
 221   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
 
 222   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
 
 225   # translations, unused commented out
 
 226   my $deliverydate  = $locale->text('Required by');
 
 229   my %align  = map { $_ => 'right' } qw(qty ship right discount linetotal stock_in_out weight ship_missing);
 
 230   my %nowrap = map { $_ => 1 }       qw(description unit  price_source);
 
 232   $form->{marge_total}           = 0;
 
 233   $form->{sellprice_total}       = 0;
 
 234   $form->{lastcost_total}        = 0;
 
 235   $form->{totalweight}           = 0;
 
 236   my %projectnumber_labels = ();
 
 237   my @projectnumber_values = ("");
 
 239   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 240     push(@projectnumber_values, $item->{"id"});
 
 241     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
 
 244   _update_part_information();
 
 245   _update_ship() if ($is_s_p_order);
 
 246   _update_custom_variables();
 
 250   my $record = _make_record();
 
 254   for my $i (1 .. $numrows) {
 
 255     my %column_data = ();
 
 257     my $record_item = $record->id && $record->items ? $record->items->[$i-1] : _make_record_item($i);
 
 260     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
 
 261       qw(qty discount sellprice lastcost price_new price_old)
 
 262         unless ($form->{simple_save});
 
 264     if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
 
 265       $form->{"sellprice_$i"} = $form->{"price_new_$i"};
 
 269     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
 
 270     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
 
 272     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
 273         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
 274       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
 277     $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 278     $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 279     $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
 
 281     my $this_unit = $form->{"unit_$i"};
 
 282     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
 
 284     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
 
 285       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
 
 286       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
 
 288       $column_data{price_factor} =
 
 289         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
 
 290                              '-default' => $form->{"price_factor_id_$i"},
 
 291                              '-values'  => \@values,
 
 292                              '-labels'  => \%labels,
 
 293                              '-style'   => 'width:90px'));
 
 295       $column_data{price_factor} = ' ';
 
 297     $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
 
 299     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
 
 302 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
 
 303 #is shown for lastcost and sellprice.
 
 304     my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
 
 305     $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
 
 307     my $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
 
 308     my $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
 
 309     my $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
 
 310     my $rows            = $form->numtextrows($form->{"description_$i"}, 30, 6);
 
 312     # quick delete single row
 
 313     $column_data{runningnumber}  = q|<a onclick= "$('#partnumber_| . $i . q|').val(''); $('#update_button').click();">| .
 
 314                                    q|<img height="10px" width="10px" src="image/cross.png" alt="| . $locale->text('Remove') . q|"></a> |;
 
 315     $column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
 
 318     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -id => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
 
 319     $column_data{type_and_classific} = SL::Presenter::Part::type_abbreviation($form->{"part_type_$i"}).
 
 320                                        SL::Presenter::Part::classification_abbreviation($form->{"classification_id_$i"}) if $form->{"id_$i"};
 
 321     $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
 
 322                                 ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
 
 323                                 : $cgi->textfield(-name => "description_$i", -id => "description_$i",   -value => $form->{"description_$i"}, -size => 30))
 
 324                                 . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
 
 326     my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
 
 328     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -class => "numeric", -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
 
 329     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_dialog('qty_$i', '', 'formel_$i', '')", -value => $locale->text('*/'))
 
 330                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"})
 
 331       if $form->{"formel_$i"};
 
 333     $column_data{ship} = '';
 
 334     if ($form->{"id_$i"}) {
 
 335       my $ship_qty        = $form->{"ship_$i"} * 1;
 
 336       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
 
 337       $ship_qty          /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
 
 339       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"}
 
 340       . $cgi->hidden(-name => "ship_$i", -value => $form->{"ship_$i"}, $qty_dec);
 
 342       my $ship_missing_qty    = $form->{"qty_$i"} - $ship_qty;
 
 343       my $ship_missing_amount = $form->round_amount($ship_missing_qty * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
 
 345       $column_data{ship_missing} = $form->format_amount(\%myconfig, $ship_missing_qty) . ' ' . $form->{"unit_$i"} . '; ' . $form->format_amount(\%myconfig, $ship_missing_amount, $decimalplaces);
 
 348     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
 
 349     $column_data{bin}         = $form->{"bin_$i"};
 
 351     $column_data{weight}      = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
 
 353     my $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 354     my $discount_value  = $form->format_amount(\%myconfig, $form->{"discount_$i"});
 
 357     if ($form->{"id_${i}"} && !$is_delivery_order) {
 
 358       my $price_source  = SL::PriceSource->new(record_item => $record_item, record => $record);
 
 359          $price         = $price_source->price_from_source($::form->{"active_price_source_$i"});
 
 360       my $discount      = $price_source->discount_from_source($::form->{"active_discount_source_$i"});
 
 361       my $best_price    = $price_source->best_price;
 
 362       my $best_discount = $price_source->best_discount;
 
 363       $column_data{price_source} .= $cgi->button(-value => $price->source_description, -onClick => "kivi.io.price_chooser($i)");
 
 364       if ($price->source) {
 
 365         $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->invalid, title => $price->invalid }) if $price->invalid;
 
 366         $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->missing, title => $price->missing }) if $price->missing;
 
 367         if (!$price->missing && !$price->invalid) {
 
 368           $column_data{price_source} .= ' ' . $cgi->img({src => 'image/up.png',   alt => t8('This price has since gone up'),      title => t8('This price has since gone up' )     }) if $price->price - $record_item->sellprice > 0.01;
 
 369           $column_data{price_source} .= ' ' . $cgi->img({src => 'image/down.png', alt => t8('This price has since gone down'),    title => t8('This price has since gone down')    }) if $price->price - $record_item->sellprice < -0.01;
 
 370           $column_data{price_source} .= ' ' . $cgi->img({src => 'image/ok.png',   alt => t8('There is a better price available'), title => t8('There is a better price available') }) if $best_price && $price->source ne $price_source->best_price->source;
 
 373       if ($discount->source) {
 
 374         $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->invalid, title => $discount->invalid }) if $discount->invalid;
 
 375         $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->missing, title => $discount->missing }) if $discount->missing;
 
 376         if (!$discount->missing && !$discount->invalid) {
 
 377           $column_data{price_source} .= ' ' . $cgi->img({src => 'image/up.png',   alt => t8('This discount has since gone up'),      title => t8('This discount has since gone up')      }) if $discount->discount * 100 - $record_item->discount > 0.01;
 
 378           $column_data{price_source} .= ' ' . $cgi->img({src => 'image/down.png', alt => t8('This discount has since gone down'),    title => t8('This discount has since gone down')    }) if $discount->discount * 100 - $record_item->discount < -0.01;
 
 379           $column_data{price_source} .= ' ' . $cgi->img({src => 'image/ok.png',   alt => t8('There is a better discount available'), title => t8('There is a better discount available') }) if $best_discount && $discount->source ne $price_source->best_discount->source;
 
 384     my $right_to_edit_prices  = (!$is_purchase && $main::auth->assert('sales_edit_prices', 1)) || ($is_purchase && $main::auth->assert('purchase_edit_prices', 1));
 
 385     my $edit_prices           = $right_to_edit_prices && (!$::form->{"active_price_source_$i"} || !$price || $price->editable);
 
 386     my $edit_discounts        = $right_to_edit_prices && !$::form->{"active_discount_source_$i"};
 
 387     $column_data{sellprice}   = (!$edit_prices)
 
 388                                 ? $cgi->hidden(   -name => "sellprice_$i", -id => "sellprice_$i", -value => $sellprice_value) . $sellprice_value
 
 389                                 : $cgi->textfield(-name => "sellprice_$i", -id => "sellprice_$i", -size => 10, -class => "numeric", -value => $sellprice_value);
 
 390     $column_data{discount}    = (!$edit_discounts)
 
 391                                   ? $cgi->hidden(   -name => "discount_$i", -id => "discount_$i", -value => $discount_value) . $discount_value . ' %'
 
 392                                   : $cgi->textfield(-name => "discount_$i", -id => "discount_$i", -size => 3, -"data-validate" => "number", -class => "numeric", -value => $discount_value);
 
 394     if ($is_delivery_order) {
 
 395       $column_data{stock_in_out} =  calculate_stock_in_out($i);
 
 398     $column_data{serialnr}  = qq|<input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">|;
 
 399     $column_data{projectnr} = NTI($cgi->popup_menu(
 
 400       '-name' => "project_id_$i",
 
 401       '-values' => \@projectnumber_values,
 
 402       '-labels' => \%projectnumber_labels,
 
 403       '-default' => $form->{"project_id_$i"}
 
 405     $column_data{reqdate}   = qq|<input name="reqdate_$i" size="11" data-validate="date" value="$form->{"reqdate_$i"}">|;
 
 406     $column_data{subtotal}  = sprintf qq|<input type="checkbox" name="subtotal_$i" value="1" %s>|, $form->{"subtotal_$i"} ? 'checked' : '';
 
 408 # begin marge calculations
 
 409     $form->{"lastcost_$i"}     *= 1;
 
 410     $form->{"marge_percent_$i"} = 0;
 
 414     if ( $form->{taxincluded} and $form->{"qty_$i"} * 1  and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
 
 415       # if we use taxincluded we need to calculate the marge from the net_value
 
 416       # all the marge calculations are based on linetotal which we need to
 
 417       # convert to net first
 
 419       # there is no direct form value for the tax_rate of the item, but
 
 420       # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
 
 421       # gives the tax percentage (e.g. 0.19)
 
 422       $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
 
 424       $real_sellprice            = $linetotal;
 
 426     my $real_lastcost            = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 427     my $marge_percent_warn       = $myconfig{marge_percent_warn} * 1 || 15;
 
 428     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
 
 430     if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
 
 431       $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
 
 432       $marge_color                = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
 
 435     $form->{"marge_absolut_$i"}  = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
 
 436     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
 
 437     $form->{"lastcost_total"}   += $real_lastcost;
 
 438     $form->{"sellprice_total"}  += $real_sellprice;
 
 440     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
 
 442     $column_data{marge} = sprintf qq|<font %s>%s  %s%%</font>|,
 
 443       $marge_color, $form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"};
 
 444     $column_data{listprice} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2);
 
 445     $column_data{lastcost}  = sprintf qq|<input size="5" name="lastcost_$i" value="%s">|, $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
 
 446 # / marge calculations ending
 
 448 # Calculate total weight
 
 449     $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
 
 452     if ($form->{"id_$i"}) {
 
 453       my $part         = IC->get_basic_part_info(id => $form->{"id_$i"});
 
 454       my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
 
 455       $column_data{onhand} = sprintf "<font %s>%s %s</font>",
 
 457                       $form->format_amount(\%myconfig, $part->{onhand}, 2),
 
 462     my @ROW1 = map { { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} } } grep { $column_def{$_}{display} } @header_sort;
 
 463     my @ROW2 = map { { value => sprintf "<b>%s</b> %s", $column_def{$_}{value}, $column_data{$_} } } grep { $column_def{$_}{display} } @row2_sort;
 
 466     # add hidden ids for persistent (item|invoice)_ids and previous (converted_from*) ids
 
 468       push @hidden_vars, qw(orderitems_id converted_from_orderitems_id);
 
 471       push @hidden_vars, qw(orderitems_id converted_from_orderitems_id converted_from_invoice_id);
 
 474       push @hidden_vars, qw(invoice_id converted_from_orderitems_id converted_from_delivery_order_items_id converted_from_invoice_id);
 
 476     if ($::form->{type} =~ /credit_note/) {
 
 477       push @hidden_vars, qw(invoice_id converted_from_invoice_id);
 
 479    if ($is_delivery_order) {
 
 480       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
 
 481       push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost);
 
 482       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
 
 483       push @hidden_vars, qw(delivery_order_items_id converted_from_orderitems_id converted_from_delivery_order_items_id has_sernumber);
 
 486     my @HIDDENS = map { value => $_}, (
 
 487           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
 
 488           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
 
 489           map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
 
 490             (qw(bo price_old id inventory_accno bin partsgroup partnotes active_price_source active_discount_source
 
 491                 income_accno expense_accno listprice part_type taxaccounts ordnumber donumber transdate cusordnumber
 
 492                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
 
 495     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
 
 497     $form->{invsubtotal} += $linetotal;
 
 499     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
 
 500     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
 
 502     my $colspan = scalar @ROW1;
 
 503     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, obj => $record_item };
 
 506   $form->{totalweight} = $totalweight;
 
 508   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
 
 512   if (abs($form->{sellprice_total} * 1) >= 0.01) {
 
 513     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
 
 516   $main::lxdebug->leave_sub();
 
 519 sub setup_io_select_item_action_bar {
 
 522   for my $bar ($::request->layout->get('actionbar')) {
 
 526         submit    => [ '#form' ],
 
 527         accesskey => 'enter',
 
 534   $main::lxdebug->enter_sub();
 
 537   my $mode            = $params{mode}            || croak "Missing parameter 'mode'";
 
 538   my $pre_entered_qty = $params{pre_entered_qty} || 1;
 
 541   setup_io_select_item_action_bar();
 
 543   my $previous_form = $::auth->save_form_in_session(form => $::form);
 
 544   $::form->{title}  = $::myconfig{item_multiselect} ?
 
 545       $::locale->text('Set count for one or more of the items to select them'):
 
 546       $::locale->text('Select from one of the items below');
 
 549   my @item_list = map {
 
 550     # maybe there is a better backend function or way to calc
 
 551     $_->{display_sellprice} = ($_->{price_factor}) ? $_->{sellprice} / $_->{price_factor} : $_->{sellprice};
 
 553   } @{ $::form->{item_list} };
 
 555   # delete action variable
 
 556   delete @{$::form}{qw(action item_list)};
 
 558   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM   => $previous_form,
 
 560                                                          ITEM_LIST       => \@item_list,
 
 561                                                          IS_ASSEMBLY     => $mode eq 'IC',
 
 562                                                          IS_PURCHASE     => $mode eq 'IS',
 
 563                                                          PRE_ENTERED_QTY => $pre_entered_qty, });
 
 565   $main::lxdebug->leave_sub();
 
 570   # this function is used for adding parts to records (mode = IR/IS)
 
 571   # and to assemblies (mode = IC)
 
 573   $main::lxdebug->enter_sub();
 
 575   my $form     = $main::form;
 
 576   my %myconfig = %main::myconfig;
 
 580   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
 
 582   my $mode     = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
 
 583   my $row_key  = $mode eq 'IC' ? 'assembly_rows' : 'rowcount';
 
 584   my $curr_row = $form->{ $row_key };
 
 588   if ($myconfig{item_multiselect}) {
 
 591       next unless $form->{$_};
 
 592       next unless /^select_qty_(\d+)/;
 
 593       $multi_items{"id_${row}"}  = $1;
 
 594       $multi_items{"qty_${row}"} = $form->{$_};
 
 597     $form->{$_} = $multi_items{$_} for keys %multi_items;
 
 599     $form->{"id_${row}"} = delete($form->{select_item_id}) || croak 'Missing item selection ID';
 
 603   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 604     qw(sellprice weight);
 
 606   if ( $mode eq 'IC' ) {
 
 608     # the qty variables of the existing assembly items are all still formatted, so we parse them here
 
 609     # including the qty of the just added part
 
 610     $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for (1 .. $row - 1);
 
 612     if ($myconfig{item_multiselect}) {
 
 613       # other modes and multiselection:
 
 614       # parse all newly entered qtys
 
 615       $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for ($curr_row .. $row - 1);
 
 619   for my $i ($curr_row .. $row - 1) {
 
 620     $form->{ $row_key } = $i;
 
 622     my $id = $form->{"id_${i}"};
 
 624     delete $form->{item_list};
 
 627       IS->retrieve_item(\%myconfig, \%$form);
 
 628     } elsif ($mode eq 'IR') {
 
 629       IR->retrieve_item(\%myconfig, \%$form);
 
 630     } elsif ($mode eq 'IC') {
 
 631       IC->assembly_item(\%myconfig, \%$form);
 
 633       croak "Invalid item selection mode '${mode}'";
 
 636     my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
 
 638     # if there was a price entered, override it
 
 640     unless ( $mode eq 'IC' ) {
 
 641       $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 645         qw(id partnumber description sellprice listprice inventory_accno
 
 646            income_accno expense_accno bin unit weight part_type taxaccounts
 
 647            partsgroup formel longdescription not_discountable partnotes lastcost
 
 648            price_factor_id price_factor);
 
 650     my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 651     push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 653     map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
 
 655     if (my $record = _make_record()) {
 
 656       my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
 
 657       my $best_price   = $price_source->best_price;
 
 660         $::form->{"sellprice_$i"}           = $best_price->price;
 
 661         $::form->{"active_price_source_$i"} = $best_price->source;
 
 664       my $best_discount = $price_source->best_discount;
 
 666       if ($best_discount) {
 
 667         $::form->{"discount_$i"}               = $best_discount->discount;
 
 668         $::form->{"active_discount_source_$i"} = $best_discount->source;
 
 672     $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
 
 674     if ($form->{"part_payment_id_$i"} ne "") {
 
 675       $form->{payment_id} = $form->{"part_payment_id_$i"};
 
 678     my ($dec)         = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 680     my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 683       $form->{"sellprice_$i"} = $sellprice;
 
 686       # if there is an exchange rate adjust sellprice
 
 687       if (($form->{exchangerate} * 1) != 0) {
 
 688         $form->{"sellprice_$i"} /= $form->{exchangerate};
 
 689         $form->{"sellprice_$i"} =
 
 690             $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
 
 694     # at this stage qty of newly added part needs to be have been parsed
 
 695     $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
 
 697     if ($form->{"not_discountable_$i"}) {
 
 698       $form->{"discount_$i"} = 0;
 
 702         $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"}) * $form->{"qty_$i"};
 
 703     map { $form->{"${_}_base"} += $amount }                         (split / /, $form->{"taxaccounts_$i"});
 
 704     map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
 
 706     $form->{creditremaining} -= $amount;
 
 707     $form->{"runningnumber_$i"} = $i;
 
 712           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
 
 713     } qw(sellprice lastcost qty) if $form->{part_type} ne 'assembly';
 
 714     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0) if $form->{part_type} ne 'assembly';
 
 716     delete $form->{nextsub};
 
 722   $main::lxdebug->leave_sub();
 
 728   my $price = $::form->{vc} eq 'customer' ? 'sellprice_as_number' : 'lastcost_as_number';
 
 729   my $previousform = $::auth->save_form_in_session;
 
 730   my $callback     = build_std_url("action=return_from_new_item", "previousform=$previousform");
 
 731   my $i            = $::form->{rowcount};
 
 733   my $parts_classification_type = $::form->{vc} eq 'customer' ? 'sales' : 'purchases';
 
 736   push @HIDDENS,      { 'name' => 'callback',     'value' => $callback };
 
 737   push @HIDDENS, map +{ 'name' => $_,             'value' => $::form->{$_} },        qw(rowcount vc);
 
 738   push @HIDDENS, map +{ 'name' => "part.$_",      'value' => $::form->{"${_}_$i"} }, qw(partnumber description unit price_factor_id);
 
 739   push @HIDDENS,      { 'name' => "part.$price",  'value' => $::form->{"sellprice_$i"} };
 
 740   push @HIDDENS,      { 'name' => "part.notes",   'value' => $::form->{"longdescription_$i"} };
 
 742   push @HIDDENS,      { 'name' => "parts_classification_type", 'value' => $parts_classification_type };
 
 745   print $::form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
 
 748 sub return_from_new_item {
 
 751   my $part = SL::DB::Manager::Part->find_by(id => delete $::form->{new_parts_id}) or die 'can not find part that was just saved!';
 
 753   $::auth->restore_form_from_session(delete $::form->{previousform}, form => $::form);
 
 755   $::form->{"id_$::form->{rowcount}"} = $part->id;
 
 757   my $url = build_std_url("script=$::form->{script}", "RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session);
 
 758   print $::request->{cgi}->redirect($url);
 
 762   $main::lxdebug->enter_sub();
 
 764   my $form     = $main::form;
 
 765   my %myconfig = %main::myconfig;
 
 772   # remove any makes or model rows
 
 773   if ($form->{part_type} eq 'assembly') {
 
 775     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
 
 776     #$form->{sellprice} = 0;
 
 778     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 779       qw(sellprice rop stock);
 
 781     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
 
 783     for my $i (1 .. ($form->{assembly_rows} - 1)) {
 
 784       if ($form->{"qty_$i"}) {
 
 788         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 790         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 792         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 794         # fuer assemblies auskommentiert. siehe oben
 
 795         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
 
 796         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
 
 800     # kann das hier auch weg? s.o. jb
 
 801     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
 
 803     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
 
 804     $form->{assembly_rows} = $count;
 
 806   } elsif ($form->{part_type} !~ m{^(?:part|service)$}) {
 
 807     remove_emptied_rows(1);
 
 809     $form->{creditremaining} -= &invoicetotal;
 
 814   $main::lxdebug->leave_sub();
 
 817 sub remove_emptied_rows {
 
 818   my $dont_add_empty = shift;
 
 821   return unless $form->{rowcount};
 
 823   my @flds = qw(id partnumber description qty ship sellprice unit
 
 824                 discount inventory_accno income_accno expense_accno listprice
 
 825                 taxaccounts bin assembly weight projectnumber project_id
 
 826                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
 
 827                 not_discountable shop ve gv buchungsgruppen_id language_values
 
 828                 price_old price_new unit_old ordnumber donumber
 
 829                 transdate longdescription basefactor marge_total marge_percent
 
 830                 marge_price_factor lastcost price_factor_id partnotes
 
 831                 stock_out stock_in has_sernumber reqdate orderitems_id
 
 832                 active_price_source active_discount_source delivery_order_items_id
 
 833                 invoice_id converted_from_orderitems_id
 
 834                 converted_from_delivery_order_items_id converted_from_invoice_id);
 
 836   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 837   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 840   for my $i (1 .. $form->{rowcount} - 1) {
 
 841     next unless $form->{"partnumber_$i"};
 
 843     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
 
 846   my $new_rowcount = scalar @new_rows;
 
 847   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
 
 848   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
 
 852   $main::lxdebug->enter_sub();
 
 854   my $form     = $main::form;
 
 855   my %myconfig = %main::myconfig;
 
 859   $form->{oldinvtotal} = 0;
 
 861   # add all parts and deduct paid
 
 862   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
 
 864   my ($amount, $sellprice, $discount, $qty);
 
 866   for my $i (1 .. $form->{rowcount}) {
 
 867     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 868     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
 
 869     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 871     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 873     $amount = $sellprice * (1 - $discount / 100) * $qty;
 
 874     map { $form->{"${_}_base"} += $amount }
 
 875       (split (/ /, $form->{"taxaccounts_$i"}));
 
 876     $form->{oldinvtotal} += $amount;
 
 879   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
 
 880     split(/ /, $form->{taxaccounts})
 
 881     if !$form->{taxincluded};
 
 883   $form->{oldtotalpaid} = 0;
 
 884   for my $i (1 .. $form->{paidaccounts}) {
 
 885     $form->{oldtotalpaid} += $form->{"paid_$i"};
 
 888   $main::lxdebug->leave_sub();
 
 891   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 895   $main::lxdebug->enter_sub();
 
 897   my $form     = $main::form;
 
 898   my $locale   = $main::locale;
 
 902   # check if items are valid
 
 903   if ($form->{rowcount} == 1) {
 
 904     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
 
 906     $::dispatcher->end_request;
 
 909   for my $i (1 .. $form->{rowcount} - 1) {
 
 910     $form->isblank("partnumber_$i",
 
 911                    $locale->text('Number missing in Row') . " $i");
 
 914   $main::lxdebug->leave_sub();
 
 918   $main::lxdebug->enter_sub();
 
 922   if ($::instance_conf->get_feature_experimental_order) {
 
 924     # At this point, the record is saved and the exchangerate contains
 
 925     # an unformatted value. _make_record uses RDBO attributes (i.e. _as_number)
 
 926     # to assign values and thus expects an formatted value.
 
 927     $::form->{exchangerate} = $::form->format_amount(\%::myconfig, $::form->{exchangerate});
 
 929     my $order = _make_record();
 
 931     $order->currency(SL::DB::Currency->new(name => $::form->{currency})->load) if $::form->{currency};
 
 932     $order->globalproject_id(undef)                                            if !$order->globalproject_id;
 
 933     $order->payment_id(undef)                                                  if !$order->payment_id;
 
 936     foreach my $item (@{$order->items_sorted}) {
 
 937       $item->custom_variables([]);
 
 939       $item->price_factor_id(undef) if !$item->price_factor_id;
 
 940       $item->project_id(undef)      if !$item->project_id;
 
 942       # autovivify all cvars that are not in the form (cvars_by_config can do it).
 
 943       # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
 
 944        foreach my $var (@{ $item->cvars_by_config }) {
 
 945         my $key = 'ic_cvar_' . $var->config->name . '_' . $row;
 
 946         $var->unparsed_value($::form->{$key});
 
 947         $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
 
 949       $item->parse_custom_variable_values;
 
 954     require SL::Controller::Order;
 
 955     my $c = SL::Controller::Order->new(order => $order);
 
 956     $c->setup_custom_shipto_from_form($order, $::form);
 
 959     $main::lxdebug->leave_sub();
 
 960     $::dispatcher->end_request;
 
 965   $main::lxdebug->leave_sub();
 
 969   my $form     = $main::form;
 
 970   my %myconfig = %main::myconfig;
 
 971   my $locale   = $main::locale;
 
 975   if ($form->{second_run}) {
 
 976     $form->{print_and_post} = 0;
 
 978   $form->{ordnumber} = $form->{invnumber};
 
 980   $form->{old_employee_id} = $form->{employee_id};
 
 981   $form->{old_salesman_id} = $form->{salesman_id};
 
 983   delete $form->{$_} foreach (qw(id printed emailed queued));
 
 985   # When creating a new sales order from a saved sales invoice, reset id,
 
 986   # ordnumber, transdate and deliverydate as we are creating a new order. This
 
 987   # workflow is probably mainly used as a template mechanism for creating new
 
 988   # orders from existing invoices, so we probably don't want to link the items.
 
 989   # Is this order function called anywhere else?
 
 990   # The worksflows in oe already call sales_order and purchase_order in oe, not
 
 991   # this general function which now only seems to be called from saved sales
 
 993   # Why is ordnumber set to invnumber above, does this ever make sense?
 
 995   if ( $form->{script} eq 'is.pl' && $form->{type} eq 'invoice' ) {
 
 996     delete $form->{$_} foreach (qw(ordnumber id transdate deliverydate));
 
1000   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
 
1001     $form->{title} = $locale->text('Add Purchase Order');
 
1002     $form->{vc}    = 'vendor';
 
1003     $form->{type}  = 'purchase_order';
 
1006   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
 
1007     $form->{title} = $locale->text('Add Sales Order');
 
1008     $form->{vc}    = 'customer';
 
1009     $form->{type}  = 'sales_order';
 
1012   $form->{script} = 'oe.pl';
 
1014   $form->{rowcount}--;
 
1016   $form->{cp_id} *= 1;
 
1018   require "bin/mozilla/$form->{script}";
 
1019   my $script = $form->{"script"};
 
1021   $script =~ s|.pl$||;
 
1022   $locale = Locale->new($::lx_office_conf{system}->{language}, $script);
 
1024   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
1026   my $currency = $form->{currency};
 
1030   $form->{currency}     = $currency;
 
1031   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
1032   $form->{exchangerate} = $form->{forex} || '';
 
1034   for my $i (1 .. $form->{rowcount}) {
 
1035     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
 
1036             if ($form->{"${_}_${i}"}) }
 
1037         qw(ship qty sellprice basefactor discount));
 
1038     $form->{"converted_from_invoice_id_$i"} = delete $form->{"invoice_id_$i"};
 
1045   $main::lxdebug->enter_sub();
 
1047   my $form     = $main::form;
 
1048   my %myconfig = %main::myconfig;
 
1049   my $locale   = $main::locale;
 
1053   # we are coming from *_order and convert to quotation
 
1054   # it seems that quotation is only called if we have a existing order
 
1055   if ($form->{type} =~  /(sales|purchase)_order/) {
 
1056     $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
 
1058   if ($form->{second_run}) {
 
1059     $form->{print_and_post} = 0;
 
1061   delete $form->{$_} foreach (qw(id printed emailed queued quonumber transaction_description));
 
1064   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
 
1065     $form->{title} = $locale->text('Add Request for Quotation');
 
1066     $form->{vc}    = 'vendor';
 
1067     $form->{type}  = 'request_quotation';
 
1070   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
 
1071     $form->{title} = $locale->text('Add Quotation');
 
1072     $form->{vc}    = 'customer';
 
1073     $form->{type}  = 'sales_quotation';
 
1077   $form->{cp_id} *= 1;
 
1079   $form->{script} = 'oe.pl';
 
1081   $form->{rowcount}--;
 
1083   require "bin/mozilla/$form->{script}";
 
1085   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
1087   my $currency = $form->{currency};
 
1091   $form->{currency}     = $currency;
 
1092   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
1093   $form->{exchangerate} = $form->{forex} || '';
 
1095   for my $i (1 .. $form->{rowcount}) {
 
1096     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
 
1097                                                      $form->{"${_}_${i}"})
 
1098             if ($form->{"${_}_${i}"}) }
 
1099         qw(ship qty sellprice basefactor discount lastcost));
 
1105   $main::lxdebug->leave_sub();
 
1108 sub request_for_quotation {
 
1113   $::lxdebug->enter_sub();
 
1119   my $inline = delete $options{inline};
 
1121   require SL::Helper::PrintOptions;
 
1122   my $print_options = SL::Helper::PrintOptions->get_print_options(
 
1124     myconfig => \%::myconfig,
 
1125     locale   => $::locale,
 
1126     options  => \%options);
 
1129     $::lxdebug->leave_sub();
 
1130     return $print_options;
 
1133   print $print_options;
 
1134   $::lxdebug->leave_sub();
 
1139   $main::lxdebug->enter_sub();
 
1141   my $form     = $main::form;
 
1142   my $locale   = $main::locale;
 
1146   if ($form->{print_nextsub}) {
 
1147     call_sub($form->{print_nextsub});
 
1148     $main::lxdebug->leave_sub();
 
1152   # if this goes to the printer pass through
 
1154   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
 
1155     $form->error($locale->text('Select postscript or PDF!'))
 
1156       if ($form->{format} !~ /(postscript|pdf)/);
 
1158     $old_form = Form->new;
 
1159     map { $old_form->{$_} = $form->{$_} } keys %$form;
 
1162   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
 
1163     if ($form->{formname} eq "proforma") {
 
1164       $form->{proforma} = 1;
 
1166     $form->{print_and_save} = 1;
 
1167     my $formname = $form->{formname};
 
1169     $form->{formname} = $formname;
 
1171     $::lxdebug->leave_sub();
 
1172     $::dispatcher->end_request;
 
1175   &print_form($old_form);
 
1177   $main::lxdebug->leave_sub();
 
1181   $main::lxdebug->enter_sub();
 
1183   my $form     = $main::form;
 
1184   my %myconfig = %main::myconfig;
 
1185   my $locale   = $main::locale;
 
1189   my $defaults = SL::DB::Default->get;
 
1190   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
 
1191   $form->{templates} = $defaults->templates;
 
1193   my ($old_form, %params) = @_;
 
1197   my $numberfld = "invnumber";
 
1201     ($form->{display_form}) ? $form->{display_form} : "display_form";
 
1203   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
 
1204   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
 
1206   if ($form->{formname} eq "invoice") {
 
1207     $form->{label} = $locale->text('Invoice');
 
1210   if ($form->{formname} eq "invoice_for_advance_payment") {
 
1211     $form->{label} = $locale->text('Invoice for Advance Payment');
 
1214   if ($form->{formname} eq "final_invoice") {
 
1215     $form->{label} = $locale->text('Final Invoice');
 
1218   if ($form->{formname} eq 'sales_order') {
 
1221     $form->{"${inv}date"} = $form->{transdate};
 
1222     $form->{label}        = $locale->text('Confirmation');
 
1223     $numberfld            = "sonumber";
 
1227   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
 
1230     $form->{"${inv}date"} = $form->{invdate};
 
1231     $form->{label}        = $locale->text('Proforma Invoice');
 
1232     $numberfld            = "sonumber";
 
1236   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
 
1239     $form->{"${inv}date"} = $form->{transdate};
 
1240     $form->{"invdate"}    = $form->{transdate};
 
1241     $form->{invnumber}    = $form->{ordnumber};
 
1242     $form->{label}        = $locale->text('Proforma Invoice');
 
1243     $numberfld            = "sonumber";
 
1247   if ($form->{formname} eq 'purchase_order') {
 
1250     $form->{"${inv}date"} = $form->{transdate};
 
1251     $form->{label}        = $locale->text('Purchase Order');
 
1252     $numberfld            = "ponumber";
 
1255   if ($form->{formname} eq 'bin_list') {
 
1258     $form->{"${inv}date"} = $form->{transdate};
 
1259     $form->{label}        = $locale->text('Bin List');
 
1262   if ($form->{formname} eq 'sales_quotation') {
 
1265     $form->{"${inv}date"} = $form->{transdate};
 
1266     $form->{label}        = $locale->text('Quotation');
 
1267     $numberfld            = "sqnumber";
 
1271   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
 
1274     $form->{"${inv}date"} = $form->{transdate};
 
1275     $form->{"invdate"}    = $form->{transdate};
 
1276     $form->{label}        = $locale->text('Proforma Invoice');
 
1277     $numberfld            = "sqnumber";
 
1281   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'ic_supply') ) {
 
1284     $form->{"${inv}date"} = $form->{transdate};
 
1285     $form->{"invdate"}    = $form->{transdate};
 
1286     $form->{invnumber}    = $form->{ordnumber};
 
1287     $form->{label}        = $locale->text('Intra-Community supply');
 
1288     $numberfld            = "sonumber";
 
1292   if ($form->{formname} eq 'request_quotation') {
 
1295     $form->{"${inv}date"} = $form->{transdate};
 
1296     $form->{label}        = $locale->text('RFQ');
 
1297     $numberfld            = "rfqnumber";
 
1301   if ($form->{type} =~ /_delivery_order$/) {
 
1304     $form->{"${inv}date"} = $form->{transdate};
 
1305     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
 
1306     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
 
1308   if ($form->{type} =~ /letter/) {
 
1311     $form->{label}        = $locale->text('Letter');
 
1314   $form->{TEMPLATE_DRIVER_OPTIONS} = { };
 
1315   if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice invoice_for_advance_payment final_invoice request_quotation purchase_order purchase_delivery_order credit_note)) {
 
1316     $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = $form->get_variable_content_types();
 
1319   if ($form->{format} =~ m{pdf}) {
 
1320     _maybe_attach_zugferd_data($form);
 
1323   $form->isblank("email", $locale->text('E-mail address missing!'))
 
1324     if ($form->{media} eq 'email');
 
1325   $form->isblank("${inv}date",
 
1326            $locale->text($form->{label})
 
1328            . $locale->text(' Date missing!'));
 
1330   # $locale->text('Invoice Number missing!')
 
1331   # $locale->text('Invoice Date missing!')
 
1332   # $locale->text('Order Number missing!')
 
1333   # $locale->text('Order Date missing!')
 
1334   # $locale->text('Quotation Number missing!')
 
1335   # $locale->text('Quotation Date missing!')
 
1337   $form->{what_done} = $form->{formname};
 
1341   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
 
1342   my ($saved_email, $saved_cc, $saved_bcc) =
 
1343     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
 
1345   my $language_saved = $form->{language_id};
 
1346   my $payment_id_saved = $form->{payment_id};
 
1347   my $delivery_term_id_saved = $form->{delivery_term_id};
 
1348   my $salesman_id_saved = $form->{salesman_id};
 
1349   my $cp_id_saved = $form->{cp_id};
 
1350   my $taxzone_id_saved = $form->{taxzone_id};
 
1351   my $currency_saved = $form->{currency};
 
1353   call_sub("$form->{vc}_details") if ($form->{vc});
 
1355   $form->{language_id} = $language_saved;
 
1356   $form->{payment_id} = $payment_id_saved;
 
1357   $form->{delivery_term_id} = $delivery_term_id_saved;
 
1358   $form->{taxzone_id} = $taxzone_id_saved;
 
1359   $form->{currency} = $currency_saved;
 
1361   $form->{"email"} = $saved_email if ($saved_email);
 
1362   $form->{"cc"}    = $saved_cc    if ($saved_cc);
 
1363   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
 
1365   if (!$cp_id_saved) {
 
1366     # No contact was selected. Delete all contact variables because
 
1367     # IS->customer_details() and IR->vendor_details() get the default
 
1369     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
 
1372   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
1373   if ($form->{"language_id"}) {
 
1374     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
 
1375       AM->get_language_details(\%myconfig, $form, $form->{language_id});
 
1377     $output_dateformat = $myconfig{"dateformat"};
 
1378     $output_numberformat = $myconfig{"numberformat"};
 
1379     $output_longdates = 1;
 
1382   # Store the output number format so that the template modules know
 
1383   # how to parse the amounts back if requested.
 
1384   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
 
1386   ($form->{employee}) = split /--/, $form->{employee};
 
1388   # create the form variables
 
1389   if ($form->{type} =~ /_delivery_order$/) {
 
1390     DO->order_details(\%myconfig, \%$form);
 
1392     OE->order_details(\%myconfig, \%$form);
 
1393   } elsif ($form->{type} eq 'letter') {
 
1394     # right now, no details are needed
 
1395     # but i do not want to break the bad default (invoice)
 
1397     IS->invoice_details(\%myconfig, \%$form, $locale);
 
1400   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
 
1401   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
 
1403   if ($form->{shipto_id}) {
 
1404     $form->get_shipto(\%myconfig);
 
1407   $form->set_addition_billing_address_print_variables;
 
1409   $form->{notes} =~ s/^\s+//g;
 
1411   delete $form->{printer_command};
 
1413   $form->{language} = $form->get_template_language(\%myconfig);
 
1416   if ($form->{media} ne 'email') {
 
1417     $printer_code = $form->get_printer_code(\%myconfig);
 
1418     if ($printer_code ne "") {
 
1419       $printer_code = "_" . $printer_code;
 
1423   if ($form->{language} ne "") {
 
1424     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
 
1425     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
 
1427     $form->{language} = "_" . $form->{language};
 
1431   format_dates($output_dateformat, $output_longdates,
 
1432                qw(invdate orddate quodate pldate duedate reqdate transdate tax_point
 
1433                   shippingdate deliverydate validitydate paymentdate
 
1434                   datepaid transdate_oe transdate_do transdate_quo deliverydate_oe dodate
 
1435                   employee_startdate employee_enddate
 
1437                grep({ /^datepaid_\d+$/ ||
 
1438                         /^transdate_oe_\d+$/ ||
 
1439                         /^transdate_do_\d+$/ ||
 
1440                         /^transdate_quo_\d+$/ ||
 
1441                         /^deliverydate_oe_\d+$/ ||
 
1443                         /^deliverydate_\d+$/ ||
 
1447   reformat_numbers($output_numberformat, 2,
 
1448                    qw(invtotal ordtotal quototal subtotal linetotal
 
1449                       listprice sellprice netprice discount
 
1450                       tax taxbase total paid payment),
 
1451                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
 
1453   reformat_numbers($output_numberformat, undef,
 
1454                    qw(qty price_factor),
 
1458   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
1460   if (scalar @{ $cvar_date_fields }) {
 
1461     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
1464   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
1465     reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
1468   my $extension = 'html';
 
1469   if ($form->{format} eq 'postscript') {
 
1470     $form->{postscript}   = 1;
 
1473   } elsif ($form->{"format"} =~ /pdf/) {
 
1475     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
1477   } elsif ($form->{"format"} =~ /opendocument/) {
 
1478     $form->{opendocument} = 1;
 
1480   } elsif ($form->{"format"} =~ /excel/) {
 
1485   # search for the template
 
1486   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
 
1487     name        => $form->{formname},
 
1488     email       => $form->{media} eq 'email',
 
1489     language_id => $form->{language_id},
 
1490     printer_id  => $form->{printer_id},
 
1491     extension   => $extension,
 
1494   if (!defined $template_file) {
 
1495     $::form->error($::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files));
 
1498   $form->{IN} = $template_file;
 
1500   delete $form->{OUT};
 
1502   if ($form->{media} eq 'printer') {
 
1503     $form->{OUT}      = $form->{printer_command};
 
1504     $form->{OUT_MODE} = '|-';
 
1505     $form->{printed} .= " $form->{formname}";
 
1506     $form->{printed}  =~ s/^ //;
 
1508   my $printed = $form->{printed};
 
1510   if ($form->{media} eq 'email') {
 
1511     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
 
1512       unless $form->{subject};
 
1514     $form->{emailed} .= " $form->{formname}";
 
1515     $form->{emailed} =~ s/^ //;
 
1516     $form->{addition} = "MAILED";
 
1518   my $emailed = $form->{emailed};
 
1520   if ($form->{media} eq 'queue') {
 
1521     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
 
1524     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
 
1525     if ($filename = $queued{ $form->{formname} }) {
 
1526       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
 
1527       delete $queued{ $form->{formname} };
 
1529       $form->{queued}    =  join ' ', %queued;
 
1530       $filename          =~ s/\..*$//g;
 
1531       $filename         .=  $suffix;
 
1532       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
 
1533       $form->{OUT_MODE}  =  '>';
 
1537       ($temp_fh, $filename) = File::Temp::tempfile(
 
1538         'kivitendo-spoolXXXXXX',
 
1539         SUFFIX => "$suffix",
 
1540         DIR    => $::lx_office_conf{paths}->{spool},
 
1544       $form->{OUT} = "$filename";
 
1545       # use >> for OUT_MODE because file is already created by File::Temp
 
1546       $form->{OUT_MODE} = '>>';
 
1547       # strip directory so that only filename is stored in table status
 
1548       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
 
1552     $form->{queued} .= " $form->{formname} $filename";
 
1553     $form->{queued} =~ s/^ //;
 
1555   my $queued = $form->{queued};
 
1557 # saving the history
 
1558   if(!exists $form->{addition}) {
 
1559     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
 
1560     if($form->{media} =~ /printer/) {
 
1561       $form->{addition} = "PRINTED";
 
1563     elsif($form->{media} =~ /email/) {
 
1564       $form->{addition} = "MAILED";
 
1566     elsif($form->{media} =~ /queue/) {
 
1567       $form->{addition} = "QUEUED";
 
1569     elsif($form->{media} =~ /screen/) {
 
1570       $form->{addition} = "SCREENED";
 
1572     $form->save_history;
 
1574   # /saving the history
 
1576   # prepare meta information for template introspection
 
1577   $form->{template_meta} = {
 
1578     formname  => $form->{formname},
 
1579     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
 
1580     format    => $form->{format},
 
1581     media     => $form->{media},
 
1582     extension => $extension,
 
1583     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
 
1584     today     => DateTime->today,
 
1587   if ($defaults->print_interpolate_variables_in_positions) {
 
1588     $form->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
 
1591   $form->parse_template(\%myconfig);
 
1593   $form->{callback} = "";
 
1595   if ($form->{media} eq 'email') {
 
1596     $form->{message} = $locale->text('sent') unless $form->{message};
 
1598   my $message = $form->{message};
 
1600   # if we got back here restore the previous form
 
1601   if ($form->{media} =~ /(printer|email|queue)/) {
 
1603     $form->update_status(\%myconfig)
 
1604       if ($form->{media} eq 'queue' && $form->{id});
 
1606     return $main::lxdebug->leave_sub() if ($old_form eq "return");
 
1610       $old_form->{"${inv}number"} = $form->{"${inv}number"};
 
1612       # restore and display form
 
1613       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
 
1615       $form->{queued}  = $queued;
 
1616       $form->{printed} = $printed;
 
1617       $form->{emailed} = $emailed;
 
1618       $form->{message} = $message;
 
1620       $form->{rowcount}--;
 
1621       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
1622         qw(exchangerate creditlimit creditremaining);
 
1624       for my $i (1 .. $form->{paidaccounts}) {
 
1626           $form->{"${_}_$i"} =
 
1627             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
1628         } qw(paid exchangerate);
 
1631       call_sub($display_form);
 
1632       $::dispatcher->end_request;
 
1636       ($form->{media} eq 'printer')
 
1637       ? $locale->text('sent to printer')
 
1638       : $locale->text('emailed to') . " $form->{email}";
 
1640     if (!$params{no_redirect}) {
 
1641       $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
 
1644   if ($form->{printing}) {
 
1645    call_sub($display_form);
 
1646    $::dispatcher->end_request;
 
1649   $main::lxdebug->leave_sub();
 
1652 sub customer_details {
 
1653   $main::lxdebug->enter_sub();
 
1655   my $form     = $main::form;
 
1656   my %myconfig = %main::myconfig;
 
1658   IS->customer_details(\%myconfig, \%$form, @_);
 
1660   $main::lxdebug->leave_sub();
 
1663 sub vendor_details {
 
1664   $main::lxdebug->enter_sub();
 
1666   my $form     = $main::form;
 
1667   my %myconfig = %main::myconfig;
 
1669   IR->vendor_details(\%myconfig, \%$form, @_);
 
1671   $main::lxdebug->leave_sub();
 
1675   $main::lxdebug->enter_sub();
 
1677   my $form     = $main::form;
 
1681   $form->{postasnew} = 1;
 
1682   map { delete $form->{$_} } qw(printed emailed queued);
 
1686   $main::lxdebug->leave_sub();
 
1689 sub relink_accounts {
 
1690   $main::lxdebug->enter_sub();
 
1692   my $form     = $main::form;
 
1693   my %myconfig = %main::myconfig;
 
1695   $form->{"taxaccounts"} =~ s/\s*$//;
 
1696   $form->{"taxaccounts"} =~ s/^\s*//;
 
1697   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
 
1698     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber tax_id)); # add tax_id ?
 
1700   $form->{"taxaccounts"} = "";
 
1702   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
 
1704   $main::lxdebug->leave_sub();
 
1707 sub get_payment_terms_for_invoice {
 
1708   my $terms = $::form->{payment_id}  ? SL::DB::PaymentTerm->new(id => $::form->{payment_id}) ->load
 
1709             : $::form->{customer_id} ? SL::DB::Customer   ->new(id => $::form->{customer_id})->load->payment
 
1710             : $::form->{vendor_id}   ? SL::DB::Vendor     ->new(id => $::form->{vendor_id})  ->load->payment
 
1719   my $js      = SL::ClientJS->new(controller => SL::Controller::Base->new);
 
1720   my $terms   = get_payment_terms_for_invoice();
 
1721   my $invdate = $::form->{invdate} eq 'undefined' ? DateTime->today_local : DateTime->from_kivitendo($::form->{invdate});
 
1722   my $duedate = $terms ? $terms->calc_date(reference_date => $invdate, due_date => $::form->{duedate})->to_kivitendo : ($::form->{duedate} || $invdate->to_kivitendo);
 
1724   if ($terms && $terms->auto_calculation) {
 
1725     $js->hide('#duedate_container')
 
1726        ->show('#duedate_fixed')
 
1727        ->html('#duedate_fixed', $duedate);
 
1730     $js->show('#duedate_container')
 
1731        ->hide('#duedate_fixed');
 
1734   $js->val('#duedate', $duedate)
 
1738 sub _update_part_information {
 
1739   $main::lxdebug->enter_sub();
 
1741   my $form     = $main::form;
 
1743   my %part_information = IC->get_basic_part_info('id' => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ]);
 
1745   $form->{PART_INFORMATION} = \%part_information;
 
1747   foreach my $i (1..$form->{rowcount}) {
 
1748     next unless ($form->{"id_${i}"});
 
1750     my $info                        = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
 
1751     $form->{"partunit_${i}"}        = $info->{unit};
 
1752     $form->{"weight_$i"}            = $info->{weight};
 
1753     $form->{"part_type_$i"}         = $info->{part_type};
 
1754     $form->{"classification_id_$i"} = $info->{classification_id};
 
1755     $form->{"has_sernumber_$i"}     = $info->{has_sernumber};
 
1758   $main::lxdebug->leave_sub();
 
1762   return unless $::form->{id};
 
1763   my $helper = SL::Helper::ShippedQty->new->calculate($::form->{id});
 
1765   for my $i (1..$::form->{rowcount}) {
 
1766     if (my $oid = $::form->{"orderitems_id_$i"}) {
 
1767       $::form->{"ship_$i"} = $helper->shipped_qty->{$oid};
 
1772 sub _update_custom_variables {
 
1773   $main::lxdebug->enter_sub();
 
1775   my $form     = $main::form;
 
1777   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
 
1778   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
 
1780   $main::lxdebug->leave_sub();
 
1783 sub _render_custom_variables_inputs {
 
1784   $main::lxdebug->enter_sub(2);
 
1786   my $form     = $main::form;
 
1790   if (!$form->{CVAR_CONFIGS}->{IC}) {
 
1791     $main::lxdebug->leave_sub();
 
1795   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
 
1797   # get partsgroup_id from part
 
1799   if ($params{part_id}) {
 
1800     $partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id;
 
1803   my $num_visible_cvars = 0;
 
1804   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
 
1805     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
 
1807     # set partsgroup filter
 
1808     my $partsgroup_filtered = 0;
 
1809     if ($cvar->{flag_partsgroup_filter}) {
 
1810       if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) {
 
1811         $partsgroup_filtered = 1;
 
1815     my $hide_non_editable = 1;
 
1818     my $description = '';
 
1819     if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) {
 
1820       $num_visible_cvars++;
 
1821       $description = $cvar->{description} . ' ';
 
1825     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
 
1827     push @{ $params{ROW2} }, {
 
1828       line_break     => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)),
 
1829       description    => $description,
 
1832          hide_non_editable => $hide_non_editable,
 
1834          name_prefix       => 'ic_',
 
1835          name_postfix      => "_$params{row}",
 
1836          valid             => $cvar->{valid},
 
1837          value             => CVar->parse($::form->{$form_key}, $cvar),
 
1838          partsgroup_filtered => $partsgroup_filtered,
 
1843   $main::lxdebug->leave_sub(2);
 
1846 sub _remove_billed_or_delivered_rows {
 
1849   croak "Missing parameter 'quantities'" if !$params{quantities};
 
1851   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
 
1854   my $make_key = sub {
 
1856     return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
 
1857     my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
 
1858     return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
 
1861   my $removed_rows = 0;
 
1863   while ($row < $::form->{rowcount}) {
 
1865     next unless $::form->{"id_$row"};
 
1867     my $parts_id                      = $::form->{"id_$row"};
 
1868     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
 
1870     my $key                           = $make_key->($row);
 
1871     my $sub_qty                       = min($base_qty, $params{quantities}->{$key});
 
1872     $params{quantities}->{$key}      -= $sub_qty;
 
1874     if (!$sub_qty || ($sub_qty != $base_qty)) {
 
1875       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
 
1876       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
 
1883   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
 
1884   $::form->{rowcount} -= $removed_rows;
 
1887 # TODO: both of these are makeshift so that price sources can operate on rdbo objects. if
 
1888 # this ever gets rewritten in controller style, throw this out
 
1889 sub _make_record_item {
 
1890   my ($row, %params) = @_;
 
1893     sales_order             => 'OrderItem',
 
1894     purchase_order          => 'OrderItem',
 
1895     sales_quotation         => 'OrderItem',
 
1896     request_quotation       => 'OrderItem',
 
1897     invoice                 => 'InvoiceItem',
 
1898     invoice_for_advance_payment => 'InvoiceItem',
 
1899     final_invoice           => 'InvoiceItem',
 
1900     credit_note             => 'InvoiceItem',
 
1901     purchase_invoice        => 'InvoiceItem',
 
1902     purchase_delivery_order => 'DeliveryOrderItem',
 
1903     sales_delivery_order    => 'DeliveryOrderItem',
 
1904   }->{$::form->{type}};
 
1906   return unless $class;
 
1908   $class = 'SL::DB::' . $class;
 
1910   my %translated_methods = (
 
1911     'SL::DB::OrderItem' => {
 
1913       orderitems_id           => 'id',
 
1915     'SL::DB::DeliveryOrderItem' => {
 
1917       delivery_order_items_id => 'id',
 
1919     'SL::DB::InvoiceItem' => {
 
1925   eval "require $class";
 
1927   my $obj = $::form->{"orderitems_id_$row"}
 
1928           ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{"orderitems_id_$row"})
 
1931   for my $key (grep { /_$row$/ } keys %$::form) {
 
1933     $method =~ s/_$row$//;
 
1934     $method = $translated_methods{$class}{$method} // $method;
 
1935     my $value = $::form->{$key};
 
1936     if ($obj->meta->column($method)) {
 
1937       if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
 
1938         $obj->${\"$method\_as_date"}($value);
 
1939       } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
 
1940         $obj->${\"$method\_as_number"}(($value // '') eq '' ? undef : $value);
 
1941       } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
 
1942         $obj->$method(!!$value);
 
1943       } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
 
1944         $obj->$method(($value // '') eq '' ? undef : $value * 1);
 
1946         $obj->$method($value);
 
1949       if ($method eq 'discount') {
 
1950         $obj->discount($obj->discount / 100.0);
 
1954       $obj->{__additional_form_attributes}{$method} = $value;
 
1958   if ($::form->{"id_$row"}) {
 
1959     $obj->part(SL::DB::Part->load_cached($::form->{"id_$row"}));
 
1962   if ($obj->can('qty')) {
 
1963     $obj->qty(     $obj->qty      * $params{factor});
 
1964     $obj->base_qty($obj->base_qty * $params{factor});
 
1972     sales_order             => 'Order',
 
1973     purchase_order          => 'Order',
 
1974     sales_quotation         => 'Order',
 
1975     request_quotation       => 'Order',
 
1976     purchase_delivery_order => 'DeliveryOrder',
 
1977     sales_delivery_order    => 'DeliveryOrder',
 
1978   }->{$::form->{type}};
 
1980   if ($::form->{type} =~ /invoice|credit_note/) {
 
1981     $class = $::form->{vc} eq 'customer' ? 'Invoice'
 
1982            : $::form->{vc} eq 'vendor'   ? 'PurchaseInvoice'
 
1983            : do { die 'unknown invoice type' };
 
1986   my $factor = $::form->{type} =~ m{credit_note} ? -1 : 1;
 
1988   return unless $class;
 
1990   $class = 'SL::DB::' . $class;
 
1992   eval "require $class";
 
1994   my $obj = $::form->{id}
 
1995           ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{id})
 
1998   for my $method (keys %$::form) {
 
1999     next unless $obj->can($method);
 
2000     next unless $obj->meta->column($method);
 
2002     if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
 
2003       $obj->${\"$method\_as_date"}($::form->{$method});
 
2004     } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
 
2005       $obj->${\"$method\_as_number"}(($::form->{$method} // '') eq '' ? undef : $::form->{$method});
 
2006     } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
 
2007       $obj->$method(!!$::form->{$method});
 
2008     } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
 
2009       $obj->$method(($::form->{$method} // '') eq '' ? undef : $::form->{$method} * 1);
 
2011       $obj->$method($::form->{$method});
 
2016   for my $i (1 .. $::form->{rowcount}) {
 
2017     next unless $::form->{"id_$i"};
 
2018     push @items, _make_record_item($i, factor => $factor);
 
2021   $obj->items(@items) if @items;
 
2023   if ($class eq 'SL::DB::DeliveryOrder' && !$obj->order_type) {
 
2024     $obj->order_type(SL::DB::DeliveryOrder::TypeData::validate_type($::form->{type}));
 
2027   if ($class eq 'SL::DB::Invoice') {
 
2028     my $paid = $factor *
 
2030       map  { $::form->parse_amount(\%::myconfig, $::form->{$_}) }
 
2031       grep { m{^paid_\d+$} }
 
2039 sub setup_sales_purchase_print_options {
 
2040   my $print_form = Form->new('');
 
2041   $print_form->{printers}  = SL::DB::Manager::Printer->get_all_sorted;
 
2043   $print_form->{$_} = $::form->{$_} for qw(type media printer_id storno formname groupitems);
 
2045   return SL::Helper::PrintOptions->get_print_options(
 
2046     form    => $print_form,
 
2053 sub _get_files_for_email_dialog {
 
2054   my %files = map { ($_ => []) } qw(versions files vc_files part_files project_files);
 
2056   return %files if !$::instance_conf->get_doc_storage;
 
2058   if ($::form->{id}) {
 
2059     $files{versions} = [ SL::File->get_all_versions(object_id => $::form->{id},    object_type => $::form->{type}, file_type => 'document') ];
 
2060     $files{files}    = [ SL::File->get_all(         object_id => $::form->{id},    object_type => $::form->{type}, file_type => 'attachment') ];
 
2061     $files{vc_files} = [ SL::File->get_all(         object_id => $::form->{vc_id}, object_type => $::form->{vc},   file_type => 'attachment') ]
 
2062       if $::form->{vc} && $::form->{"vc_id"};
 
2063     $files{project_files} = [ SL::File->get_all(object_id => $::form->{project_id}, object_type => 'project',file_type => 'attachment') ]
 
2064       if $::form->{project_id};
 
2068     uniq_by { $_->{id} }
 
2071       +{ id         => $::form->{"id_$_"},
 
2072          partnumber => $::form->{"partnumber_$_"},
 
2074     } (1 .. $::form->{rowcount});
 
2076   foreach my $part (@parts) {
 
2077     my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
 
2078     push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
 
2081   foreach my $key (keys %files) {
 
2082     $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
 
2088 sub show_sales_purchase_email_dialog {
 
2092   if ($::form->{cp_id}) {
 
2093     $email = SL::DB::Contact->load_cached($::form->{cp_id})->cp_email;
 
2095   # write a dispatch table if a third type enters
 
2096   # check record mail for sales_invoice
 
2097   if ($::form->{type} eq 'invoice' && (!$email || $::instance_conf->get_invoice_mail_settings ne 'cp')) {
 
2098     # check for invoice_mail if defined (vc.invoice_email)
 
2099     $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->invoice_mail;
 
2100     if ($record_email) {
 
2101       # check if cc for contact is also wanted
 
2102       $email_cc = $email if ($::instance_conf->get_invoice_mail_settings eq 'invoice_mail_cc_cp');
 
2103       $email    = $record_email;
 
2106   # check record mail for sales_delivery_order
 
2107   if ($::form->{type} eq 'sales_delivery_order') {
 
2108     # check for deliver_order_mail if defined (vc.delivery_order_mail)
 
2109     $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->delivery_order_mail;
 
2110     if ($record_email) {
 
2111       # check if cc for contact is also wanted
 
2112       $email_cc = $email; # always cc to cp
 
2113       $email    = $record_email;
 
2116   # still no email? use general mail (vc.email)
 
2117   if (!$email && $::form->{vc} && $::form->{vc_id}) {
 
2118     $email = SL::DB::Customer->load_cached($::form->{vc_id})->email if 'customer' eq $::form->{vc};
 
2119     $email = SL::DB::Vendor  ->load_cached($::form->{vc_id})->email if 'vendor'   eq $::form->{vc};
 
2122   $email = '' if $::form->{type} eq 'purchase_delivery_order';
 
2124   $::form->{language} = $::form->get_template_language(\%::myconfig);
 
2125   $::form->{language} = "_" . $::form->{language};
 
2127   my %body_params = (record_email => $record_email);
 
2128   if (($::form->{type} eq 'invoice') && $::form->{direct_debit}) {
 
2129     $body_params{translation_type}          = "preset_text_invoice_direct_debit";
 
2130     $body_params{fallback_translation_type} = "preset_text_invoice";
 
2133   my @employees_with_email = grep {
 
2134     my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
 
2135     $user && !!trim($user->get_config_value('email'));
 
2136   } @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
 
2141     subject             => $::form->generate_email_subject,
 
2142     message             => $::form->generate_email_body(%body_params),
 
2143     attachment_filename => $::form->generate_attachment_filename,
 
2144     js_send_function    => 'kivi.SalesPurchase.send_email()',
 
2147   my %files = _get_files_for_email_dialog();
 
2149   my $all_partner_email_addresses;
 
2150   $all_partner_email_addresses = SL::DB::Customer->load_cached($::form->{vc_id})->get_all_email_addresses() if 'customer' eq $::form->{vc};
 
2151   $all_partner_email_addresses = SL::DB::Vendor  ->load_cached($::form->{vc_id})->get_all_email_addresses() if 'vendor'   eq $::form->{vc};
 
2153   my $html  = $::form->parse_html_template("common/_send_email_dialog", {
 
2154     email_form      => $email_form,
 
2155     show_bcc        => $::auth->assert('email_bcc', 'may fail'),
 
2157     is_customer     => $::form->{vc} eq 'customer',
 
2158     is_invoice_mail => ($record_email && $::form->{type} eq 'invoice'),
 
2159     ALL_EMPLOYEES   => \@employees_with_email,
 
2160     ALL_PARTNER_EMAIL_ADDRESSES => $all_partner_email_addresses,
 
2163   print $::form->ajax_response_header, $html;
 
2166 sub send_sales_purchase_email {
 
2167   my $type        = $::form->{type};
 
2168   my $id          = $::form->{id};
 
2169   my $script      = $type =~ m{sales_order|purchase_order|quotation} ? 'oe.pl'
 
2170                   : $type =~ m{delivery_}                            ? 'do.pl'
 
2173   my $email_form  = delete $::form->{email_form};
 
2175   if ($email_form->{additional_to}) {
 
2176     $email_form->{to} = join ', ', grep { $_ } $email_form->{to}, @{$email_form->{additional_to}};
 
2177     delete $email_form->{additional_to};
 
2180   my %field_names = (to => 'email');
 
2182   $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
 
2184   $::form->{media} = 'email';
 
2186   $::form->{attachment_policy} //= '';
 
2188   # Is an old file version available?
 
2190   if ($::form->{attachment_policy} eq 'old_file') {
 
2191     $attfile = SL::File->get_all(object_id     => $id,
 
2192                                  object_type   => $type,
 
2193                                  file_type     => 'document',
 
2194                                  print_variant => $::form->{formname},);
 
2197   if ($::form->{attachment_policy} eq 'no_file' || ($::form->{attachment_policy} eq 'old_file' && $attfile)) {
 
2198     $::form->send_email(\%::myconfig, 'pdf');
 
2201     print_form("return");
 
2202     Common->save_email_status(\%::myconfig, $::form);
 
2205   flash_later('info', $::locale->text('The email has been sent.'));
 
2207   print $::form->redirect_header($script . '?action=edit&id=' . $::form->escape($id) . '&type=' . $::form->escape($type));
 
2210 sub _maybe_attach_zugferd_data {
 
2213   my $record = _make_record();
 
2216     || !$record->can('customer')
 
2217     || !$record->customer
 
2218     || !$record->can('create_pdf_a_print_options')
 
2219     || !$record->can('create_zugferd_data')
 
2220     || !$record->customer->create_zugferd_invoices_for_this_customer;
 
2223     my $xmlfile = File::Temp->new;
 
2224     $xmlfile->print($record->create_zugferd_data);
 
2227     $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_a}           = $record->create_pdf_a_print_options(zugferd_xmp_data => $record->create_zugferd_xmp_data);
 
2228     $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_attachments} = [
 
2229       { source       => $xmlfile,
 
2230         name         => 'factur-x.xml',
 
2231         description  => $::locale->text('Factur-X/ZUGFeRD invoice'),
 
2232         relationship => '/Alternative',
 
2233         mime_type    => 'text/xml',
 
2238   if (my $e = SL::X::ZUGFeRDValidation->caught) {
 
2239     $::form->error($e->message);
 
2243 sub download_factur_x_xml {
 
2246   my $record = _make_record();
 
2249       || !$record->can('customer')
 
2250       || !$record->customer
 
2251       || !$record->can('create_pdf_a_print_options')
 
2252       || !$record->can('create_zugferd_data')
 
2253       || !$record->customer->create_zugferd_invoices_for_this_customer;
 
2255   my $xml_content = eval { $record->create_zugferd_data };
 
2257   if (my $e = SL::X::ZUGFeRDValidation->caught) {
 
2258     $::form->error($e->message);
 
2261   my $attachment_filename = $::form->generate_attachment_filename;
 
2262   $attachment_filename    =~ s{\.[^.]+$}{.xml};
 
2264     '-type'           => 'application/xml',
 
2265     '-connection'     => 'close',
 
2266     '-attachment'     => $attachment_filename,
 
2267     '-content-length' => length($xml_content),
 
2270   print $::request->cgi->header(%headers);
 
2272   $::locale->with_raw_io(\*STDOUT, sub { print $xml_content });