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., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  33 #######################################################################
 
  35 # common routines used in is, ir, oe
 
  37 #######################################################################
 
  41 use List::MoreUtils qw(any uniq);
 
  42 use List::Util qw(min max first);
 
  55 use SL::Helper::CreatePDF;
 
  56 use SL::Helper::Flash;
 
  58 require "bin/mozilla/common.pl";
 
  62 # any custom scripts for this one
 
  63 if (-f "bin/mozilla/custom_io.pl") {
 
  64   eval { require "bin/mozilla/custom_io.pl"; };
 
  66 if (-f "bin/mozilla/$::form->{login}_io.pl") {
 
  67   eval { require "bin/mozilla/$::form->{login}_io.pl"; };
 
  74 # this is for our long dates
 
  75 # $locale->text('January')
 
  76 # $locale->text('February')
 
  77 # $locale->text('March')
 
  78 # $locale->text('April')
 
  79 # $locale->text('May ')
 
  80 # $locale->text('June')
 
  81 # $locale->text('July')
 
  82 # $locale->text('August')
 
  83 # $locale->text('September')
 
  84 # $locale->text('October')
 
  85 # $locale->text('November')
 
  86 # $locale->text('December')
 
  88 # this is for our short month
 
  89 # $locale->text('Jan')
 
  90 # $locale->text('Feb')
 
  91 # $locale->text('Mar')
 
  92 # $locale->text('Apr')
 
  93 # $locale->text('May')
 
  94 # $locale->text('Jun')
 
  95 # $locale->text('Jul')
 
  96 # $locale->text('Aug')
 
  97 # $locale->text('Sep')
 
  98 # $locale->text('Oct')
 
  99 # $locale->text('Nov')
 
 100 # $locale->text('Dec')
 
 107   $main::auth->assert('part_service_assembly_edit   | vendor_invoice_edit       | sales_order_edit    | invoice_edit |' .
 
 108                 'request_quotation_edit       | sales_quotation_edit      | purchase_order_edit | ' .
 
 109                 'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details');
 
 112 ########################################
 
 113 # Eintrag fuer Version 2.2.0 geaendert #
 
 114 # neue Optik im Rechnungsformular      #
 
 115 ########################################
 
 117   $main::lxdebug->enter_sub();
 
 121   my $form     = $main::form;
 
 122   my %myconfig = %main::myconfig;
 
 123   my $locale   = $main::locale;
 
 124   my $cgi      = $::request->{cgi};
 
 128   my ($stock_in_out, $stock_in_out_title);
 
 130   my $defaults = AM->get_defaults();
 
 131   $form->{show_weight} = $defaults->{show_weight};
 
 132   $form->{weightunit} = $defaults->{weightunit};
 
 134   my $is_purchase        = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
 
 135   my $show_min_order_qty =  first { $_ eq $form->{type} } qw(request_quotation purchase_order);
 
 136   my $is_delivery_order  = $form->{type} =~ /_delivery_order$/;
 
 137   my $is_s_p_order       = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
 
 139   if ($is_delivery_order) {
 
 140     if ($form->{type} eq 'sales_delivery_order') {
 
 141       $stock_in_out_title = $locale->text('Release From Stock');
 
 142       $stock_in_out       = 'out';
 
 144       $stock_in_out_title = $locale->text('Transfer To Stock');
 
 145       $stock_in_out       = 'in';
 
 148     retrieve_partunits();
 
 152   my @header_sort = qw(runningnumber partnumber description ship qty unit weight sellprice_pg sellprice discount linetotal);
 
 154     {  id => 'runningnumber', width => 5,     value => $locale->text('No.'),                  display => 1, },
 
 155     {  id => 'partnumber',    width => 8,     value => $locale->text('Number'),               display => 1, },
 
 156     {  id => 'description',   width => 30,    value => $locale->text('Part Description'),     display => 1, },
 
 157     {  id => 'ship',          width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
 
 158     {  id => 'qty',           width => 5,     value => $locale->text('Qty'),                  display => 1, },
 
 159     {  id => 'price_factor',  width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
 
 160     {  id => 'unit',          width => 5,     value => $locale->text('Unit'),                 display => 1, },
 
 161     {  id => 'weight',        width => 5,     value => $locale->text('Weight'),               display => $defaults->{show_weight}, },
 
 162     {  id => 'serialnr',      width => 10,    value => $locale->text('Serial No.'),           display => 0, },
 
 163     {  id => 'projectnr',     width => 10,    value => $locale->text('Project'),              display => 0, },
 
 164     {  id => 'sellprice',     width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
 
 165     {  id => 'sellprice_pg',  width => 8,     value => $locale->text('Pricegroup'),           display => !$is_delivery_order && !$is_purchase, },
 
 166     {  id => 'discount',      width => 5,     value => $locale->text('Discount'),             display => !$is_delivery_order, },
 
 167     {  id => 'linetotal',     width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
 
 168     {  id => 'bin',           width => 10,    value => $locale->text('Bin'),                  display => 0, },
 
 169     {  id => 'stock_in_out',  width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
 
 171   my @column_index = map { $_->{id} } grep { $_->{display} } @HEADER;
 
 175   my $all_units       = AM->retrieve_units(\%myconfig, $form);
 
 177   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 179   my $colspan = scalar @column_index;
 
 181   $form->{invsubtotal} = 0;
 
 182   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
 
 185   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
 
 186   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
 
 189   # translations, unused commented out
 
 190 #  $runningnumber = $locale->text('No.');
 
 191 #  my $deliverydate  = $locale->text('Delivery Date');
 
 192   my $serialnumber  = $locale->text('Serial No.');
 
 193   my $projectnumber = $locale->text('Project');
 
 194 #  $partsgroup    = $locale->text('Group');
 
 195   my $reqdate       = $locale->text('Reqdate');
 
 196   my $deliverydate  = $locale->text('Required by');
 
 199   my %align  = map { $_ => 'right' } qw(qty ship right sellprice_pg discount linetotal stock_in_out weight);
 
 200   my %nowrap = map { $_ => 1 }       qw(description unit);
 
 202   $form->{marge_total}           = 0;
 
 203   $form->{sellprice_total}       = 0;
 
 204   $form->{lastcost_total}        = 0;
 
 205   $form->{totalweight}           = 0;
 
 206   my %projectnumber_labels = ();
 
 207   my @projectnumber_values = ("");
 
 209   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 210     push(@projectnumber_values, $item->{"id"});
 
 211     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
 
 214   _update_part_information();
 
 215   _update_ship() if ($is_s_p_order);
 
 216   _update_custom_variables();
 
 223   for my $i (1 .. $numrows) {
 
 224     my %column_data = ();
 
 227     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
 
 228       qw(qty discount sellprice lastcost price_new price_old)
 
 229         unless ($form->{simple_save});
 
 231     if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
 
 232       $form->{"sellprice_$i"} = $form->{"price_new_$i"};
 
 236     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
 
 237     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
 
 239     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
 240         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
 241       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
 243     # adjust prices by unit, ignore if pricegroup changed
 
 244     if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) {
 
 245         $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 246         $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 247         $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
 
 249     my $this_unit = $form->{"unit_$i"};
 
 250     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
 
 252     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
 
 253       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
 
 254       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
 
 256       $column_data{price_factor} =
 
 257         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
 
 258                              '-default' => $form->{"price_factor_id_$i"},
 
 259                              '-values'  => \@values,
 
 260                              '-labels'  => \%labels,
 
 261                              '-style'   => 'width:90px'));
 
 263       $column_data{price_factor} = ' ';
 
 265     $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
 
 267     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
 
 270 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
 
 271 #is shown for lastcost and sellprice.
 
 272     my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
 
 273     $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
 
 275     my $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
 
 276     my $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
 
 277     my $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
 
 278     my $rows            = $form->numtextrows($form->{"description_$i"}, 30, 6);
 
 280     # quick delete single row
 
 281     $column_data{runningnumber} .= q|<a onclick= "$('#partnumber_| . $i . q|').val(''); $('#update_button').click();">| .
 
 282                                    q|<img height="10px" width="10px" src="image/cross.png" alt="| . $locale->text('Remove') . q|"></a> |;
 
 283     $column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
 
 286     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -id => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
 
 287     $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
 
 288                                 ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
 
 289                                 : $cgi->textfield(-name => "description_$i", -id => "description_$i",   -value => $form->{"description_$i"}, -size => 30))
 
 290                                 . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
 
 292     my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
 
 294     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
 
 295     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_window('qty_$i','alu_$i', 'formel_$i', $i)", -value => $locale->text('*/'))
 
 296                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"}) . $cgi->hidden("-name" => "alu_$i", "-value" => $form->{"alu_$i"})
 
 297       if $form->{"formel_$i"};
 
 299     $column_data{ship} = '';
 
 300     if ($form->{"id_$i"}) {
 
 301       my $ship_qty        = $form->{"ship_$i"} * 1;
 
 302       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
 
 303       $ship_qty          /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
 
 305       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"};
 
 308     # build in drop down list for pricesgroups
 
 309     # $sellprice_value setzt den Wert etwas unabhängiger von der Darstellung.
 
 310     # Hintergrund: Preisgruppen werden hier überprüft und neu berechnet.
 
 311     # Vorher wurde der ganze cgi->textfield Block zweimal identisch eingebaut, dass passiert
 
 312     # jetzt nach der Abfrage.
 
 314     if ($form->{"prices_$i"}) {
 
 315       $column_data{sellprice_pg} = qq|<select name="sellprice_pg_$i" style="width: 8em">$form->{"prices_$i"}</select>|;
 
 316       $sellprice_value           =($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})
 
 317                                       ? $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces)
 
 318                                       : $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 320       # for last row and report
 
 321       # set pricegroup drop down list from report menu
 
 322       if ($form->{"sellprice_$i"} != 0) {
 
 323         # remember the pricegroup_id in pricegroup_old
 
 324         # but don't overwrite it
 
 325         $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"};
 
 326         my $default_option           = $form->{"sellprice_$i"}.'--'.$form->{"pricegroup_id_$i"};
 
 327         $column_data{sellprice_pg}   = NTI($cgi->popup_menu("sellprice_pg_$i", [ $default_option ], $default_option, { $default_option => $form->{"pricegroup_$i"} || '' }));
 
 329         $column_data{sellprice_pg} = qq| |;
 
 331       $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 334     # Falls der Benutzer die Preise nicht anpassen sollte, wird das entsprechende
 
 335     # Textfield auf readonly gesetzt. Anm. von Sven: Manipulation der Preise ist
 
 336     # immer noch möglich, konsequenterweise sollten diese NUR aus der Datenbank
 
 338     my $edit_prices = $main::auth->assert('edit_prices', 1);
 
 339     $column_data{sellprice} = (!$edit_prices)
 
 340                                 ? $cgi->textfield(-readonly => "readonly",
 
 341                                                   -name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value)
 
 342                                 : $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value);
 
 343     $column_data{discount}    = (!$edit_prices)
 
 344                                   ? $cgi->textfield(-readonly => "readonly",
 
 345                                                     -name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}))
 
 346                                   : $cgi->textfield(-name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}));
 
 347     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
 
 348     $column_data{bin}         = $form->{"bin_$i"};
 
 350     $column_data{weight}      = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
 
 352     if ($is_delivery_order) {
 
 353       $column_data{stock_in_out} =  calculate_stock_in_out($i);
 
 356     my @ROW1 = map { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} }, @column_index;
 
 360     push @ROW2, { value => qq|<b>$serialnumber</b> <input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">| }
 
 361       if $form->{type} !~ /_quotation/;
 
 362     push @ROW2, { value => qq|<b>$projectnumber</b> | . NTI($cgi->popup_menu('-name'  => "project_id_$i",        '-values'  => \@projectnumber_values,
 
 363                                                                              '-labels' => \%projectnumber_labels, '-default' => $form->{"project_id_$i"})) };
 
 364     push @ROW2, { value => qq|<b>$reqdate</b> <input name="reqdate_$i" size="11" onBlur="check_right_date_format(this)" value="$form->{"reqdate_$i"}">| }
 
 365       if ($form->{type} =~ /order/ ||  $form->{type} =~ /invoice/);
 
 366     push @ROW2, { value => sprintf qq|<b>%s</b> <input type="checkbox" name="subtotal_$i" value="1" %s>|,
 
 367                    $locale->text('Subtotal'), $form->{"subtotal_$i"} ? 'checked' : '' };
 
 369 # begin marge calculations
 
 370     $form->{"lastcost_$i"}     *= 1;
 
 371     $form->{"marge_percent_$i"} = 0;
 
 375     if ( $form->{taxincluded} and $form->{"qty_$i"} * 1  and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
 
 376       # if we use taxincluded we need to calculate the marge from the net_value
 
 377       # all the marge calculations are based on linetotal which we need to
 
 378       # convert to net first
 
 380       # there is no direct form value for the tax_rate of the item, but
 
 381       # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
 
 382       # gives the tax percentage (e.g. 0.19)
 
 383       $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
 
 385       $real_sellprice            = $linetotal;
 
 387     my $real_lastcost            = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 388     my $marge_percent_warn       = $myconfig{marge_percent_warn} * 1 || 15;
 
 389     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
 
 391     if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
 
 392       $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
 
 393       $marge_color                = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
 
 396     $form->{"marge_absolut_$i"}  = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
 
 397     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
 
 398     $form->{"lastcost_total"}   += $real_lastcost;
 
 399     $form->{"sellprice_total"}  += $real_sellprice;
 
 401     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
 
 403     push @ROW2, { value => sprintf qq|
 
 404          <font %s><b>%s</b> %s  %s%% </font>
 
 406          <b>%s</b> <input size="5" name="lastcost_$i" value="%s">|,
 
 407                    $marge_color, $locale->text('Ertrag'),$form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"},
 
 408                    $locale->text('LP'), $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2),
 
 409                    $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces) }
 
 410       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/ || $form->{type} =~ /^credit_note$/ ) && !$is_delivery_order;
 
 412     $form->{"listprice_$i"} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2)
 
 413       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/) ;
 
 414 # / marge calculations ending
 
 416 # Calculate total weight
 
 417     $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
 
 420     if ($form->{"id_$i"}) {
 
 421       my $part         = IC->get_basic_part_info(id => $form->{"id_$i"});
 
 422       my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
 
 423       push @ROW2, { value => sprintf "<b>%s</b> <font %s>%s %s</font>",
 
 424                       $locale->text('On Hand'),
 
 426                       $form->format_amount(\%myconfig, $part->{onhand}, 2),
 
 434     if ($is_delivery_order) {
 
 435       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
 
 436       $form->{"pricegroup_id_$i"} = $form->{"pricegroup_old_$i"} if $form->{"pricegroup_old_$i"};
 
 437       $form->{"sellprice_pg_$i"}  = $form->{"hidden_prices_$i"}  if $form->{"hidden_prices_$i"};
 
 438       push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost pricegroup_id sellprice_pg);
 
 439       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
 
 442     my @HIDDENS = map { value => $_}, (
 
 443           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
 
 444           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
 
 445           map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
 
 446             (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes
 
 447                 income_accno expense_accno listprice assembly taxaccounts ordnumber donumber transdate cusordnumber
 
 448                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
 
 451     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
 
 453     $form->{invsubtotal} += $linetotal;
 
 455     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
 
 456     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
 
 458     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, };
 
 461   $form->{totalweight} = $totalweight;
 
 463   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
 
 467   if (0 != ($form->{sellprice_total} * 1)) {
 
 468     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
 
 471   $main::lxdebug->leave_sub();
 
 474 ##################################################
 
 475 # build html-code for pricegroups in variable $form->{prices_$j}
 
 478   $main::lxdebug->enter_sub();
 
 480   my $form     = $main::form;
 
 481   my $locale   = $main::locale;
 
 482   my $cgi      = $::request->{cgi};
 
 486   my $rowcount = shift;
 
 487   for my $j (1 .. $rowcount) {
 
 488     next unless $form->{PRICES}{$j};
 
 489     # build drop down list for pricegroups
 
 490     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
 
 491     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} }
 
 492                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
 
 494     foreach my $item (@{ $form->{PRICES}{$j} }) {
 
 495       # set new selectedpricegroup_id and prices for "Preis"
 
 496       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
 
 497       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
 
 498       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
 
 501     # save hidden pricegroups for delivery_orders
 
 502     next unless my @selected_prices = grep { $_->{selected} } @{ $form->{PRICES}{$j} };
 
 503     $form->{"hidden_prices_$j"} = $selected_prices[-1]{price} . "--" . $selected_prices[-1]{pricegroup_id};
 
 505   $main::lxdebug->leave_sub();
 
 509   $main::lxdebug->enter_sub();
 
 512   my $mode   = $params{mode} || croak "Missing parameter 'mode'";
 
 516   my $previous_form = $::auth->save_form_in_session(form => $::form);
 
 517   $::form->{title}  = $::locale->text('Select from one of the items below');
 
 520   my @item_list = map {
 
 521     $_->{display_sellprice}  = $_->{sellprice} * (1 - $::form->{tradediscount});
 
 522     $_->{display_sellprice} /= $_->{price_factor} if ($_->{price_factor});
 
 524   } @{ $::form->{item_list} };
 
 526   # delete action variable
 
 527   delete @{$::form}{qw(action item_list)};
 
 529   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
 
 531                                                          ITEM_LIST     => \@item_list,
 
 532                                                          IS_PURCHASE   => $mode eq 'IS' });
 
 534   $main::lxdebug->leave_sub();
 
 538   $main::lxdebug->enter_sub();
 
 540   my $form     = $main::form;
 
 541   my %myconfig = %main::myconfig;
 
 545   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
 
 547   my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
 
 548   my $id   = delete($form->{select_item_id})   || croak 'Missing item selection ID';
 
 549   my $i    = $form->{ $mode eq 'IC' ? 'assembly_rows' : 'rowcount' };
 
 551   $form->{"id_${i}"} = $id;
 
 554     IS->retrieve_item(\%myconfig, \%$form);
 
 555   } elsif ($mode eq 'IR') {
 
 556     IR->retrieve_item(\%myconfig, \%$form);
 
 557   } elsif ($mode eq 'IC') {
 
 558     IC->assembly_item(\%myconfig, \%$form);
 
 560     croak "Invalid item selection mode '${mode}'";
 
 563   my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
 
 565   # if there was a price entered, override it
 
 566   my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 569     qw(id partnumber description sellprice listprice inventory_accno
 
 570        income_accno expense_accno bin unit weight assembly taxaccounts
 
 571        partsgroup formel longdescription not_discountable partnotes lastcost
 
 572        price_factor_id price_factor);
 
 574   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 575   push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 577   map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
 
 579   $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
 
 581   if ($form->{"part_payment_id_$i"} ne "") {
 
 582     $form->{payment_id} = $form->{"part_payment_id_$i"};
 
 585   my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 587   my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 590     $form->{"sellprice_$i"} = $sellprice;
 
 593     # if there is an exchange rate adjust sellprice
 
 594     if (($form->{exchangerate} * 1) != 0) {
 
 595       $form->{"sellprice_$i"} /= $form->{exchangerate};
 
 596       $form->{"sellprice_$i"} =
 
 597         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
 
 601     if ($::form->{tradediscount}) {
 
 602       $::form->{"sellprice_$i"} *= 1 - $::form->{tradediscount};
 
 606   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 607     qw(sellprice listprice weight);
 
 609   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
 
 611   if ($form->{"not_discountable_$i"}) {
 
 612     $form->{"discount_$i"} = 0;
 
 616     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
 
 618   map { $form->{"${_}_base"} += $amount }
 
 619     (split / /, $form->{"taxaccounts_$i"});
 
 620   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
 
 621     $form->{"taxaccounts_$i"}
 
 622     if !$form->{taxincluded};
 
 624   $form->{creditremaining} -= $amount;
 
 626   $form->{"runningnumber_$i"} = $i;
 
 628   delete $form->{nextsub};
 
 633       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
 
 634   } qw(sellprice listprice lastcost) if $form->{item} ne 'assembly';
 
 636   # get pricegroups for parts
 
 637   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 639   # build up html code for prices_$i
 
 640   set_pricegroup($form->{rowcount});
 
 644   $main::lxdebug->leave_sub();
 
 648   $main::lxdebug->enter_sub();
 
 650   my $form     = $main::form;
 
 651   my %myconfig = %main::myconfig;
 
 655   my $price_key = ($form->{type} =~ m/request_quotation|purchase_order/) || ($form->{script} eq 'ir.pl') ? 'lastcost' : 'sellprice';
 
 658   $form->{old_callback} = $form->escape($form->{callback}, 1);
 
 659   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
 
 661   # save all form variables except action in the session and keep the key in the previousform variable
 
 662   my $previousform = $::auth->save_form_in_session(skip_keys => [ qw(action) ]);
 
 665   push @HIDDENS,      { 'name' => 'previousform', 'value' => $previousform };
 
 666   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc);
 
 667   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit);
 
 668   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
 
 669   push @HIDDENS,      { 'name' => $price_key,     'value' => $form->parse_amount(\%myconfig, $form->{"sellprice_$form->{rowcount}"}) };
 
 670   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{"longdescription_$form->{rowcount}"} };
 
 673   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
 
 675   $main::lxdebug->leave_sub();
 
 679   $main::lxdebug->enter_sub();
 
 681   my $form     = $main::form;
 
 682   my %myconfig = %main::myconfig;
 
 689   # remove any makes or model rows
 
 690   if ($form->{item} eq 'assembly') {
 
 692     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
 
 693     #$form->{sellprice} = 0;
 
 695     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 696       qw(listprice sellprice rop stock);
 
 698     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
 
 700     for my $i (1 .. ($form->{assembly_rows} - 1)) {
 
 701       if ($form->{"qty_$i"}) {
 
 705         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 707         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 709         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 711         # fuer assemblies auskommentiert. siehe oben
 
 712         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
 
 713         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
 
 717     # kann das hier auch weg? s.o. jb
 
 718     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
 
 720     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
 
 721     $form->{assembly_rows} = $count;
 
 723   } elsif ($form->{item} !~ m{^(?:part|service)$}) {
 
 724     remove_emptied_rows(1);
 
 726     $form->{creditremaining} -= &invoicetotal;
 
 731   if (   $form->{type} =~ (/sales_quotation/)
 
 732       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
 
 733       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
 
 734       or ($form->{type} =~ /sales_order/)) {
 
 736     # get pricegroups for parts
 
 737     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 739     # build up html code for prices_$i
 
 740     set_pricegroup($form->{rowcount});
 
 746   $main::lxdebug->leave_sub();
 
 749 sub remove_emptied_rows {
 
 750   my $dont_add_empty = shift;
 
 753   return unless $form->{rowcount};
 
 755   my @flds = qw(id partnumber description qty ship sellprice unit
 
 756                 discount inventory_accno income_accno expense_accno listprice
 
 757                 taxaccounts bin assembly weight projectnumber project_id
 
 758                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
 
 759                 not_discountable shop ve gv buchungsgruppen_id language_values
 
 760                 sellprice_pg pricegroup_old price_old price_new unit_old ordnumber donumber
 
 761                 transdate longdescription basefactor marge_total marge_percent
 
 762                 marge_price_factor lastcost price_factor_id partnotes
 
 763                 stock_out stock_in has_sernumber reqdate);
 
 765   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 766   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 769   for my $i (1 .. $form->{rowcount} - 1) {
 
 770     next unless $form->{"partnumber_$i"};
 
 772     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
 
 775   my $new_rowcount = scalar @new_rows;
 
 776   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
 
 777   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
 
 781   $main::lxdebug->enter_sub();
 
 783   my $form     = $main::form;
 
 784   my %myconfig = %main::myconfig;
 
 788   $form->{oldinvtotal} = 0;
 
 790   # add all parts and deduct paid
 
 791   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
 
 793   my ($amount, $sellprice, $discount, $qty);
 
 795   for my $i (1 .. $form->{rowcount}) {
 
 796     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 797     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
 
 798     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 800     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 802     $amount = $sellprice * (1 - $discount / 100) * $qty;
 
 803     map { $form->{"${_}_base"} += $amount }
 
 804       (split (/ /, $form->{"taxaccounts_$i"}));
 
 805     $form->{oldinvtotal} += $amount;
 
 808   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
 
 809     split(/ /, $form->{taxaccounts})
 
 810     if !$form->{taxincluded};
 
 812   $form->{oldtotalpaid} = 0;
 
 813   for my $i (1 .. $form->{paidaccounts}) {
 
 814     $form->{oldtotalpaid} += $form->{"paid_$i"};
 
 817   $main::lxdebug->leave_sub();
 
 820   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 824   $main::lxdebug->enter_sub();
 
 826   my $form     = $main::form;
 
 827   my $locale   = $main::locale;
 
 831   # check if items are valid
 
 832   if ($form->{rowcount} == 1) {
 
 833     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
 
 838   for my $i (1 .. $form->{rowcount} - 1) {
 
 839     $form->isblank("partnumber_$i",
 
 840                    $locale->text('Number missing in Row') . " $i");
 
 843   $main::lxdebug->leave_sub();
 
 847   $main::lxdebug->enter_sub();
 
 849   my $form     = $main::form;
 
 850   my %myconfig = %main::myconfig;
 
 851   my $locale   = $main::locale;
 
 855   if ($form->{second_run}) {
 
 856     $form->{print_and_post} = 0;
 
 858   $form->{ordnumber} = $form->{invnumber};
 
 860   $form->{old_employee_id} = $form->{employee_id};
 
 861   $form->{old_salesman_id} = $form->{salesman_id};
 
 863   map { delete $form->{$_} } qw(id printed emailed queued);
 
 865   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
 
 866     $form->{title} = $locale->text('Add Purchase Order');
 
 867     $form->{vc}    = 'vendor';
 
 868     $form->{type}  = 'purchase_order';
 
 871   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
 
 872     $form->{title} = $locale->text('Add Sales Order');
 
 873     $form->{vc}    = 'customer';
 
 874     $form->{type}  = 'sales_order';
 
 877   $form->{script} = 'oe.pl';
 
 883   require "bin/mozilla/$form->{script}";
 
 884   my $script = $form->{"script"};
 
 887   $locale = new Locale($::lx_office_conf{system}->{language}, $script);
 
 889   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
 891   my $currency = $form->{currency};
 
 895   $form->{currency}     = $currency;
 
 896   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
 897   $form->{exchangerate} = $form->{forex} || '';
 
 899   for my $i (1 .. $form->{rowcount}) {
 
 900     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
 
 901             if ($form->{"${_}_${i}"}) }
 
 902         qw(ship qty sellprice listprice basefactor discount));
 
 908   $main::lxdebug->leave_sub();
 
 912   $main::lxdebug->enter_sub();
 
 914   my $form     = $main::form;
 
 915   my %myconfig = %main::myconfig;
 
 916   my $locale   = $main::locale;
 
 920   if ($form->{second_run}) {
 
 921     $form->{print_and_post} = 0;
 
 923   map { delete $form->{$_} } qw(id printed emailed queued);
 
 926   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
 
 927     $form->{title} = $locale->text('Add Request for Quotation');
 
 928     $form->{vc}    = 'vendor';
 
 929     $form->{type}  = 'request_quotation';
 
 932   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
 
 933     $form->{title} = $locale->text('Add Quotation');
 
 934     $form->{vc}    = 'customer';
 
 935     $form->{type}  = 'sales_quotation';
 
 941   $form->{script} = 'oe.pl';
 
 945   require "bin/mozilla/$form->{script}";
 
 947   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
 949   my $currency = $form->{currency};
 
 953   $form->{currency}     = $currency;
 
 954   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
 955   $form->{exchangerate} = $form->{forex} || '';
 
 957   for my $i (1 .. $form->{rowcount}) {
 
 958     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
 
 959                                                      $form->{"${_}_${i}"})
 
 960             if ($form->{"${_}_${i}"}) }
 
 961         qw(ship qty sellprice listprice basefactor discount lastcost));
 
 967   $main::lxdebug->leave_sub();
 
 970 sub request_for_quotation {
 
 975   $main::lxdebug->enter_sub();
 
 977   my $form     = $main::form;
 
 978   my %myconfig = %main::myconfig;
 
 979   my $locale   = $main::locale;
 
 983   if ($form->{second_run}) {
 
 984     $form->{print_and_post} = 0;
 
 985     $form->{resubmit}       = 0;
 
 988   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
 
 990   if ($form->{"cp_id"}) {
 
 991     CT->get_contact(\%myconfig, $form);
 
 992     $form->{"email"} = $form->{"cp_email"} if $form->{"cp_email"};
 
 995   $form->{language} = $form->get_template_language(\%myconfig);
 
 996   $form->{language} = "_" . $form->{language} if $form->{language};
 
 998   my $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
 
1000   $form->{oldmedia} = $form->{media};
 
1001   $form->{media}    = "email";
 
1003   my $global_bcc = AM->get_defaults()->{global_bcc};
 
1005   $form->{bcc} = join ', ', grep $_, $form->{bcc}, $global_bcc;
 
1007   my $attachment_filename = $form->generate_attachment_filename();
 
1008   my $subject             = $form->{subject} || $form->generate_email_subject();
 
1012   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
 
1013   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override login password);
 
1014   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
 
1015   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
 
1017   print $form->parse_html_template('generic/edit_email',
 
1019                                      a_filename    => $attachment_filename,
 
1020                                      subject       => $subject,
 
1021                                      print_options => print_options('inline' => 1),
 
1022                                      HIDDEN        => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
 
1023                                      SHOW_BCC      => $::auth->assert('email_bcc', 'may fail') });
 
1025   $main::lxdebug->leave_sub();
 
1029   $main::lxdebug->enter_sub();
 
1031   my $form     = $main::form;
 
1032   my %myconfig = %main::myconfig;
 
1036   my $callback = $form->{script} . "?action=edit";
 
1037   map({ $callback .= "\&${_}=" . E($form->{$_}); } qw(type id));
 
1039   print_form("return");
 
1041   Common->save_email_status(\%myconfig, $form);
 
1043   $form->{callback} = $callback;
 
1046   $main::lxdebug->leave_sub();
 
1049 # generate the printing options displayed at the bottom of oe and is forms.
 
1050 # this function will attempt to guess what type of form is displayed, and will generate according options
 
1053 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
 
1054 # the opthash function builds hashrefs which are then pieced together for the template arrays.
 
1055 # unneeded options are "undef"ed out, and then grepped out.
 
1057 # the inline options is untested, but intended to be used later in metatemplating
 
1059   $main::lxdebug->enter_sub();
 
1061   my $form     = $main::form;
 
1062   my %myconfig = %main::myconfig;
 
1063   my $locale   = $main::locale;
 
1069   # names 3 parameters and returns a hashref, for use in templates
 
1070   sub opthash { +{ value => shift, selected => shift, oname => shift } }
 
1071   my (@FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
 
1073   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
 
1074   $form->{sendmode}   = "attachment";
 
1075   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
 
1076   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
 
1077   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
 
1078   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
 
1079                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
 
1081   $form->{PD}{ $form->{formname} } = "selected";
 
1082   $form->{DF}{ $form->{format} }   = "selected";
 
1083   $form->{OP}{ $form->{media} }    = "selected";
 
1084   $form->{SM}{ $form->{formname} } = "selected";
 
1086   push @FORMNAME, grep $_,
 
1087     ($form->{type} eq 'purchase_order') ? (
 
1088       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
 
1089       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List'))
 
1091     ($form->{type} eq 'credit_note') ?
 
1092       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
 
1093     ($form->{type} eq 'sales_order') ? (
 
1094       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
 
1095       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
 
1097     ($form->{type} =~ /sales_quotation$/) ?
 
1098       opthash('sales_quotation',     $form->{PD}{sales_quotation},     $locale->text('Quotation')) : undef,
 
1099     ($form->{type} =~ /request_quotation$/) ?
 
1100       opthash('request_quotation',   $form->{PD}{request_quotation},   $locale->text('Request for Quotation')) : undef,
 
1101     ($form->{type} eq 'invoice') ? (
 
1102       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
 
1103       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
 
1105     ($form->{type} eq 'invoice' && $form->{storno}) ? (
 
1106       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
 
1108     ($form->{type} =~ /_delivery_order$/) ? (
 
1109       opthash($form->{type},         $form->{PD}{$form->{type}},       $locale->text('Delivery Order')),
 
1110       opthash('pick_list',           $form->{PD}{pick_list},           $locale->text('Pick List')),
 
1114     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
 
1115     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
 
1116       if ($form->{media} eq 'email');
 
1118   my $printable_templates = any { $::lx_office_conf{print_templates}->{$_} } qw(latex opendocument);
 
1119   push @MEDIA, grep $_,
 
1120       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
 
1121     ($printable_templates && $form->{printers} && scalar @{ $form->{printers} }) ?
 
1122       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
 
1123     ($printable_templates && !$options{no_queue}) ?
 
1124       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
 
1125         if ($form->{media} ne 'email');
 
1127   push @FORMAT, grep $_,
 
1128     ($::lx_office_conf{print_templates}->{opendocument} &&     $::lx_office_conf{applications}->{openofficeorg_writer}  &&     $::lx_office_conf{applications}->{xvfb}
 
1129                                                         && (-x $::lx_office_conf{applications}->{openofficeorg_writer}) && (-x $::lx_office_conf{applications}->{xvfb})
 
1130      && !$options{no_opendocument_pdf}) ?
 
1131       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
 
1132     ($::lx_office_conf{print_templates}->{latex}) ?
 
1133       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
 
1134     ($::lx_office_conf{print_templates}->{latex} && !$options{no_postscript}) ?
 
1135       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
 
1136     (!$options{no_html}) ?
 
1137       opthash("html", $form->{DF}{html}, "HTML") : undef,
 
1138     ($::lx_office_conf{print_templates}->{opendocument} && !$options{no_opendocument}) ?
 
1139       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef,
 
1140     ($::lx_office_conf{print_templates}->{excel} && !$options{no_excel}) ?
 
1141       opthash("excel",               $form->{DF}{excel},               $locale->text("Excel")) : undef;
 
1144     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
 
1145       if (ref $form->{languages} eq 'ARRAY');
 
1148     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
 
1149       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
 
1154     show  => !$options{"hide_" . $_->[1]} && scalar @{ $_->[0] }
 
1156   [ \@FORMNAME,    'formname',    ],
 
1157   [ \@LANGUAGE_ID, 'language_id', ],
 
1158   [ \@FORMAT,      'format',      ],
 
1159   [ \@SENDMODE,    'sendmode',    ],
 
1160   [ \@MEDIA,       'media',       ],
 
1161   [ \@PRINTER_ID,  'printer_id',  ];
 
1163   my %dont_display_groupitems = (
 
1167   my %template_vars = (
 
1168     display_copies       => scalar @{ $form->{printers} || [] } && $::lx_office_conf{print_templates}->{latex} && $form->{media} ne 'email',
 
1169     display_remove_draft => (!$form->{id} && $form->{draft_id}),
 
1170     display_groupitems   => !$dont_display_groupitems{$form->{type}},
 
1171     groupitems_checked   => $form->{groupitems} ? "checked" : '',
 
1172     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
 
1175   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
 
1177   if ($options{inline}) {
 
1178     $main::lxdebug->leave_sub();
 
1179     return $print_options;
 
1182   print $print_options;
 
1184   $main::lxdebug->leave_sub();
 
1188   $main::lxdebug->enter_sub();
 
1190   my $form     = $main::form;
 
1191   my $locale   = $main::locale;
 
1195   if ($form->{print_nextsub}) {
 
1196     call_sub($form->{print_nextsub});
 
1197     $main::lxdebug->leave_sub();
 
1201   # if this goes to the printer pass through
 
1203   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
 
1204     $form->error($locale->text('Select postscript or PDF!'))
 
1205       if ($form->{format} !~ /(postscript|pdf)/);
 
1207     $old_form = new Form;
 
1208     map { $old_form->{$_} = $form->{$_} } keys %$form;
 
1211   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
 
1212     if ($form->{formname} eq "proforma") {
 
1213       $form->{proforma} = 1;
 
1215     $form->{print_and_save} = 1;
 
1216     my $formname = $form->{formname};
 
1218     $form->{formname} = $formname;
 
1220     $::lxdebug->leave_sub();
 
1224   &print_form($old_form);
 
1226   $main::lxdebug->leave_sub();
 
1230   $main::lxdebug->enter_sub();
 
1232   my $form     = $main::form;
 
1233   my %myconfig = %main::myconfig;
 
1234   my $locale   = $main::locale;
 
1238   my $defaults = SL::DB::Default->get;
 
1239   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
 
1240   $form->{templates} = $defaults->templates;
 
1242   my ($old_form, %params) = @_;
 
1246   my $numberfld = "invnumber";
 
1250     ($form->{display_form}) ? $form->{display_form} : "display_form";
 
1252   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
 
1253   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
 
1255   if ($form->{formname} eq "invoice") {
 
1256     $form->{label} = $locale->text('Invoice');
 
1258   if ($form->{formname} eq 'sales_order') {
 
1261     $form->{"${inv}date"} = $form->{transdate};
 
1262     $form->{label}        = $locale->text('Confirmation');
 
1263     $numberfld            = "sonumber";
 
1267   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
 
1270     $form->{"${inv}date"} = $form->{invdate};
 
1271     $form->{label}        = $locale->text('Proforma Invoice');
 
1272     $numberfld            = "sonumber";
 
1276   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
 
1279     $form->{"${inv}date"} = $form->{transdate};
 
1280     $form->{"invdate"}    = $form->{transdate};
 
1281     $form->{invnumber}    = $form->{ordnumber};
 
1282     $form->{label}        = $locale->text('Proforma Invoice');
 
1283     $numberfld            = "sonumber";
 
1287   if ($form->{formname} eq 'purchase_order') {
 
1290     $form->{"${inv}date"} = $form->{transdate};
 
1291     $form->{label}        = $locale->text('Purchase Order');
 
1292     $numberfld            = "ponumber";
 
1295   if ($form->{formname} eq 'bin_list') {
 
1298     $form->{"${inv}date"} = $form->{transdate};
 
1299     $form->{label}        = $locale->text('Bin List');
 
1302   if ($form->{formname} eq 'sales_quotation') {
 
1305     $form->{"${inv}date"} = $form->{transdate};
 
1306     $form->{label}        = $locale->text('Quotation');
 
1307     $numberfld            = "sqnumber";
 
1311   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
 
1314     $form->{"${inv}date"} = $form->{transdate};
 
1315     $form->{"invdate"}    = $form->{transdate};
 
1316     $form->{label}        = $locale->text('Proforma Invoice');
 
1317     $numberfld            = "sqnumber";
 
1321   if ($form->{formname} eq 'request_quotation') {
 
1324     $form->{"${inv}date"} = $form->{transdate};
 
1325     $form->{label}        = $locale->text('RFQ');
 
1326     $numberfld            = "rfqnumber";
 
1330   if ($form->{type} =~ /_delivery_order$/) {
 
1333     $form->{"${inv}date"} = $form->{transdate};
 
1334     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
 
1335     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
 
1338   $form->{TEMPLATE_DRIVER_OPTIONS} = { };
 
1339   if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice request_quotation purchase_order purchase_delivery_order)) {
 
1340     $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = {
 
1341       longdescription => 'html',
 
1342       partnotes       => 'html',
 
1346   $form->isblank("email", $locale->text('E-mail address missing!'))
 
1347     if ($form->{media} eq 'email');
 
1348   $form->isblank("${inv}date",
 
1349            $locale->text($form->{label})
 
1351            . $locale->text(' Date missing!'));
 
1353   # $locale->text('Invoice Number missing!')
 
1354   # $locale->text('Invoice Date missing!')
 
1355   # $locale->text('Order Number missing!')
 
1356   # $locale->text('Order Date missing!')
 
1357   # $locale->text('Quotation Number missing!')
 
1358   # $locale->text('Quotation Date missing!')
 
1360   $form->{what_done} = $form->{formname};
 
1364   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
 
1365   my ($saved_email, $saved_cc, $saved_bcc) =
 
1366     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
 
1368   my $language_saved = $form->{language_id};
 
1369   my $payment_id_saved = $form->{payment_id};
 
1370   my $delivery_term_id_saved = $form->{delivery_term_id};
 
1371   my $salesman_id_saved = $form->{salesman_id};
 
1372   my $cp_id_saved = $form->{cp_id};
 
1373   my $taxzone_id_saved = $form->{taxzone_id};
 
1374   my $currency_saved = $form->{currency};
 
1376   call_sub("$form->{vc}_details") if ($form->{vc});
 
1378   $form->{language_id} = $language_saved;
 
1379   $form->{payment_id} = $payment_id_saved;
 
1380   $form->{delivery_term_id} = $delivery_term_id_saved;
 
1381   $form->{taxzone_id} = $taxzone_id_saved;
 
1382   $form->{currency} = $currency_saved;
 
1384   $form->{"email"} = $saved_email if ($saved_email);
 
1385   $form->{"cc"}    = $saved_cc    if ($saved_cc);
 
1386   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
 
1388   if (!$cp_id_saved) {
 
1389     # No contact was selected. Delete all contact variables because
 
1390     # IS->customer_details() and IR->vendor_details() get the default
 
1392     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
 
1395   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
1396   if ($form->{"language_id"}) {
 
1397     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
 
1398       AM->get_language_details(\%myconfig, $form, $form->{language_id});
 
1400     $output_dateformat = $myconfig{"dateformat"};
 
1401     $output_numberformat = $myconfig{"numberformat"};
 
1402     $output_longdates = 1;
 
1405   # Store the output number format so that the template modules know
 
1406   # how to parse the amounts back if requested.
 
1407   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
 
1409   ($form->{employee}) = split /--/, $form->{employee};
 
1411   # create the form variables
 
1412   if ($form->{type} =~ /_delivery_order$/) {
 
1413     DO->order_details(\%myconfig, \%$form);
 
1415     OE->order_details(\%myconfig, \%$form);
 
1417     IS->invoice_details(\%myconfig, \%$form, $locale);
 
1420   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
 
1421   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
 
1423   if ($form->{shipto_id}) {
 
1424     $form->get_shipto(\%myconfig);
 
1427   $form->{notes} =~ s/^\s+//g;
 
1429   delete $form->{printer_command};
 
1431   $form->{language} = $form->get_template_language(\%myconfig);
 
1434   if ($form->{media} ne 'email') {
 
1435     $printer_code = $form->get_printer_code(\%myconfig);
 
1436     if ($printer_code ne "") {
 
1437       $printer_code = "_" . $printer_code;
 
1441   if ($form->{language} ne "") {
 
1442     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
 
1443     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
 
1445     $form->{language} = "_" . $form->{language};
 
1449   format_dates($output_dateformat, $output_longdates,
 
1450                qw(invdate orddate quodate pldate duedate reqdate transdate
 
1451                   shippingdate deliverydate validitydate paymentdate
 
1452                   datepaid transdate_oe deliverydate_oe dodate
 
1453                   employee_startdate employee_enddate
 
1455                grep({ /^datepaid_\d+$/ ||
 
1456                         /^transdate_oe_\d+$/ ||
 
1457                         /^deliverydate_oe_\d+$/ ||
 
1459                         /^deliverydate_\d+$/ ||
 
1463   reformat_numbers($output_numberformat, 2,
 
1464                    qw(invtotal ordtotal quototal subtotal linetotal
 
1465                       listprice sellprice netprice discount
 
1466                       tax taxbase total paid payment),
 
1467                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
 
1469   reformat_numbers($output_numberformat, undef,
 
1470                    qw(qty price_factor),
 
1474   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
1476   if (scalar @{ $cvar_date_fields }) {
 
1477     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
1480   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
1481     reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
1484   my $extension = 'html';
 
1485   if ($form->{format} eq 'postscript') {
 
1486     $form->{postscript}   = 1;
 
1489   } elsif ($form->{"format"} =~ /pdf/) {
 
1491     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
1493   } elsif ($form->{"format"} =~ /opendocument/) {
 
1494     $form->{opendocument} = 1;
 
1496   } elsif ($form->{"format"} =~ /excel/) {
 
1501   # search for the template
 
1502   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
 
1503     name        => $form->{formname},
 
1504     email       => $form->{media} eq 'email',
 
1505     language_id => $form->{language_id},
 
1506     printer_id  => $form->{printer_id},
 
1507     extension   => $extension,
 
1510   if (!defined $template_file) {
 
1511     $::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));
 
1514   $form->{IN} = $template_file;
 
1516   delete $form->{OUT};
 
1518   if ($form->{media} eq 'printer') {
 
1519     $form->{OUT}      = $form->{printer_command};
 
1520     $form->{OUT_MODE} = '|-';
 
1521     $form->{printed} .= " $form->{formname}";
 
1522     $form->{printed}  =~ s/^ //;
 
1524   my $printed = $form->{printed};
 
1526   if ($form->{media} eq 'email') {
 
1527     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
 
1528       unless $form->{subject};
 
1530     $form->{emailed} .= " $form->{formname}";
 
1531     $form->{emailed} =~ s/^ //;
 
1533   my $emailed = $form->{emailed};
 
1535   if ($form->{media} eq 'queue') {
 
1536     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
 
1539     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
 
1540     if ($filename = $queued{ $form->{formname} }) {
 
1541       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
 
1542       delete $queued{ $form->{formname} };
 
1544       $form->{queued}    =  join ' ', %queued;
 
1545       $filename          =~ s/\..*$//g;
 
1546       $filename         .=  $suffix;
 
1547       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
 
1548       $form->{OUT_MODE}  =  '>';
 
1552       ($temp_fh, $filename) = File::Temp::tempfile(
 
1553         'kivitendo-spoolXXXXXX',
 
1554         SUFFIX => "$suffix",
 
1555         DIR    => $::lx_office_conf{paths}->{spool},
 
1559       $form->{OUT} = "$filename";
 
1560       # use >> for OUT_MODE because file is already created by File::Temp
 
1561       $form->{OUT_MODE} = '>>';
 
1562       # strip directory so that only filename is stored in table status
 
1563       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
 
1567     $form->{queued} .= " $form->{formname} $filename";
 
1568     $form->{queued} =~ s/^ //;
 
1570   my $queued = $form->{queued};
 
1572 # saving the history
 
1573   if(!exists $form->{addition}) {
 
1574     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
 
1575     if($form->{media} =~ /printer/) {
 
1576       $form->{addition} = "PRINTED";
 
1578     elsif($form->{media} =~ /email/) {
 
1579       $form->{addition} = "MAILED";
 
1581     elsif($form->{media} =~ /queue/) {
 
1582       $form->{addition} = "QUEUED";
 
1584     elsif($form->{media} =~ /screen/) {
 
1585       $form->{addition} = "SCREENED";
 
1587     $form->save_history;
 
1589   # /saving the history
 
1591   # prepare meta information for template introspection
 
1592   $form->{template_meta} = {
 
1593     formname  => $form->{formname},
 
1594     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
 
1595     format    => $form->{format},
 
1596     media     => $form->{media},
 
1597     extension => $extension,
 
1598     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
 
1599     today     => DateTime->today,
 
1602   $form->parse_template(\%myconfig);
 
1604   $form->{callback} = "";
 
1606   if ($form->{media} eq 'email') {
 
1607     $form->{message} = $locale->text('sent') unless $form->{message};
 
1609   my $message = $form->{message};
 
1611   # if we got back here restore the previous form
 
1612   if ($form->{media} =~ /(printer|email|queue)/) {
 
1614     $form->update_status(\%myconfig)
 
1615       if ($form->{media} eq 'queue' && $form->{id});
 
1617     return $main::lxdebug->leave_sub() if ($old_form eq "return");
 
1621       $old_form->{"${inv}number"} = $form->{"${inv}number"};
 
1623       # restore and display form
 
1624       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
 
1626       $form->{queued}  = $queued;
 
1627       $form->{printed} = $printed;
 
1628       $form->{emailed} = $emailed;
 
1629       $form->{message} = $message;
 
1631       $form->{rowcount}--;
 
1632       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
1633         qw(exchangerate creditlimit creditremaining);
 
1635       for my $i (1 .. $form->{paidaccounts}) {
 
1637           $form->{"${_}_$i"} =
 
1638             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
1639         } qw(paid exchangerate);
 
1642       call_sub($display_form);
 
1647       ($form->{media} eq 'printer')
 
1648       ? $locale->text('sent to printer')
 
1649       : $locale->text('emailed to') . " $form->{email}";
 
1651     if (!$params{no_redirect}) {
 
1652       $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
 
1655   if ($form->{printing}) {
 
1656    call_sub($display_form);
 
1660   $main::lxdebug->leave_sub();
 
1663 sub customer_details {
 
1664   $main::lxdebug->enter_sub();
 
1666   my $form     = $main::form;
 
1667   my %myconfig = %main::myconfig;
 
1669   IS->customer_details(\%myconfig, \%$form, @_);
 
1671   $main::lxdebug->leave_sub();
 
1674 sub vendor_details {
 
1675   $main::lxdebug->enter_sub();
 
1677   my $form     = $main::form;
 
1678   my %myconfig = %main::myconfig;
 
1680   IR->vendor_details(\%myconfig, \%$form, @_);
 
1682   $main::lxdebug->leave_sub();
 
1686   $main::lxdebug->enter_sub();
 
1688   my $form     = $main::form;
 
1692   $form->{postasnew} = 1;
 
1693   map { delete $form->{$_} } qw(printed emailed queued);
 
1697   $main::lxdebug->leave_sub();
 
1701   $main::lxdebug->enter_sub();
 
1705   $::form->{print_and_post} = 0 if $::form->{second_run};
 
1707   map { $::form->{$_} = $::form->parse_amount(\%::myconfig, $::form->{$_}) } qw(exchangerate creditlimit creditremaining);
 
1709   # get details for customer/vendor
 
1710   call_sub($::form->{vc} . "_details", qw(name department_1 department_2 street zipcode city country contact email phone fax), $::form->{vc} . "number");
 
1712   # get pricegroups for parts
 
1713   IS->get_pricegroups_for_parts(\%::myconfig, \%$::form);
 
1715   # build up html code for prices_$i
 
1716   set_pricegroup($::form->{rowcount});
 
1718   $::form->{rowcount}--;
 
1720   my @shipto_vars   = qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
 
1721                          shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail
 
1722                          shiptodepartment_1 shiptodepartment_2);
 
1723   my $previous_form = $::auth->save_form_in_session(skip_keys => [ @shipto_vars, qw(header shipto_id) ]);
 
1724   $::form->{title}  = $::locale->text('Ship to');
 
1727   my $vc_obj = ($::form->{vc} eq 'customer' ? "SL::DB::Customer" : "SL::DB::Vendor")->new(id => $::form->{$::form->{vc} . "_id"})->load;
 
1729   print $::form->parse_html_template('io/ship_to', { previousform => $previous_form,
 
1730                                                      nextsub      => $::form->{display_form} || 'display_form',
 
1734   $main::lxdebug->leave_sub();
 
1737 sub ship_to_entered {
 
1738   $::auth->restore_form_from_session(delete $::form->{previousform});
 
1739   call_sub($::form->{nextsub});
 
1742 sub relink_accounts {
 
1743   $main::lxdebug->enter_sub();
 
1745   my $form     = $main::form;
 
1746   my %myconfig = %main::myconfig;
 
1750   $form->{"taxaccounts"} =~ s/\s*$//;
 
1751   $form->{"taxaccounts"} =~ s/^\s*//;
 
1752   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
 
1753     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
 
1755   $form->{"taxaccounts"} = "";
 
1757   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
 
1759   $main::lxdebug->leave_sub();
 
1763   $main::lxdebug->enter_sub();
 
1765   my $form     = $main::form;
 
1766   my %myconfig = %main::myconfig;
 
1770   my $invdate = $form->{invdate} eq 'undefined' ? undef : $form->{invdate};
 
1771   my $duedate = $form->get_duedate(\%myconfig, $invdate);
 
1773   print $form->ajax_response_header() . ($duedate || $invdate);
 
1775   $main::lxdebug->leave_sub();
 
1778 sub _update_part_information {
 
1779   $main::lxdebug->enter_sub();
 
1781   my $form     = $main::form;
 
1783   my %part_information = IC->get_basic_part_info('id'        => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ],
 
1784                                                  'vendor_id' => $form->{vendor_id});
 
1786   $form->{PART_INFORMATION} = \%part_information;
 
1788   foreach my $i (1..$form->{rowcount}) {
 
1789     next unless ($form->{"id_${i}"});
 
1791     my $info                 = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
 
1792     $form->{"partunit_${i}"} = $info->{unit};
 
1793     $form->{"weight_$i"}     = $info->{weight};
 
1796   $main::lxdebug->leave_sub();
 
1800   $main::lxdebug->enter_sub();
 
1802   my $form     = $main::form;
 
1803   my %myconfig = %main::myconfig;
 
1805   if (!$form->{ordnumber} || !$form->{id}) {
 
1806     map { $form->{"ship_$_"} = 0 } (1..$form->{rowcount});
 
1807     $main::lxdebug->leave_sub();
 
1811   my $all_units = AM->retrieve_all_units();
 
1813   my %ship = DO->get_shipped_qty('type'  => ($form->{type} eq 'purchase_order') ? 'purchase' : 'sales',
 
1814                                  'oe_id' => $form->{id},);
 
1816   foreach my $i (1..$form->{rowcount}) {
 
1817     next unless ($form->{"id_${i}"});
 
1819     $form->{"ship_$i"} = 0;
 
1821     my $ship_entry = $ship{$form->{"id_$i"}};
 
1823     next if (!$ship_entry || ($ship_entry->{qty} <= 0));
 
1826       ($form->{simple_save} ? $form->{"qty_$i"} : $form->parse_amount(\%myconfig, $form->{"qty_$i"}))
 
1827       * $all_units->{$form->{"unit_$i"}}->{factor}
 
1828       / $all_units->{$form->{"partunit_$i"}}->{factor};
 
1830     $form->{"ship_$i"}  = min($rowqty, $ship_entry->{qty});
 
1831     $ship_entry->{qty} -= $form->{"ship_$i"};
 
1834   foreach my $i (1..$form->{rowcount}) {
 
1835     next unless ($form->{"id_${i}"});
 
1837     my $ship_entry = $ship{$form->{"id_$i"}};
 
1839     next if (!$ship_entry || ($ship_entry->{qty} <= 0.01));
 
1841     $form->{"ship_$i"} += $ship_entry->{qty};
 
1842     $ship_entry->{qty}  = 0;
 
1845   $main::lxdebug->leave_sub();
 
1848 sub _update_custom_variables {
 
1849   $main::lxdebug->enter_sub();
 
1851   my $form     = $main::form;
 
1853   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
 
1854   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
 
1856   $main::lxdebug->leave_sub();
 
1859 sub _render_custom_variables_inputs {
 
1860   $main::lxdebug->enter_sub(2);
 
1862   my $form     = $main::form;
 
1866   if (!$form->{CVAR_CONFIGS}->{IC}) {
 
1867     $main::lxdebug->leave_sub();
 
1871   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
 
1873   # get partsgroup_id from part
 
1875   if ($params{part_id}) {
 
1876     $partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id;
 
1879   my $num_visible_cvars = 0;
 
1880   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
 
1881     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
 
1883     # set partsgroup filter
 
1884     my $partsgroup_filtered = 0;
 
1885     if ($cvar->{flag_partsgroup_filter}) {
 
1886       if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) {
 
1887         $partsgroup_filtered = 1;
 
1891     my $hide_non_editable = 1;
 
1894     my $description = '';
 
1895     if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) {
 
1896       $num_visible_cvars++;
 
1897       $description = $cvar->{description} . ' ';
 
1901     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
 
1903     push @{ $params{ROW2} }, {
 
1904       line_break     => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)),
 
1905       description    => $description,
 
1908          hide_non_editable => $hide_non_editable,
 
1910          name_prefix       => 'ic_',
 
1911          name_postfix      => "_$params{row}",
 
1912          valid             => $cvar->{valid},
 
1913          value             => CVar->parse($::form->{$form_key}, $cvar),
 
1914          partsgroup_filtered => $partsgroup_filtered,
 
1919   $main::lxdebug->leave_sub(2);
 
1922 sub _remove_billed_or_delivered_rows {
 
1925   croak "Missing parameter 'quantities'" if !$params{quantities};
 
1927   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
 
1930   my $make_key = sub {
 
1932     return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
 
1933     my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
 
1934     return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
 
1937   my $removed_rows = 0;
 
1939   while ($row < $::form->{rowcount}) {
 
1941     next unless $::form->{"id_$row"};
 
1943     my $parts_id                      = $::form->{"id_$row"};
 
1944     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
 
1946     my $key                           = $make_key->($row);
 
1947     my $sub_qty                       = min($base_qty, $params{quantities}->{$key});
 
1948     $params{quantities}->{$key}      -= $sub_qty;
 
1950     if (!$sub_qty || ($sub_qty != $base_qty)) {
 
1951       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
 
1952       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
 
1959   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
 
1960   $::form->{rowcount} -= $removed_rows;