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);
 
  53 use SL::Helper::CreatePDF;
 
  54 use SL::Helper::Flash;
 
  56 require "bin/mozilla/common.pl";
 
  60 # any custom scripts for this one
 
  61 if (-f "bin/mozilla/custom_io.pl") {
 
  62   eval { require "bin/mozilla/custom_io.pl"; };
 
  64 if (-f "bin/mozilla/$::form->{login}_io.pl") {
 
  65   eval { require "bin/mozilla/$::form->{login}_io.pl"; };
 
  72 # this is for our long dates
 
  73 # $locale->text('January')
 
  74 # $locale->text('February')
 
  75 # $locale->text('March')
 
  76 # $locale->text('April')
 
  77 # $locale->text('May ')
 
  78 # $locale->text('June')
 
  79 # $locale->text('July')
 
  80 # $locale->text('August')
 
  81 # $locale->text('September')
 
  82 # $locale->text('October')
 
  83 # $locale->text('November')
 
  84 # $locale->text('December')
 
  86 # this is for our short month
 
  87 # $locale->text('Jan')
 
  88 # $locale->text('Feb')
 
  89 # $locale->text('Mar')
 
  90 # $locale->text('Apr')
 
  91 # $locale->text('May')
 
  92 # $locale->text('Jun')
 
  93 # $locale->text('Jul')
 
  94 # $locale->text('Aug')
 
  95 # $locale->text('Sep')
 
  96 # $locale->text('Oct')
 
  97 # $locale->text('Nov')
 
  98 # $locale->text('Dec')
 
 105   $main::auth->assert('part_service_assembly_edit   | vendor_invoice_edit       | sales_order_edit    | invoice_edit |' .
 
 106                 'request_quotation_edit       | sales_quotation_edit      | purchase_order_edit | ' .
 
 107                 'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details');
 
 110 ########################################
 
 111 # Eintrag fuer Version 2.2.0 geaendert #
 
 112 # neue Optik im Rechnungsformular      #
 
 113 ########################################
 
 115   $main::lxdebug->enter_sub();
 
 119   my $form     = $main::form;
 
 120   my %myconfig = %main::myconfig;
 
 121   my $locale   = $main::locale;
 
 122   my $cgi      = $::request->{cgi};
 
 126   my ($stock_in_out, $stock_in_out_title);
 
 128   my $defaults = AM->get_defaults();
 
 129   $form->{show_weight} = $defaults->{show_weight};
 
 130   $form->{weightunit} = $defaults->{weightunit};
 
 132   my $is_purchase        = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
 
 133   my $show_min_order_qty =  first { $_ eq $form->{type} } qw(request_quotation purchase_order);
 
 134   my $is_delivery_order  = $form->{type} =~ /_delivery_order$/;
 
 135   my $is_s_p_order       = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
 
 137   if ($is_delivery_order) {
 
 138     if ($form->{type} eq 'sales_delivery_order') {
 
 139       $stock_in_out_title = $locale->text('Release From Stock');
 
 140       $stock_in_out       = 'out';
 
 142       $stock_in_out_title = $locale->text('Transfer To Stock');
 
 143       $stock_in_out       = 'in';
 
 146     retrieve_partunits();
 
 150   my @header_sort = qw(runningnumber partnumber description ship qty unit weight sellprice_pg sellprice discount linetotal);
 
 152     {  id => 'runningnumber', width => 5,     value => $locale->text('No.'),                  display => 1, },
 
 153     {  id => 'partnumber',    width => 8,     value => $locale->text('Number'),               display => 1, },
 
 154     {  id => 'description',   width => 30,    value => $locale->text('Part Description'),     display => 1, },
 
 155     {  id => 'ship',          width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
 
 156     {  id => 'qty',           width => 5,     value => $locale->text('Qty'),                  display => 1, },
 
 157     {  id => 'price_factor',  width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
 
 158     {  id => 'unit',          width => 5,     value => $locale->text('Unit'),                 display => 1, },
 
 159     {  id => 'weight',        width => 5,     value => $locale->text('Weight'),               display => $defaults->{show_weight}, },
 
 160     {  id => 'serialnr',      width => 10,    value => $locale->text('Serial No.'),           display => 0, },
 
 161     {  id => 'projectnr',     width => 10,    value => $locale->text('Project'),              display => 0, },
 
 162     {  id => 'sellprice',     width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
 
 163     {  id => 'sellprice_pg',  width => 8,     value => $locale->text('Pricegroup'),           display => !$is_delivery_order && !$is_purchase, },
 
 164     {  id => 'discount',      width => 5,     value => $locale->text('Discount'),             display => !$is_delivery_order, },
 
 165     {  id => 'linetotal',     width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
 
 166     {  id => 'bin',           width => 10,    value => $locale->text('Bin'),                  display => 0, },
 
 167     {  id => 'stock_in_out',  width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
 
 169   my @column_index = map { $_->{id} } grep { $_->{display} } @HEADER;
 
 173   my $all_units       = AM->retrieve_units(\%myconfig, $form);
 
 175   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 177   my $colspan = scalar @column_index;
 
 179   $form->{invsubtotal} = 0;
 
 180   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
 
 183   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
 
 184   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
 
 187   # translations, unused commented out
 
 188 #  $runningnumber = $locale->text('No.');
 
 189 #  my $deliverydate  = $locale->text('Delivery Date');
 
 190   my $serialnumber  = $locale->text('Serial No.');
 
 191   my $projectnumber = $locale->text('Project');
 
 192 #  $partsgroup    = $locale->text('Group');
 
 193   my $reqdate       = $locale->text('Reqdate');
 
 194   my $deliverydate  = $locale->text('Required by');
 
 197   my %align  = map { $_ => 'right' } qw(qty ship right sellprice_pg discount linetotal stock_in_out weight);
 
 198   my %nowrap = map { $_ => 1 }       qw(description unit);
 
 200   $form->{marge_total}           = 0;
 
 201   $form->{sellprice_total}       = 0;
 
 202   $form->{lastcost_total}        = 0;
 
 203   $form->{totalweight}           = 0;
 
 204   my %projectnumber_labels = ();
 
 205   my @projectnumber_values = ("");
 
 207   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 208     push(@projectnumber_values, $item->{"id"});
 
 209     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
 
 212   _update_part_information();
 
 213   _update_ship() if ($is_s_p_order);
 
 214   _update_custom_variables();
 
 221   for my $i (1 .. $numrows) {
 
 222     my %column_data = ();
 
 225     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
 
 226       qw(qty discount sellprice lastcost price_new price_old)
 
 227         unless ($form->{simple_save});
 
 229     if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
 
 230       $form->{"sellprice_$i"} = $form->{"price_new_$i"};
 
 234     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
 
 235     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
 
 237     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
 238         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
 239       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
 241     # adjust prices by unit, ignore if pricegroup changed
 
 242     if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) {
 
 243         $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 244         $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 245         $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
 
 247     my $this_unit = $form->{"unit_$i"};
 
 248     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
 
 250     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
 
 251       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
 
 252       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
 
 254       $column_data{price_factor} =
 
 255         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
 
 256                              '-default' => $form->{"price_factor_id_$i"},
 
 257                              '-values'  => \@values,
 
 258                              '-labels'  => \%labels,
 
 259                              '-style'   => 'width:90px'));
 
 261       $column_data{price_factor} = ' ';
 
 263     $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
 
 265     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
 
 268 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
 
 269 #is shown for lastcost and sellprice.
 
 270     my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
 
 271     $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
 
 273     my $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
 
 274     my $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
 
 275     my $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
 
 276     my $rows            = $form->numtextrows($form->{"description_$i"}, 30, 6);
 
 278     $column_data{runningnumber} = $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
 
 279     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -id => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
 
 280     $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
 
 281                                 ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
 
 282                                 : $cgi->textfield(-name => "description_$i", -id => "description_$i",   -value => $form->{"description_$i"}, -size => 30))
 
 283                                 . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
 
 285     my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
 
 287     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
 
 288     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_window('qty_$i','alu_$i', 'formel_$i', $i)", -value => $locale->text('*/'))
 
 289                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"}) . $cgi->hidden("-name" => "alu_$i", "-value" => $form->{"alu_$i"})
 
 290       if $form->{"formel_$i"};
 
 292     $column_data{ship} = '';
 
 293     if ($form->{"id_$i"}) {
 
 294       my $ship_qty        = $form->{"ship_$i"} * 1;
 
 295       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
 
 296       $ship_qty          /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
 
 298       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"};
 
 301     # build in drop down list for pricesgroups
 
 302     # $sellprice_value setzt den Wert etwas unabhängiger von der Darstellung.
 
 303     # Hintergrund: Preisgruppen werden hier überprüft und neu berechnet.
 
 304     # Vorher wurde der ganze cgi->textfield Block zweimal identisch eingebaut, dass passiert
 
 305     # jetzt nach der Abfrage.
 
 307     if ($form->{"prices_$i"}) {
 
 308       $column_data{sellprice_pg} = qq|<select name="sellprice_pg_$i" style="width: 8em">$form->{"prices_$i"}</select>|;
 
 309       $sellprice_value           =($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})
 
 310                                       ? $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces)
 
 311                                       : $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 313       # for last row and report
 
 314       # set pricegroup drop down list from report menu
 
 315       if ($form->{"sellprice_$i"} != 0) {
 
 316         # remember the pricegroup_id in pricegroup_old
 
 317         # but don't overwrite it
 
 318         $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"};
 
 319         my $default_option           = $form->{"sellprice_$i"}.'--'.$form->{"pricegroup_id_$i"};
 
 320         $column_data{sellprice_pg}   = NTI($cgi->popup_menu("sellprice_pg_$i", [ $default_option ], $default_option, { $default_option => $form->{"pricegroup_$i"} || '' }));
 
 322         $column_data{sellprice_pg} = qq| |;
 
 324       $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 327     # Falls der Benutzer die Preise nicht anpassen sollte, wird das entsprechende
 
 328     # Textfield auf readonly gesetzt. Anm. von Sven: Manipulation der Preise ist
 
 329     # immer noch möglich, konsequenterweise sollten diese NUR aus der Datenbank
 
 331     my $edit_prices = $main::auth->assert('edit_prices', 1);
 
 332     $column_data{sellprice} = (!$edit_prices)
 
 333                                 ? $cgi->textfield(-readonly => "readonly",
 
 334                                                   -name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value)
 
 335                                 : $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value);
 
 336     $column_data{discount}    = (!$edit_prices)
 
 337                                   ? $cgi->textfield(-readonly => "readonly",
 
 338                                                     -name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}))
 
 339                                   : $cgi->textfield(-name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}));
 
 340     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
 
 341     $column_data{bin}         = $form->{"bin_$i"};
 
 343     $column_data{weight}      = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
 
 345     if ($is_delivery_order) {
 
 346       $column_data{stock_in_out} =  calculate_stock_in_out($i);
 
 349     my @ROW1 = map { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} }, @column_index;
 
 353     push @ROW2, { value => qq|<b>$serialnumber</b> <input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">| }
 
 354       if $form->{type} !~ /_quotation/;
 
 355     push @ROW2, { value => qq|<b>$projectnumber</b> | . NTI($cgi->popup_menu('-name'  => "project_id_$i",        '-values'  => \@projectnumber_values,
 
 356                                                                              '-labels' => \%projectnumber_labels, '-default' => $form->{"project_id_$i"})) };
 
 357     push @ROW2, { value => qq|<b>$reqdate</b> <input name="reqdate_$i" size="11" onBlur="check_right_date_format(this)" value="$form->{"reqdate_$i"}">| }
 
 358       if ($form->{type} =~ /order/ ||  $form->{type} =~ /invoice/);
 
 359     push @ROW2, { value => sprintf qq|<b>%s</b> <input type="checkbox" name="subtotal_$i" value="1" %s>|,
 
 360                    $locale->text('Subtotal'), $form->{"subtotal_$i"} ? 'checked' : '' };
 
 362 # begin marge calculations
 
 363     $form->{"lastcost_$i"}     *= 1;
 
 364     $form->{"marge_percent_$i"} = 0;
 
 368     if ( $form->{taxincluded} and $form->{"qty_$i"} * 1  and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
 
 369       # if we use taxincluded we need to calculate the marge from the net_value
 
 370       # all the marge calculations are based on linetotal which we need to
 
 371       # convert to net first
 
 373       # there is no direct form value for the tax_rate of the item, but
 
 374       # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
 
 375       # gives the tax percentage (e.g. 0.19)
 
 376       $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
 
 378       $real_sellprice            = $linetotal;
 
 380     my $real_lastcost            = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 381     my $marge_percent_warn       = $myconfig{marge_percent_warn} * 1 || 15;
 
 382     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
 
 384     if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
 
 385       $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
 
 386       $marge_color                = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
 
 389     $form->{"marge_absolut_$i"}  = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
 
 390     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
 
 391     $form->{"lastcost_total"}   += $real_lastcost;
 
 392     $form->{"sellprice_total"}  += $real_sellprice;
 
 394     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
 
 396     push @ROW2, { value => sprintf qq|
 
 397          <font %s><b>%s</b> %s  %s%% </font>
 
 399          <b>%s</b> <input size="5" name="lastcost_$i" value="%s">|,
 
 400                    $marge_color, $locale->text('Ertrag'),$form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"},
 
 401                    $locale->text('LP'), $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2),
 
 402                    $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces) }
 
 403       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/ || $form->{type} =~ /^credit_note$/ ) && !$is_delivery_order;
 
 405     $form->{"listprice_$i"} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2)
 
 406       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/) ;
 
 407 # / marge calculations ending
 
 409 # Calculate total weight
 
 410     $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
 
 413     if ($form->{"id_$i"}) {
 
 414       my $part         = IC->get_basic_part_info(id => $form->{"id_$i"});
 
 415       my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
 
 416       push @ROW2, { value => sprintf "<b>%s</b> <font %s>%s %s</font>",
 
 417                       $locale->text('On Hand'),
 
 419                       $form->format_amount(\%myconfig, $part->{onhand}, 2),
 
 427     if ($is_delivery_order) {
 
 428       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
 
 429       $form->{"pricegroup_id_$i"} = $form->{"pricegroup_old_$i"} if $form->{"pricegroup_old_$i"};
 
 430       $form->{"sellprice_pg_$i"}  = $form->{"hidden_prices_$i"}  if $form->{"hidden_prices_$i"};
 
 431       push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost pricegroup_id sellprice_pg);
 
 432       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
 
 435     my @HIDDENS = map { value => $_}, (
 
 436           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
 
 437           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
 
 438           map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
 
 439             (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes
 
 440                 income_accno expense_accno listprice assembly taxaccounts ordnumber donumber transdate cusordnumber
 
 441                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
 
 444     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
 
 446     $form->{invsubtotal} += $linetotal;
 
 448     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
 
 449     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
 
 451     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, };
 
 454   $form->{totalweight} = $totalweight;
 
 456   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
 
 460   if (0 != ($form->{sellprice_total} * 1)) {
 
 461     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
 
 464   $main::lxdebug->leave_sub();
 
 467 ##################################################
 
 468 # build html-code for pricegroups in variable $form->{prices_$j}
 
 471   $main::lxdebug->enter_sub();
 
 473   my $form     = $main::form;
 
 474   my $locale   = $main::locale;
 
 475   my $cgi      = $::request->{cgi};
 
 479   my $rowcount = shift;
 
 480   for my $j (1 .. $rowcount) {
 
 481     next unless $form->{PRICES}{$j};
 
 482     # build drop down list for pricegroups
 
 483     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
 
 484     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} }
 
 485                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
 
 487     foreach my $item (@{ $form->{PRICES}{$j} }) {
 
 488       # set new selectedpricegroup_id and prices for "Preis"
 
 489       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
 
 490       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
 
 491       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
 
 494     # save hidden pricegroups for delivery_orders
 
 495     next unless my @selected_prices = grep { $_->{selected} } @{ $form->{PRICES}{$j} };
 
 496     $form->{"hidden_prices_$j"} = $selected_prices[-1]{price} . "--" . $selected_prices[-1]{pricegroup_id};
 
 498   $main::lxdebug->leave_sub();
 
 502   $main::lxdebug->enter_sub();
 
 505   my $mode   = $params{mode} || croak "Missing parameter 'mode'";
 
 509   my $previous_form = $::auth->save_form_in_session(form => $::form);
 
 510   $::form->{title}  = $::locale->text('Select from one of the items below');
 
 513   my @item_list = map {
 
 514     $_->{display_sellprice}  = $_->{sellprice} * (1 - $::form->{tradediscount});
 
 515     $_->{display_sellprice} /= $_->{price_factor} if ($_->{price_factor});
 
 517   } @{ $::form->{item_list} };
 
 519   # delete action variable
 
 520   delete @{$::form}{qw(action item_list)};
 
 522   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
 
 524                                                          ITEM_LIST     => \@item_list,
 
 525                                                          IS_PURCHASE   => $mode eq 'IS' });
 
 527   $main::lxdebug->leave_sub();
 
 531   $main::lxdebug->enter_sub();
 
 533   my $form     = $main::form;
 
 534   my %myconfig = %main::myconfig;
 
 538   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
 
 540   my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
 
 541   my $id   = delete($form->{select_item_id})   || croak 'Missing item selection ID';
 
 542   my $i    = $form->{ $mode eq 'IC' ? 'assembly_rows' : 'rowcount' };
 
 544   $form->{"id_${i}"} = $id;
 
 547     IS->retrieve_item(\%myconfig, \%$form);
 
 548   } elsif ($mode eq 'IR') {
 
 549     IR->retrieve_item(\%myconfig, \%$form);
 
 550   } elsif ($mode eq 'IC') {
 
 551     IC->assembly_item(\%myconfig, \%$form);
 
 553     croak "Invalid item selection mode '${mode}'";
 
 556   my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
 
 558   # if there was a price entered, override it
 
 559   my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 562     qw(id partnumber description sellprice listprice inventory_accno
 
 563        income_accno expense_accno bin unit weight assembly taxaccounts
 
 564        partsgroup formel longdescription not_discountable partnotes lastcost
 
 565        price_factor_id price_factor);
 
 567   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 568   push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 570   map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
 
 572   $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
 
 574   if ($form->{"part_payment_id_$i"} ne "") {
 
 575     $form->{payment_id} = $form->{"part_payment_id_$i"};
 
 578   my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 580   my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 583     $form->{"sellprice_$i"} = $sellprice;
 
 586     # if there is an exchange rate adjust sellprice
 
 587     if (($form->{exchangerate} * 1) != 0) {
 
 588       $form->{"sellprice_$i"} /= $form->{exchangerate};
 
 589       $form->{"sellprice_$i"} =
 
 590         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
 
 594     if ($::form->{tradediscount}) {
 
 595       $::form->{"sellprice_$i"} *= 1 - $::form->{tradediscount};
 
 599   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 600     qw(sellprice listprice weight);
 
 602   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
 
 604   if ($form->{"not_discountable_$i"}) {
 
 605     $form->{"discount_$i"} = 0;
 
 609     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
 
 611   map { $form->{"${_}_base"} += $amount }
 
 612     (split / /, $form->{"taxaccounts_$i"});
 
 613   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
 
 614     $form->{"taxaccounts_$i"}
 
 615     if !$form->{taxincluded};
 
 617   $form->{creditremaining} -= $amount;
 
 619   $form->{"runningnumber_$i"} = $i;
 
 621   delete $form->{nextsub};
 
 626       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
 
 627   } qw(sellprice listprice lastcost) if $form->{item} ne 'assembly';
 
 629   # get pricegroups for parts
 
 630   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 632   # build up html code for prices_$i
 
 633   set_pricegroup($form->{rowcount});
 
 637   $main::lxdebug->leave_sub();
 
 641   $main::lxdebug->enter_sub();
 
 643   my $form     = $main::form;
 
 644   my %myconfig = %main::myconfig;
 
 648   my $price_key = ($form->{type} =~ m/request_quotation|purchase_order/) || ($form->{script} eq 'ir.pl') ? 'lastcost' : 'sellprice';
 
 651   $form->{old_callback} = $form->escape($form->{callback}, 1);
 
 652   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
 
 654   # save all form variables except action in the session and keep the key in the previousform variable
 
 655   my $previousform = $::auth->save_form_in_session(skip_keys => [ qw(action) ]);
 
 658   push @HIDDENS,      { 'name' => 'previousform', 'value' => $previousform };
 
 659   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc);
 
 660   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit);
 
 661   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
 
 662   push @HIDDENS,      { 'name' => $price_key,     'value' => $form->parse_amount(\%myconfig, $form->{"sellprice_$form->{rowcount}"}) };
 
 663   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{"longdescription_$form->{rowcount}"} };
 
 666   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
 
 668   $main::lxdebug->leave_sub();
 
 672   $main::lxdebug->enter_sub();
 
 674   my $form     = $main::form;
 
 675   my %myconfig = %main::myconfig;
 
 682   # remove any makes or model rows
 
 683   if ($form->{item} eq 'assembly') {
 
 685     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
 
 686     #$form->{sellprice} = 0;
 
 688     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 689       qw(listprice sellprice rop stock);
 
 691     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
 
 693     for my $i (1 .. ($form->{assembly_rows} - 1)) {
 
 694       if ($form->{"qty_$i"}) {
 
 698         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 700         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 702         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 704         # fuer assemblies auskommentiert. siehe oben
 
 705         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
 
 706         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
 
 710     # kann das hier auch weg? s.o. jb
 
 711     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
 
 713     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
 
 714     $form->{assembly_rows} = $count;
 
 716   } elsif ($form->{item} !~ m{^(?:part|service)$}) {
 
 717     remove_emptied_rows(1);
 
 719     $form->{creditremaining} -= &invoicetotal;
 
 724   if (   $form->{type} =~ (/sales_quotation/)
 
 725       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
 
 726       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
 
 727       or ($form->{type} =~ /sales_order/)) {
 
 729     # get pricegroups for parts
 
 730     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 732     # build up html code for prices_$i
 
 733     set_pricegroup($form->{rowcount});
 
 739   $main::lxdebug->leave_sub();
 
 742 sub remove_emptied_rows {
 
 743   my $dont_add_empty = shift;
 
 746   return unless $form->{rowcount};
 
 748   my @flds = qw(id partnumber description qty ship sellprice unit
 
 749                 discount inventory_accno income_accno expense_accno listprice
 
 750                 taxaccounts bin assembly weight projectnumber project_id
 
 751                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
 
 752                 not_discountable shop ve gv buchungsgruppen_id language_values
 
 753                 sellprice_pg pricegroup_old price_old price_new unit_old ordnumber donumber
 
 754                 transdate longdescription basefactor marge_total marge_percent
 
 755                 marge_price_factor lastcost price_factor_id partnotes
 
 756                 stock_out stock_in has_sernumber reqdate);
 
 758   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 759   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 762   for my $i (1 .. $form->{rowcount} - 1) {
 
 763     next unless $form->{"partnumber_$i"};
 
 765     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
 
 768   my $new_rowcount = scalar @new_rows;
 
 769   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
 
 770   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
 
 774   $main::lxdebug->enter_sub();
 
 776   my $form     = $main::form;
 
 777   my %myconfig = %main::myconfig;
 
 781   $form->{oldinvtotal} = 0;
 
 783   # add all parts and deduct paid
 
 784   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
 
 786   my ($amount, $sellprice, $discount, $qty);
 
 788   for my $i (1 .. $form->{rowcount}) {
 
 789     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 790     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
 
 791     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 793     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 795     $amount = $sellprice * (1 - $discount / 100) * $qty;
 
 796     map { $form->{"${_}_base"} += $amount }
 
 797       (split (/ /, $form->{"taxaccounts_$i"}));
 
 798     $form->{oldinvtotal} += $amount;
 
 801   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
 
 802     split(/ /, $form->{taxaccounts})
 
 803     if !$form->{taxincluded};
 
 805   $form->{oldtotalpaid} = 0;
 
 806   for my $i (1 .. $form->{paidaccounts}) {
 
 807     $form->{oldtotalpaid} += $form->{"paid_$i"};
 
 810   $main::lxdebug->leave_sub();
 
 813   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 817   $main::lxdebug->enter_sub();
 
 819   my $form     = $main::form;
 
 820   my $locale   = $main::locale;
 
 824   # check if items are valid
 
 825   if ($form->{rowcount} == 1) {
 
 826     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
 
 831   for my $i (1 .. $form->{rowcount} - 1) {
 
 832     $form->isblank("partnumber_$i",
 
 833                    $locale->text('Number missing in Row') . " $i");
 
 836   $main::lxdebug->leave_sub();
 
 840   $main::lxdebug->enter_sub();
 
 842   my $form     = $main::form;
 
 843   my %myconfig = %main::myconfig;
 
 844   my $locale   = $main::locale;
 
 848   if ($form->{second_run}) {
 
 849     $form->{print_and_post} = 0;
 
 851   $form->{ordnumber} = $form->{invnumber};
 
 853   $form->{old_employee_id} = $form->{employee_id};
 
 854   $form->{old_salesman_id} = $form->{salesman_id};
 
 856   map { delete $form->{$_} } qw(id printed emailed queued);
 
 858   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
 
 859     $form->{title} = $locale->text('Add Purchase Order');
 
 860     $form->{vc}    = 'vendor';
 
 861     $form->{type}  = 'purchase_order';
 
 864   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
 
 865     $form->{title} = $locale->text('Add Sales Order');
 
 866     $form->{vc}    = 'customer';
 
 867     $form->{type}  = 'sales_order';
 
 870   $form->{script} = 'oe.pl';
 
 878   require "bin/mozilla/$form->{script}";
 
 879   my $script = $form->{"script"};
 
 882   $locale = new Locale($::lx_office_conf{system}->{language}, $script);
 
 884   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
 886   my $currency = $form->{currency};
 
 890   $form->{currency}     = $currency;
 
 891   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
 892   $form->{exchangerate} = $form->{forex} || '';
 
 894   for my $i (1 .. $form->{rowcount}) {
 
 895     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
 
 896             if ($form->{"${_}_${i}"}) }
 
 897         qw(ship qty sellprice listprice basefactor discount));
 
 903   $main::lxdebug->leave_sub();
 
 907   $main::lxdebug->enter_sub();
 
 909   my $form     = $main::form;
 
 910   my %myconfig = %main::myconfig;
 
 911   my $locale   = $main::locale;
 
 915   if ($form->{second_run}) {
 
 916     $form->{print_and_post} = 0;
 
 918   map { delete $form->{$_} } qw(id printed emailed queued);
 
 921   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
 
 922     $form->{title} = $locale->text('Add Request for Quotation');
 
 923     $form->{vc}    = 'vendor';
 
 924     $form->{type}  = 'request_quotation';
 
 927   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
 
 928     $form->{title} = $locale->text('Add Quotation');
 
 929     $form->{vc}    = 'customer';
 
 930     $form->{type}  = 'sales_quotation';
 
 936   $form->{script} = 'oe.pl';
 
 942   require "bin/mozilla/$form->{script}";
 
 944   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
 946   my $currency = $form->{currency};
 
 950   $form->{currency}     = $currency;
 
 951   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
 952   $form->{exchangerate} = $form->{forex} || '';
 
 954   for my $i (1 .. $form->{rowcount}) {
 
 955     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
 
 956                                                      $form->{"${_}_${i}"})
 
 957             if ($form->{"${_}_${i}"}) }
 
 958         qw(ship qty sellprice listprice basefactor discount lastcost));
 
 964   $main::lxdebug->leave_sub();
 
 967 sub request_for_quotation {
 
 972   $main::lxdebug->enter_sub();
 
 974   my $form     = $main::form;
 
 975   my %myconfig = %main::myconfig;
 
 976   my $locale   = $main::locale;
 
 980   if ($form->{second_run}) {
 
 981     $form->{print_and_post} = 0;
 
 982     $form->{resubmit}       = 0;
 
 985   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
 
 987   if ($form->{"cp_id"}) {
 
 988     CT->get_contact(\%myconfig, $form);
 
 989     $form->{"email"} = $form->{"cp_email"} if $form->{"cp_email"};
 
 992   $form->{language} = $form->get_template_language(\%myconfig);
 
 993   $form->{language} = "_" . $form->{language} if $form->{language};
 
 995   my $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
 
 997   $form->{oldmedia} = $form->{media};
 
 998   $form->{media}    = "email";
 
1000   my $attachment_filename = $form->generate_attachment_filename();
 
1001   my $subject             = $form->{subject} || $form->generate_email_subject();
 
1005   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
 
1006   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override login password);
 
1007   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
 
1008   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
 
1010   print $form->parse_html_template('generic/edit_email',
 
1012                                      a_filename    => $attachment_filename,
 
1013                                      subject       => $subject,
 
1014                                      print_options => print_options('inline' => 1),
 
1015                                      HIDDEN        => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
 
1016                                      SHOW_BCC      => $::auth->assert('email_bcc', 'may fail') });
 
1018   $main::lxdebug->leave_sub();
 
1022   $main::lxdebug->enter_sub();
 
1024   my $form     = $main::form;
 
1025   my %myconfig = %main::myconfig;
 
1029   my $callback = $form->{script} . "?action=edit";
 
1030   map({ $callback .= "\&${_}=" . E($form->{$_}); } qw(type id));
 
1032   print_form("return");
 
1034   Common->save_email_status(\%myconfig, $form);
 
1036   $form->{callback} = $callback;
 
1039   $main::lxdebug->leave_sub();
 
1042 # generate the printing options displayed at the bottom of oe and is forms.
 
1043 # this function will attempt to guess what type of form is displayed, and will generate according options
 
1046 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
 
1047 # the opthash function builds hashrefs which are then pieced together for the template arrays.
 
1048 # unneeded options are "undef"ed out, and then grepped out.
 
1050 # the inline options is untested, but intended to be used later in metatemplating
 
1052   $main::lxdebug->enter_sub();
 
1054   my $form     = $main::form;
 
1055   my %myconfig = %main::myconfig;
 
1056   my $locale   = $main::locale;
 
1062   # names 3 parameters and returns a hashref, for use in templates
 
1063   sub opthash { +{ value => shift, selected => shift, oname => shift } }
 
1064   my (@FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
 
1066   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
 
1067   $form->{sendmode}   = "attachment";
 
1068   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
 
1069   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
 
1070   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
 
1071   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
 
1072                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
 
1074   $form->{PD}{ $form->{formname} } = "selected";
 
1075   $form->{DF}{ $form->{format} }   = "selected";
 
1076   $form->{OP}{ $form->{media} }    = "selected";
 
1077   $form->{SM}{ $form->{formname} } = "selected";
 
1079   push @FORMNAME, grep $_,
 
1080     ($form->{type} eq 'purchase_order') ? (
 
1081       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
 
1082       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List'))
 
1084     ($form->{type} eq 'credit_note') ?
 
1085       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
 
1086     ($form->{type} eq 'sales_order') ? (
 
1087       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
 
1088       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
 
1090     ($form->{type} =~ /sales_quotation$/) ?
 
1091       opthash('sales_quotation',     $form->{PD}{sales_quotation},     $locale->text('Quotation')) : undef,
 
1092     ($form->{type} =~ /request_quotation$/) ?
 
1093       opthash('request_quotation',   $form->{PD}{request_quotation},   $locale->text('Request for Quotation')) : undef,
 
1094     ($form->{type} eq 'invoice') ? (
 
1095       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
 
1096       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
 
1098     ($form->{type} eq 'invoice' && $form->{storno}) ? (
 
1099       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
 
1101     ($form->{type} =~ /_delivery_order$/) ? (
 
1102       opthash($form->{type},         $form->{PD}{$form->{type}},       $locale->text('Delivery Order')),
 
1103       opthash('pick_list',           $form->{PD}{pick_list},           $locale->text('Pick List')),
 
1107     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
 
1108     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
 
1109       if ($form->{media} eq 'email');
 
1111   my $printable_templates = any { $::lx_office_conf{print_templates}->{$_} } qw(latex opendocument);
 
1112   push @MEDIA, grep $_,
 
1113       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
 
1114     ($printable_templates && $form->{printers} && scalar @{ $form->{printers} }) ?
 
1115       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
 
1116     ($printable_templates && !$options{no_queue}) ?
 
1117       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
 
1118         if ($form->{media} ne 'email');
 
1120   push @FORMAT, grep $_,
 
1121     ($::lx_office_conf{print_templates}->{opendocument} &&     $::lx_office_conf{applications}->{openofficeorg_writer}  &&     $::lx_office_conf{applications}->{xvfb}
 
1122                                                         && (-x $::lx_office_conf{applications}->{openofficeorg_writer}) && (-x $::lx_office_conf{applications}->{xvfb})
 
1123      && !$options{no_opendocument_pdf}) ?
 
1124       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
 
1125     ($::lx_office_conf{print_templates}->{latex}) ?
 
1126       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
 
1127     ($::lx_office_conf{print_templates}->{latex} && !$options{no_postscript}) ?
 
1128       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
 
1129     (!$options{no_html}) ?
 
1130       opthash("html", $form->{DF}{html}, "HTML") : undef,
 
1131     ($::lx_office_conf{print_templates}->{opendocument} && !$options{no_opendocument}) ?
 
1132       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef,
 
1133     ($::lx_office_conf{print_templates}->{excel} && !$options{no_excel}) ?
 
1134       opthash("excel",               $form->{DF}{excel},               $locale->text("Excel")) : undef;
 
1137     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
 
1138       if (ref $form->{languages} eq 'ARRAY');
 
1141     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
 
1142       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
 
1147     show  => !$options{"hide_" . $_->[1]} && scalar @{ $_->[0] }
 
1149   [ \@FORMNAME,    'formname',    ],
 
1150   [ \@LANGUAGE_ID, 'language_id', ],
 
1151   [ \@FORMAT,      'format',      ],
 
1152   [ \@SENDMODE,    'sendmode',    ],
 
1153   [ \@MEDIA,       'media',       ],
 
1154   [ \@PRINTER_ID,  'printer_id',  ];
 
1156   my %dont_display_groupitems = (
 
1160   my %template_vars = (
 
1161     display_copies       => scalar @{ $form->{printers} || [] } && $::lx_office_conf{print_templates}->{latex} && $form->{media} ne 'email',
 
1162     display_remove_draft => (!$form->{id} && $form->{draft_id}),
 
1163     display_groupitems   => !$dont_display_groupitems{$form->{type}},
 
1164     groupitems_checked   => $form->{groupitems} ? "checked" : '',
 
1165     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
 
1168   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
 
1170   if ($options{inline}) {
 
1171     $main::lxdebug->leave_sub();
 
1172     return $print_options;
 
1175   print $print_options;
 
1177   $main::lxdebug->leave_sub();
 
1181   $main::lxdebug->enter_sub();
 
1183   my $form     = $main::form;
 
1184   my $locale   = $main::locale;
 
1188   if ($form->{print_nextsub}) {
 
1189     call_sub($form->{print_nextsub});
 
1190     $main::lxdebug->leave_sub();
 
1194   # if this goes to the printer pass through
 
1196   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
 
1197     $form->error($locale->text('Select postscript or PDF!'))
 
1198       if ($form->{format} !~ /(postscript|pdf)/);
 
1200     $old_form = new Form;
 
1201     map { $old_form->{$_} = $form->{$_} } keys %$form;
 
1204   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
 
1205     if ($form->{formname} eq "proforma") {
 
1206       $form->{proforma} = 1;
 
1208     $form->{print_and_save} = 1;
 
1209     my $formname = $form->{formname};
 
1211     $form->{formname} = $formname;
 
1213     $::lxdebug->leave_sub();
 
1217   &print_form($old_form);
 
1219   $main::lxdebug->leave_sub();
 
1223   $main::lxdebug->enter_sub();
 
1225   my $form     = $main::form;
 
1226   my %myconfig = %main::myconfig;
 
1227   my $locale   = $main::locale;
 
1231   my $defaults = SL::DB::Default->get;
 
1232   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
 
1233   $form->{templates} = $defaults->templates;
 
1235   my ($old_form) = @_;
 
1239   my $numberfld = "invnumber";
 
1243     ($form->{display_form}) ? $form->{display_form} : "display_form";
 
1245   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
 
1246   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
 
1248   if ($form->{formname} eq "invoice") {
 
1249     $form->{label} = $locale->text('Invoice');
 
1251   if ($form->{formname} eq 'sales_order') {
 
1254     $form->{"${inv}date"} = $form->{transdate};
 
1255     $form->{label}        = $locale->text('Confirmation');
 
1256     $numberfld            = "sonumber";
 
1260   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
 
1263     $form->{"${inv}date"} = $form->{invdate};
 
1264     $form->{label}        = $locale->text('Proforma Invoice');
 
1265     $numberfld            = "sonumber";
 
1269   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
 
1272     $form->{"${inv}date"} = $form->{transdate};
 
1273     $form->{"invdate"}    = $form->{transdate};
 
1274     $form->{invnumber}    = $form->{ordnumber};
 
1275     $form->{label}        = $locale->text('Proforma Invoice');
 
1276     $numberfld            = "sonumber";
 
1280   if ($form->{formname} eq 'purchase_order') {
 
1283     $form->{"${inv}date"} = $form->{transdate};
 
1284     $form->{label}        = $locale->text('Purchase Order');
 
1285     $numberfld            = "ponumber";
 
1288   if ($form->{formname} eq 'bin_list') {
 
1291     $form->{"${inv}date"} = $form->{transdate};
 
1292     $form->{label}        = $locale->text('Bin List');
 
1295   if ($form->{formname} eq 'sales_quotation') {
 
1298     $form->{"${inv}date"} = $form->{transdate};
 
1299     $form->{label}        = $locale->text('Quotation');
 
1300     $numberfld            = "sqnumber";
 
1304   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
 
1307     $form->{"${inv}date"} = $form->{transdate};
 
1308     $form->{"invdate"}    = $form->{transdate};
 
1309     $form->{label}        = $locale->text('Proforma Invoice');
 
1310     $numberfld            = "sqnumber";
 
1314   if ($form->{formname} eq 'request_quotation') {
 
1317     $form->{"${inv}date"} = $form->{transdate};
 
1318     $form->{label}        = $locale->text('RFQ');
 
1319     $numberfld            = "rfqnumber";
 
1323   if ($form->{type} =~ /_delivery_order$/) {
 
1326     $form->{"${inv}date"} = $form->{transdate};
 
1327     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
 
1328     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
 
1331   $form->isblank("email", $locale->text('E-mail address missing!'))
 
1332     if ($form->{media} eq 'email');
 
1333   $form->isblank("${inv}date",
 
1334            $locale->text($form->{label})
 
1336            . $locale->text(' Date missing!'));
 
1338   # $locale->text('Invoice Number missing!')
 
1339   # $locale->text('Invoice Date missing!')
 
1340   # $locale->text('Order Number missing!')
 
1341   # $locale->text('Order Date missing!')
 
1342   # $locale->text('Quotation Number missing!')
 
1343   # $locale->text('Quotation Date missing!')
 
1345   $form->{what_done} = $form->{formname};
 
1349   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
 
1350   my ($saved_email, $saved_cc, $saved_bcc) =
 
1351     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
 
1353   my $language_saved = $form->{language_id};
 
1354   my $payment_id_saved = $form->{payment_id};
 
1355   my $delivery_term_id_saved = $form->{delivery_term_id};
 
1356   my $salesman_id_saved = $form->{salesman_id};
 
1357   my $cp_id_saved = $form->{cp_id};
 
1358   my $taxzone_id_saved = $form->{taxzone_id};
 
1359   my $currency_saved = $form->{currency};
 
1361   call_sub("$form->{vc}_details") if ($form->{vc});
 
1363   $form->{language_id} = $language_saved;
 
1364   $form->{payment_id} = $payment_id_saved;
 
1365   $form->{delivery_term_id} = $delivery_term_id_saved;
 
1366   $form->{taxzone_id} = $taxzone_id_saved;
 
1367   $form->{currency} = $currency_saved;
 
1369   $form->{"email"} = $saved_email if ($saved_email);
 
1370   $form->{"cc"}    = $saved_cc    if ($saved_cc);
 
1371   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
 
1373   if (!$cp_id_saved) {
 
1374     # No contact was selected. Delete all contact variables because
 
1375     # IS->customer_details() and IR->vendor_details() get the default
 
1377     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
 
1380   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
1381   if ($form->{"language_id"}) {
 
1382     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
 
1383       AM->get_language_details(\%myconfig, $form, $form->{language_id});
 
1385     $output_dateformat = $myconfig{"dateformat"};
 
1386     $output_numberformat = $myconfig{"numberformat"};
 
1387     $output_longdates = 1;
 
1390   # Store the output number format so that the template modules know
 
1391   # how to parse the amounts back if requested.
 
1392   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
 
1394   ($form->{employee}) = split /--/, $form->{employee};
 
1396   # create the form variables
 
1397   if ($form->{type} =~ /_delivery_order$/) {
 
1398     DO->order_details(\%myconfig, \%$form);
 
1400     OE->order_details(\%myconfig, \%$form);
 
1402     IS->invoice_details(\%myconfig, \%$form, $locale);
 
1405   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
 
1406   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
 
1408   if ($form->{shipto_id}) {
 
1409     $form->get_shipto(\%myconfig);
 
1412   my @a = qw(name department_1 department_2 street zipcode city country contact phone fax email);
 
1416   # if there is no shipto fill it in from billto
 
1417   foreach my $item (@a) {
 
1418     if ($form->{"shipto$item"}) {
 
1425     if (   $form->{formname} eq 'purchase_order'
 
1426         || $form->{formname} eq 'request_quotation') {
 
1427       $form->{shiptoname}   = $defaults->company;
 
1428       $form->{shiptostreet} = $defaults->address;
 
1430       map { $form->{"shipto$_"} = $form->{$_} } @a;
 
1434   $form->{notes} =~ s/^\s+//g;
 
1436   delete $form->{printer_command};
 
1438   $form->{language} = $form->get_template_language(\%myconfig);
 
1441   if ($form->{media} ne 'email') {
 
1442     $printer_code = $form->get_printer_code(\%myconfig);
 
1443     if ($printer_code ne "") {
 
1444       $printer_code = "_" . $printer_code;
 
1448   if ($form->{language} ne "") {
 
1449     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
 
1450     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
 
1452     $form->{language} = "_" . $form->{language};
 
1456   format_dates($output_dateformat, $output_longdates,
 
1457                qw(invdate orddate quodate pldate duedate reqdate transdate
 
1458                   shippingdate deliverydate validitydate paymentdate
 
1459                   datepaid transdate_oe deliverydate_oe dodate
 
1460                   employee_startdate employee_enddate
 
1462                grep({ /^datepaid_\d+$/ ||
 
1463                         /^transdate_oe_\d+$/ ||
 
1464                         /^deliverydate_oe_\d+$/ ||
 
1466                         /^deliverydate_\d+$/ ||
 
1470   reformat_numbers($output_numberformat, 2,
 
1471                    qw(invtotal ordtotal quototal subtotal linetotal
 
1472                       listprice sellprice netprice discount
 
1473                       tax taxbase total paid payment),
 
1474                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
 
1476   reformat_numbers($output_numberformat, undef,
 
1477                    qw(qty price_factor),
 
1481   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
1483   if (scalar @{ $cvar_date_fields }) {
 
1484     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
1487   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
1488     reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
1491   my $extension = 'html';
 
1492   if ($form->{format} eq 'postscript') {
 
1493     $form->{postscript}   = 1;
 
1496   } elsif ($form->{"format"} =~ /pdf/) {
 
1498     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
1500   } elsif ($form->{"format"} =~ /opendocument/) {
 
1501     $form->{opendocument} = 1;
 
1503   } elsif ($form->{"format"} =~ /excel/) {
 
1508   # search for the template
 
1509   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
 
1510     name        => $form->{formname},
 
1511     email       => $form->{media} eq 'email',
 
1512     language_id => $form->{language_id},
 
1513     printer_id  => $form->{printer_id},
 
1514     extension   => $extension,
 
1517   if (!defined $template_file) {
 
1518     $::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));
 
1521   $form->{IN} = $template_file;
 
1523   delete $form->{OUT};
 
1525   if ($form->{media} eq 'printer') {
 
1526     $form->{OUT}      = $form->{printer_command};
 
1527     $form->{OUT_MODE} = '|-';
 
1528     $form->{printed} .= " $form->{formname}";
 
1529     $form->{printed}  =~ s/^ //;
 
1531   my $printed = $form->{printed};
 
1533   if ($form->{media} eq 'email') {
 
1534     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
 
1535       unless $form->{subject};
 
1537     $form->{emailed} .= " $form->{formname}";
 
1538     $form->{emailed} =~ s/^ //;
 
1540   my $emailed = $form->{emailed};
 
1542   if ($form->{media} eq 'queue') {
 
1543     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
 
1546     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
 
1547     if ($filename = $queued{ $form->{formname} }) {
 
1548       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
 
1549       delete $queued{ $form->{formname} };
 
1551       $form->{queued}    =  join ' ', %queued;
 
1552       $filename          =~ s/\..*$//g;
 
1553       $filename         .=  $suffix;
 
1554       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
 
1555       $form->{OUT_MODE}  =  '>';
 
1559       ($temp_fh, $filename) = File::Temp::tempfile(
 
1560         'kivitendo-spoolXXXXXX',
 
1561         SUFFIX => "$suffix",
 
1562         DIR    => $::lx_office_conf{paths}->{spool},
 
1566       $form->{OUT} = "$filename";
 
1567       # use >> for OUT_MODE because file is already created by File::Temp
 
1568       $form->{OUT_MODE} = '>>';
 
1569       # strip directory so that only filename is stored in table status
 
1570       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
 
1574     $form->{queued} .= " $form->{formname} $filename";
 
1575     $form->{queued} =~ s/^ //;
 
1577   my $queued = $form->{queued};
 
1579 # saving the history
 
1580   if(!exists $form->{addition}) {
 
1581     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
 
1582     if($form->{media} =~ /printer/) {
 
1583       $form->{addition} = "PRINTED";
 
1585     elsif($form->{media} =~ /email/) {
 
1586       $form->{addition} = "MAILED";
 
1588     elsif($form->{media} =~ /queue/) {
 
1589       $form->{addition} = "QUEUED";
 
1591     elsif($form->{media} =~ /screen/) {
 
1592       $form->{addition} = "SCREENED";
 
1594     $form->save_history;
 
1596   # /saving the history
 
1598   # prepare meta information for template introspection
 
1599   $form->{template_meta} = {
 
1600     formname  => $form->{formname},
 
1601     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
 
1602     format    => $form->{format},
 
1603     media     => $form->{media},
 
1604     extension => $extension,
 
1605     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
 
1606     today     => DateTime->today,
 
1609   $form->parse_template(\%myconfig);
 
1611   $form->{callback} = "";
 
1613   if ($form->{media} eq 'email') {
 
1614     $form->{message} = $locale->text('sent') unless $form->{message};
 
1616   my $message = $form->{message};
 
1618   # if we got back here restore the previous form
 
1619   if ($form->{media} =~ /(printer|email|queue)/) {
 
1621     $form->update_status(\%myconfig)
 
1622       if ($form->{media} eq 'queue' && $form->{id});
 
1624     return $main::lxdebug->leave_sub() if ($old_form eq "return");
 
1628       $old_form->{"${inv}number"} = $form->{"${inv}number"};
 
1630       # restore and display form
 
1631       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
 
1633       $form->{queued}  = $queued;
 
1634       $form->{printed} = $printed;
 
1635       $form->{emailed} = $emailed;
 
1636       $form->{message} = $message;
 
1638       $form->{rowcount}--;
 
1639       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
1640         qw(exchangerate creditlimit creditremaining);
 
1642       for my $i (1 .. $form->{paidaccounts}) {
 
1644           $form->{"${_}_$i"} =
 
1645             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
1646         } qw(paid exchangerate);
 
1649       call_sub($display_form);
 
1654       ($form->{media} eq 'printer')
 
1655       ? $locale->text('sent to printer')
 
1656       : $locale->text('emailed to') . " $form->{email}";
 
1657     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
 
1659   if ($form->{printing}) {
 
1660    call_sub($display_form);
 
1664   $main::lxdebug->leave_sub();
 
1667 sub customer_details {
 
1668   $main::lxdebug->enter_sub();
 
1670   my $form     = $main::form;
 
1671   my %myconfig = %main::myconfig;
 
1673   IS->customer_details(\%myconfig, \%$form, @_);
 
1675   $main::lxdebug->leave_sub();
 
1678 sub vendor_details {
 
1679   $main::lxdebug->enter_sub();
 
1681   my $form     = $main::form;
 
1682   my %myconfig = %main::myconfig;
 
1684   IR->vendor_details(\%myconfig, \%$form, @_);
 
1686   $main::lxdebug->leave_sub();
 
1690   $main::lxdebug->enter_sub();
 
1692   my $form     = $main::form;
 
1696   $form->{postasnew} = 1;
 
1697   map { delete $form->{$_} } qw(printed emailed queued);
 
1701   $main::lxdebug->leave_sub();
 
1705   $main::lxdebug->enter_sub();
 
1709   $::form->{print_and_post} = 0 if $::form->{second_run};
 
1711   map { $::form->{$_} = $::form->parse_amount(\%::myconfig, $::form->{$_}) } qw(exchangerate creditlimit creditremaining);
 
1713   # get details for customer/vendor
 
1714   call_sub($::form->{vc} . "_details", qw(name department_1 department_2 street zipcode city country contact email phone fax), $::form->{vc} . "number");
 
1716   # get pricegroups for parts
 
1717   IS->get_pricegroups_for_parts(\%::myconfig, \%$::form);
 
1719   # build up html code for prices_$i
 
1720   set_pricegroup($::form->{rowcount});
 
1722   $::form->{rowcount}--;
 
1724   my @shipto_vars   = qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
 
1725                          shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail
 
1726                          shiptodepartment_1 shiptodepartment_2);
 
1727   my $previous_form = $::auth->save_form_in_session(skip_keys => [ @shipto_vars, qw(header shipto_id) ]);
 
1728   $::form->{title}  = $::locale->text('Ship to');
 
1731   print $::form->parse_html_template('io/ship_to', { previousform => $previous_form,
 
1732                                                      nextsub      => $::form->{display_form} || 'display_form',
 
1735   $main::lxdebug->leave_sub();
 
1738 sub ship_to_entered {
 
1739   $::auth->restore_form_from_session(delete $::form->{previousform});
 
1740   call_sub($::form->{nextsub});
 
1743 sub relink_accounts {
 
1744   $main::lxdebug->enter_sub();
 
1746   my $form     = $main::form;
 
1747   my %myconfig = %main::myconfig;
 
1751   $form->{"taxaccounts"} =~ s/\s*$//;
 
1752   $form->{"taxaccounts"} =~ s/^\s*//;
 
1753   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
 
1754     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
 
1756   $form->{"taxaccounts"} = "";
 
1758   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
 
1760   $main::lxdebug->leave_sub();
 
1764   $main::lxdebug->enter_sub();
 
1766   my $form     = $main::form;
 
1767   my %myconfig = %main::myconfig;
 
1771   my $invdate = $form->{invdate} eq 'undefined' ? undef : $form->{invdate};
 
1772   my $duedate = $form->get_duedate(\%myconfig, $invdate);
 
1774   print $form->ajax_response_header() . ($duedate || $invdate);
 
1776   $main::lxdebug->leave_sub();
 
1779 sub _update_part_information {
 
1780   $main::lxdebug->enter_sub();
 
1782   my $form     = $main::form;
 
1784   my %part_information = IC->get_basic_part_info('id'        => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ],
 
1785                                                  'vendor_id' => $form->{vendor_id});
 
1787   $form->{PART_INFORMATION} = \%part_information;
 
1789   foreach my $i (1..$form->{rowcount}) {
 
1790     next unless ($form->{"id_${i}"});
 
1792     my $info                 = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
 
1793     $form->{"partunit_${i}"} = $info->{unit};
 
1794     $form->{"weight_$i"}     = $info->{weight};
 
1797   $main::lxdebug->leave_sub();
 
1801   $main::lxdebug->enter_sub();
 
1803   my $form     = $main::form;
 
1804   my %myconfig = %main::myconfig;
 
1806   if (!$form->{ordnumber} || !$form->{id}) {
 
1807     map { $form->{"ship_$_"} = 0 } (1..$form->{rowcount});
 
1808     $main::lxdebug->leave_sub();
 
1812   my $all_units = AM->retrieve_all_units();
 
1814   my %ship = DO->get_shipped_qty('type'  => ($form->{type} eq 'purchase_order') ? 'purchase' : 'sales',
 
1815                                  'oe_id' => $form->{id},);
 
1817   foreach my $i (1..$form->{rowcount}) {
 
1818     next unless ($form->{"id_${i}"});
 
1820     $form->{"ship_$i"} = 0;
 
1822     my $ship_entry = $ship{$form->{"id_$i"}};
 
1824     next if (!$ship_entry || ($ship_entry->{qty} <= 0));
 
1827       ($form->{simple_save} ? $form->{"qty_$i"} : $form->parse_amount(\%myconfig, $form->{"qty_$i"}))
 
1828       * $all_units->{$form->{"unit_$i"}}->{factor}
 
1829       / $all_units->{$form->{"partunit_$i"}}->{factor};
 
1831     $form->{"ship_$i"}  = min($rowqty, $ship_entry->{qty});
 
1832     $ship_entry->{qty} -= $form->{"ship_$i"};
 
1835   foreach my $i (1..$form->{rowcount}) {
 
1836     next unless ($form->{"id_${i}"});
 
1838     my $ship_entry = $ship{$form->{"id_$i"}};
 
1840     next if (!$ship_entry || ($ship_entry->{qty} <= 0.01));
 
1842     $form->{"ship_$i"} += $ship_entry->{qty};
 
1843     $ship_entry->{qty}  = 0;
 
1846   $main::lxdebug->leave_sub();
 
1849 sub _update_custom_variables {
 
1850   $main::lxdebug->enter_sub();
 
1852   my $form     = $main::form;
 
1854   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
 
1855   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
 
1857   $main::lxdebug->leave_sub();
 
1860 sub _render_custom_variables_inputs {
 
1861   $main::lxdebug->enter_sub(2);
 
1863   my $form     = $main::form;
 
1867   if (!$form->{CVAR_CONFIGS}->{IC}) {
 
1868     $main::lxdebug->leave_sub();
 
1872   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
 
1874   my $num_visible_cvars = 0;
 
1875   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
 
1876     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
 
1878     my $description = '';
 
1879     if ($cvar->{flag_editable} && $cvar->{valid}) {
 
1880       $num_visible_cvars++;
 
1881       $description = $cvar->{description} . ' ';
 
1884     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
 
1886     push @{ $params{ROW2} }, {
 
1887       line_break     => $num_visible_cvars == 1,
 
1888       description    => $description,
 
1891          hide_non_editable => 1,
 
1893          name_prefix       => 'ic_',
 
1894          name_postfix      => "_$params{row}",
 
1895          valid             => $cvar->{valid},
 
1896          value             => CVar->parse($::form->{$form_key}, $cvar),
 
1901   $main::lxdebug->leave_sub(2);
 
1904 sub _remove_billed_or_delivered_rows {
 
1907   croak "Missing parameter 'quantities'" if !$params{quantities};
 
1909   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
 
1912   my $make_key = sub {
 
1914     return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
 
1915     my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
 
1916     return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
 
1919   my $removed_rows = 0;
 
1921   while ($row < $::form->{rowcount}) {
 
1923     next unless $::form->{"id_$row"};
 
1925     my $parts_id                      = $::form->{"id_$row"};
 
1926     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
 
1928     my $key                           = $make_key->($row);
 
1929     my $sub_qty                       = min($base_qty, $params{quantities}->{$key});
 
1930     $params{quantities}->{$key}      -= $sub_qty;
 
1932     if (!$sub_qty || ($sub_qty != $base_qty)) {
 
1933       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
 
1934       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
 
1941   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
 
1942   $::form->{rowcount} -= $removed_rows;