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);
 
  52 use SL::Helper::Flash;
 
  54 require "bin/mozilla/common.pl";
 
  58 # any custom scripts for this one
 
  59 if (-f "bin/mozilla/custom_io.pl") {
 
  60   eval { require "bin/mozilla/custom_io.pl"; };
 
  62 if (-f "bin/mozilla/$::form->{login}_io.pl") {
 
  63   eval { require "bin/mozilla/$::form->{login}_io.pl"; };
 
  70 # this is for our long dates
 
  71 # $locale->text('January')
 
  72 # $locale->text('February')
 
  73 # $locale->text('March')
 
  74 # $locale->text('April')
 
  75 # $locale->text('May ')
 
  76 # $locale->text('June')
 
  77 # $locale->text('July')
 
  78 # $locale->text('August')
 
  79 # $locale->text('September')
 
  80 # $locale->text('October')
 
  81 # $locale->text('November')
 
  82 # $locale->text('December')
 
  84 # this is for our short month
 
  85 # $locale->text('Jan')
 
  86 # $locale->text('Feb')
 
  87 # $locale->text('Mar')
 
  88 # $locale->text('Apr')
 
  89 # $locale->text('May')
 
  90 # $locale->text('Jun')
 
  91 # $locale->text('Jul')
 
  92 # $locale->text('Aug')
 
  93 # $locale->text('Sep')
 
  94 # $locale->text('Oct')
 
  95 # $locale->text('Nov')
 
  96 # $locale->text('Dec')
 
 103   $main::auth->assert('part_service_assembly_edit   | vendor_invoice_edit       | sales_order_edit    | invoice_edit |' .
 
 104                 'request_quotation_edit       | sales_quotation_edit      | purchase_order_edit | ' .
 
 105                 'purchase_delivery_order_edit | sales_delivery_order_edit');
 
 108 ########################################
 
 109 # Eintrag fuer Version 2.2.0 geaendert #
 
 110 # neue Optik im Rechnungsformular      #
 
 111 ########################################
 
 113   $main::lxdebug->enter_sub();
 
 117   my $form     = $main::form;
 
 118   my %myconfig = %main::myconfig;
 
 119   my $locale   = $main::locale;
 
 120   my $cgi      = $::request->{cgi};
 
 124   my ($stock_in_out, $stock_in_out_title);
 
 126   my $defaults = AM->get_defaults();
 
 127   $form->{show_weight} = $defaults->{show_weight};
 
 128   $form->{weightunit} = $defaults->{weightunit};
 
 130   my $is_purchase        = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
 
 131   my $show_min_order_qty =  first { $_ eq $form->{type} } qw(request_quotation purchase_order);
 
 132   my $is_delivery_order  = $form->{type} =~ /_delivery_order$/;
 
 133   my $is_s_p_order       = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
 
 135   if ($is_delivery_order) {
 
 136     if ($form->{type} eq 'sales_delivery_order') {
 
 137       $stock_in_out_title = $locale->text('Release From Stock');
 
 138       $stock_in_out       = 'out';
 
 140       $stock_in_out_title = $locale->text('Transfer To Stock');
 
 141       $stock_in_out       = 'in';
 
 144     retrieve_partunits();
 
 148   my @header_sort = qw(runningnumber partnumber description ship qty unit weight sellprice_pg sellprice discount linetotal);
 
 150     {  id => 'runningnumber', width => 5,     value => $locale->text('No.'),                  display => 1, },
 
 151     {  id => 'partnumber',    width => 8,     value => $locale->text('Number'),               display => 1, },
 
 152     {  id => 'description',   width => 30,    value => $locale->text('Part Description'),     display => 1, },
 
 153     {  id => 'ship',          width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
 
 154     {  id => 'qty',           width => 5,     value => $locale->text('Qty'),                  display => 1, },
 
 155     {  id => 'price_factor',  width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
 
 156     {  id => 'unit',          width => 5,     value => $locale->text('Unit'),                 display => 1, },
 
 157     {  id => 'weight',        width => 5,     value => $locale->text('Weight'),               display => $defaults->{show_weight}, },
 
 158     {  id => 'serialnr',      width => 10,    value => $locale->text('Serial No.'),           display => 0, },
 
 159     {  id => 'projectnr',     width => 10,    value => $locale->text('Project'),              display => 0, },
 
 160     {  id => 'sellprice',     width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
 
 161     {  id => 'sellprice_pg',  width => 8,     value => $locale->text('Pricegroup'),           display => !$is_delivery_order && !$is_purchase, },
 
 162     {  id => 'discount',      width => 5,     value => $locale->text('Discount'),             display => !$is_delivery_order, },
 
 163     {  id => 'linetotal',     width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
 
 164     {  id => 'bin',           width => 10,    value => $locale->text('Bin'),                  display => 0, },
 
 165     {  id => 'stock_in_out',  width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
 
 167   my @column_index = map { $_->{id} } grep { $_->{display} } @HEADER;
 
 171   my $all_units       = AM->retrieve_units(\%myconfig, $form);
 
 173   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 175   my $colspan = scalar @column_index;
 
 177   $form->{invsubtotal} = 0;
 
 178   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
 
 181   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
 
 182   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
 
 185   # translations, unused commented out
 
 186 #  $runningnumber = $locale->text('No.');
 
 187 #  my $deliverydate  = $locale->text('Delivery Date');
 
 188   my $serialnumber  = $locale->text('Serial No.');
 
 189   my $projectnumber = $locale->text('Project');
 
 190 #  $partsgroup    = $locale->text('Group');
 
 191   my $reqdate       = $locale->text('Reqdate');
 
 192   my $deliverydate  = $locale->text('Required by');
 
 195   my %align  = map { $_ => 'right' } qw(qty ship right sellprice_pg discount linetotal stock_in_out weight);
 
 196   my %nowrap = map { $_ => 1 }       qw(description unit);
 
 198   $form->{marge_total}           = 0;
 
 199   $form->{sellprice_total}       = 0;
 
 200   $form->{lastcost_total}        = 0;
 
 201   $form->{totalweight}           = 0;
 
 202   my %projectnumber_labels = ();
 
 203   my @projectnumber_values = ("");
 
 205   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
 
 206     push(@projectnumber_values, $item->{"id"});
 
 207     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
 
 210   _update_part_information();
 
 211   _update_ship() if ($is_s_p_order);
 
 212   _update_custom_variables();
 
 219   for my $i (1 .. $numrows) {
 
 220     my %column_data = ();
 
 223     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
 
 224       qw(qty discount sellprice lastcost price_new price_old)
 
 225         unless ($form->{simple_save});
 
 228     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
 
 229     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
 
 231     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
 
 232         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
 
 233       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
 
 235     # adjust prices by unit, ignore if pricegroup changed
 
 236     if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) {
 
 237         $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 238         $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
 
 239         $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
 
 241     my $this_unit = $form->{"unit_$i"};
 
 242     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
 
 244     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
 
 245       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
 
 246       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
 
 248       $column_data{price_factor} =
 
 249         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
 
 250                              '-default' => $form->{"price_factor_id_$i"},
 
 251                              '-values'  => \@values,
 
 252                              '-labels'  => \%labels,
 
 253                              '-style'   => 'width:90px'));
 
 255       $column_data{price_factor} = ' ';
 
 257     $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
 
 259     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
 
 262 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
 
 263 #is shown for lastcost and sellprice.
 
 264     my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
 
 265     $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
 
 267     my $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
 
 268     my $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
 
 269     my $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
 
 270     my $rows            = $form->numtextrows($form->{"description_$i"}, 30, 6);
 
 272     $column_data{runningnumber} = $cgi->textfield(-name => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
 
 273     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
 
 274     $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
 
 275                                 ? $cgi->textarea( -name => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
 
 276                                 : $cgi->textfield(-name => "description_$i",   -size => 30, -value => $form->{"description_$i"}))
 
 277                                 . $cgi->button(-value => $locale->text('L'), -onClick => "set_longdescription_window('longdescription_$i')");
 
 279     my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
 
 281     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
 
 282     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_window('qty_$i','alu_$i', 'formel_$i', $i)", -value => $locale->text('*/'))
 
 283                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"}) . $cgi->hidden("-name" => "alu_$i", "-value" => $form->{"alu_$i"})
 
 284       if $form->{"formel_$i"};
 
 286     $column_data{ship} = '';
 
 287     if ($form->{"id_$i"}) {
 
 288       my $ship_qty        = $form->{"ship_$i"} * 1;
 
 289       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
 
 290       $ship_qty          /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
 
 292       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"};
 
 295     # build in drop down list for pricesgroups
 
 296     # $sellprice_value setzt den Wert etwas unabhängiger von der Darstellung.
 
 297     # Hintergrund: Preisgruppen werden hier überprüft und neu berechnet.
 
 298     # Vorher wurde der ganze cgi->textfield Block zweimal identisch eingebaut, dass passiert
 
 299     # jetzt nach der Abfrage.
 
 301     if ($form->{"prices_$i"}) {
 
 302       $column_data{sellprice_pg} = qq|<select name="sellprice_pg_$i" style="width: 8em">$form->{"prices_$i"}</select>|;
 
 303       $sellprice_value           =($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})
 
 304                                       ? $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces)
 
 305                                       : $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 307       # for last row and report
 
 308       # set pricegroup drop down list from report menu
 
 309       if ($form->{"sellprice_$i"} != 0) {
 
 310         # remember the pricegroup_id in pricegroup_old
 
 311         # but don't overwrite it
 
 312         $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"};
 
 313         my $default_option           = $form->{"sellprice_$i"}.'--'.$form->{"pricegroup_id_$i"};
 
 314         $column_data{sellprice_pg}   = NTI($cgi->popup_menu("sellprice_pg_$i", [ $default_option ], $default_option, { $default_option => $form->{"pricegroup_$i"} || '' }));
 
 316         $column_data{sellprice_pg} = qq| |;
 
 318       $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 321     # Falls der Benutzer die Preise nicht anpassen sollte, wird das entsprechende
 
 322     # Textfield auf readonly gesetzt. Anm. von Sven: Manipulation der Preise ist
 
 323     # immer noch möglich, konsequenterweise sollten diese NUR aus der Datenbank
 
 325     my $edit_prices = $main::auth->assert('edit_prices', 1);
 
 326     $column_data{sellprice} = (!$edit_prices)
 
 327                                 ? $cgi->textfield(-readonly => "readonly",
 
 328                                                   -name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value)
 
 329                                 : $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value);
 
 330     $column_data{discount}    = (!$edit_prices)
 
 331                                   ? $cgi->textfield(-readonly => "readonly",
 
 332                                                     -name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}))
 
 333                                   : $cgi->textfield(-name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}));
 
 334     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
 
 335     $column_data{bin}         = $form->{"bin_$i"};
 
 337     $column_data{weight}      = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
 
 339     if ($is_delivery_order) {
 
 340       $column_data{stock_in_out} =  calculate_stock_in_out($i);
 
 343     my @ROW1 = map { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} }, @column_index;
 
 347     push @ROW2, { value => qq|<b>$serialnumber</b> <input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">| }
 
 348       if $form->{type} !~ /_quotation/;
 
 349     push @ROW2, { value => qq|<b>$projectnumber</b> | . NTI($cgi->popup_menu('-name'  => "project_id_$i",        '-values'  => \@projectnumber_values,
 
 350                                                                              '-labels' => \%projectnumber_labels, '-default' => $form->{"project_id_$i"})) };
 
 351     push @ROW2, { value => qq|<b>$reqdate</b> <input name="reqdate_$i" size="11" onBlur="check_right_date_format(this)" value="$form->{"reqdate_$i"}">| }
 
 352       if ($form->{type} =~ /order/ ||  $form->{type} =~ /invoice/);
 
 353     push @ROW2, { value => sprintf qq|<b>%s</b> <input type="checkbox" name="subtotal_$i" value="1" %s>|,
 
 354                    $locale->text('Subtotal'), $form->{"subtotal_$i"} ? 'checked' : '' };
 
 356 # begin marge calculations
 
 357     $form->{"lastcost_$i"}     *= 1;
 
 358     $form->{"marge_percent_$i"} = 0;
 
 362     if ( $form->{taxincluded} and $form->{"qty_$i"} * 1  and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
 
 363       # if we use taxincluded we need to calculate the marge from the net_value
 
 364       # all the marge calculations are based on linetotal which we need to
 
 365       # convert to net first
 
 367       # there is no direct form value for the tax_rate of the item, but
 
 368       # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
 
 369       # gives the tax percentage (e.g. 0.19)
 
 370       $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
 
 372       $real_sellprice            = $linetotal;
 
 374     my $real_lastcost            = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 375     my $marge_percent_warn       = $myconfig{marge_percent_warn} * 1 || 15;
 
 376     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
 
 378     if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
 
 379       $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
 
 380       $marge_color                = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
 
 383     $form->{"marge_absolut_$i"}  = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
 
 384     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
 
 385     $form->{"lastcost_total"}   += $real_lastcost;
 
 386     $form->{"sellprice_total"}  += $real_sellprice;
 
 388     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
 
 390     push @ROW2, { value => sprintf qq|
 
 391          <font %s><b>%s</b> %s  %s%% </font>
 
 393          <b>%s</b> <input size="5" name="lastcost_$i" value="%s">|,
 
 394                    $marge_color, $locale->text('Ertrag'),$form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"},
 
 395                    $locale->text('LP'), $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2),
 
 396                    $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces) }
 
 397       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/ || $form->{type} =~ /^credit_note$/ ) && !$is_delivery_order;
 
 399     $form->{"listprice_$i"} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2)
 
 400       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/) ;
 
 401 # / marge calculations ending
 
 403 # Calculate total weight
 
 404     $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
 
 407     if ($form->{"id_$i"}) {
 
 408       my $part         = IC->get_basic_part_info(id => $form->{"id_$i"});
 
 409       my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
 
 410       push @ROW2, { value => sprintf "<b>%s</b> <font %s>%s %s</font>",
 
 411                       $locale->text('On Hand'),
 
 413                       $form->format_amount(\%myconfig, $part->{onhand}, 2),
 
 421     if ($is_delivery_order) {
 
 422       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
 
 423       push @hidden_vars, qw(sellprice discount not_discountable price_factor_id lastcost pricegroup_id);
 
 424       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
 
 427     my @HIDDENS = map { value => $_}, (
 
 428           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
 
 429           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
 
 430           map { ($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
 
 431             (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes
 
 432                 income_accno expense_accno listprice assembly taxaccounts ordnumber transdate cusordnumber
 
 433                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
 
 436     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
 
 438     $form->{invsubtotal} += $linetotal;
 
 440     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
 
 441     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
 
 443     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, };
 
 446   $form->{totalweight} = $totalweight;
 
 448   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
 
 452   if (0 != ($form->{sellprice_total} * 1)) {
 
 453     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
 
 456   $main::lxdebug->leave_sub();
 
 459 ##################################################
 
 460 # build html-code for pricegroups in variable $form->{prices_$j}
 
 463   $main::lxdebug->enter_sub();
 
 465   my $form     = $main::form;
 
 466   my $locale   = $main::locale;
 
 467   my $cgi      = $::request->{cgi};
 
 471   my $rowcount = shift;
 
 472   for my $j (1 .. $rowcount) {
 
 473     next unless $form->{PRICES}{$j};
 
 474     # build drop down list for pricegroups
 
 475     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
 
 476     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} }
 
 477                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
 
 479     foreach my $item (@{ $form->{PRICES}{$j} }) {
 
 480       # set new selectedpricegroup_id and prices for "Preis"
 
 481       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
 
 482       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
 
 483       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
 
 486   $main::lxdebug->leave_sub();
 
 490   $main::lxdebug->enter_sub();
 
 493   my $mode   = $params{mode} || croak "Missing parameter 'mode'";
 
 497   my $previous_form = $::auth->save_form_in_session(form => $::form);
 
 498   $::form->{title}  = $::locale->text('Select from one of the items below');
 
 501   my @item_list = map {
 
 502     $_->{display_sellprice}  = $_->{sellprice} * (1 - $::form->{tradediscount});
 
 503     $_->{display_sellprice} /= $_->{price_factor} if ($_->{price_factor});
 
 505   } @{ $::form->{item_list} };
 
 507   # delete action variable
 
 508   delete @{$::form}{qw(action item_list)};
 
 510   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
 
 512                                                          ITEM_LIST     => \@item_list,
 
 513                                                          IS_PURCHASE   => $mode eq 'IS' });
 
 515   $main::lxdebug->leave_sub();
 
 519   $main::lxdebug->enter_sub();
 
 521   my $form     = $main::form;
 
 522   my %myconfig = %main::myconfig;
 
 526   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
 
 528   my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
 
 529   my $id   = delete($form->{select_item_id})   || croak 'Missing item selection ID';
 
 530   my $i    = $form->{ $mode eq 'IC' ? 'assembly_rows' : 'rowcount' };
 
 532   $form->{"id_${i}"} = $id;
 
 535     IS->retrieve_item(\%myconfig, \%$form);
 
 536   } elsif ($mode eq 'IR') {
 
 537     IR->retrieve_item(\%myconfig, \%$form);
 
 538   } elsif ($mode eq 'IC') {
 
 539     IC->assembly_item(\%myconfig, \%$form);
 
 541     croak "Invalid item selection mode '${mode}'";
 
 544   my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
 
 546   # if there was a price entered, override it
 
 547   my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 550     qw(id partnumber description sellprice listprice inventory_accno
 
 551        income_accno expense_accno bin unit weight assembly taxaccounts
 
 552        partsgroup formel longdescription not_discountable partnotes lastcost
 
 553        price_factor_id price_factor);
 
 555   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 556   push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 558   map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
 
 560   $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
 
 562   if ($form->{"part_payment_id_$i"} ne "") {
 
 563     $form->{payment_id} = $form->{"part_payment_id_$i"};
 
 566   my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 568   my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 571     $form->{"sellprice_$i"} = $sellprice;
 
 574     # if there is an exchange rate adjust sellprice
 
 575     if (($form->{exchangerate} * 1) != 0) {
 
 576       $form->{"sellprice_$i"} /= $form->{exchangerate};
 
 577       $form->{"sellprice_$i"} =
 
 578         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
 
 582     if ($::form->{tradediscount}) {
 
 583       $::form->{"sellprice_$i"} *= 1 - $::form->{tradediscount};
 
 587   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 588     qw(sellprice listprice weight);
 
 590   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
 
 592   if ($form->{"not_discountable_$i"}) {
 
 593     $form->{"discount_$i"} = 0;
 
 597     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
 
 599   map { $form->{"${_}_base"} += $amount }
 
 600     (split / /, $form->{"taxaccounts_$i"});
 
 601   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
 
 602     $form->{"taxaccounts_$i"}
 
 603     if !$form->{taxincluded};
 
 605   $form->{creditremaining} -= $amount;
 
 607   $form->{"runningnumber_$i"} = $i;
 
 609   delete $form->{nextsub};
 
 614       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
 
 615   } qw(sellprice listprice lastcost) if $form->{item} ne 'assembly';
 
 617   # get pricegroups for parts
 
 618   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 620   # build up html code for prices_$i
 
 621   set_pricegroup($form->{rowcount});
 
 625   $main::lxdebug->leave_sub();
 
 629   $main::lxdebug->enter_sub();
 
 631   my $form     = $main::form;
 
 632   my %myconfig = %main::myconfig;
 
 636   my $price_key = ($form->{type} =~ m/request_quotation|purchase_order/) || ($form->{script} eq 'ir.pl') ? 'lastcost' : 'sellprice';
 
 639   $form->{old_callback} = $form->escape($form->{callback}, 1);
 
 640   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
 
 642   # save all form variables except action in the session and keep the key in the previousform variable
 
 643   my $previousform = $::auth->save_form_in_session(skip_keys => [ qw(action) ]);
 
 646   push @HIDDENS,      { 'name' => 'previousform', 'value' => $previousform };
 
 647   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc);
 
 648   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit);
 
 649   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
 
 650   push @HIDDENS,      { 'name' => $price_key,     'value' => $form->parse_amount(\%myconfig, $form->{"sellprice_$form->{rowcount}"}) };
 
 651   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{"longdescription_$form->{rowcount}"} };
 
 654   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
 
 656   $main::lxdebug->leave_sub();
 
 660   $main::lxdebug->enter_sub();
 
 662   my $form     = $main::form;
 
 663   my %myconfig = %main::myconfig;
 
 670   # remove any makes or model rows
 
 671   if ($form->{item} eq 'part') {
 
 672     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 673       qw(listprice sellprice lastcost weight rop);
 
 675   } elsif ($form->{item} eq 'assembly') {
 
 677     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
 
 678     #$form->{sellprice} = 0;
 
 680     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
 681       qw(listprice sellprice rop stock);
 
 683     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
 
 685     for my $i (1 .. ($form->{assembly_rows} - 1)) {
 
 686       if ($form->{"qty_$i"}) {
 
 690         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 692         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
 
 694         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 696         # fuer assemblies auskommentiert. siehe oben
 
 697         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
 
 698         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
 
 702     # kann das hier auch weg? s.o. jb
 
 703     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
 
 705     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
 
 706     $form->{assembly_rows} = $count;
 
 708   } elsif ($form->{item} eq 'service') {
 
 709     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(listprice sellprice lastcost);
 
 712     remove_emptied_rows(1);
 
 714     $form->{creditremaining} -= &invoicetotal;
 
 719   if (   $form->{type} =~ (/sales_quotation/)
 
 720       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
 
 721       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
 
 722       or ($form->{type} =~ /sales_order/)) {
 
 724     # get pricegroups for parts
 
 725     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
 727     # build up html code for prices_$i
 
 728     set_pricegroup($form->{rowcount});
 
 734   $main::lxdebug->leave_sub();
 
 737 sub remove_emptied_rows {
 
 738   my $dont_add_empty = shift;
 
 741   return unless $form->{rowcount};
 
 743   my @flds = qw(id partnumber description qty ship sellprice unit
 
 744                 discount inventory_accno income_accno expense_accno listprice
 
 745                 taxaccounts bin assembly weight projectnumber project_id
 
 746                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
 
 747                 not_discountable shop ve gv buchungsgruppen_id language_values
 
 748                 sellprice_pg pricegroup_old price_old price_new unit_old ordnumber
 
 749                 transdate longdescription basefactor marge_total marge_percent
 
 750                 marge_price_factor lastcost price_factor_id partnotes
 
 751                 stock_out stock_in has_sernumber reqdate);
 
 753   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
 
 754   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
 
 757   for my $i (1 .. $form->{rowcount} - 1) {
 
 758     next unless $form->{"partnumber_$i"};
 
 760     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
 
 763   my $new_rowcount = scalar @new_rows;
 
 764   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
 
 765   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
 
 769   $main::lxdebug->enter_sub();
 
 771   my $form     = $main::form;
 
 772   my %myconfig = %main::myconfig;
 
 776   $form->{oldinvtotal} = 0;
 
 778   # add all parts and deduct paid
 
 779   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
 
 781   my ($amount, $sellprice, $discount, $qty);
 
 783   for my $i (1 .. $form->{rowcount}) {
 
 784     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 785     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
 
 786     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 788     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
 
 790     $amount = $sellprice * (1 - $discount / 100) * $qty;
 
 791     map { $form->{"${_}_base"} += $amount }
 
 792       (split (/ /, $form->{"taxaccounts_$i"}));
 
 793     $form->{oldinvtotal} += $amount;
 
 796   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
 
 797     split(/ /, $form->{taxaccounts})
 
 798     if !$form->{taxincluded};
 
 800   $form->{oldtotalpaid} = 0;
 
 801   for my $i (1 .. $form->{paidaccounts}) {
 
 802     $form->{oldtotalpaid} += $form->{"paid_$i"};
 
 805   $main::lxdebug->leave_sub();
 
 808   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 812   $main::lxdebug->enter_sub();
 
 814   my $form     = $main::form;
 
 815   my $locale   = $main::locale;
 
 819   # check if items are valid
 
 820   if ($form->{rowcount} == 1) {
 
 821     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
 
 826   for my $i (1 .. $form->{rowcount} - 1) {
 
 827     $form->isblank("partnumber_$i",
 
 828                    $locale->text('Number missing in Row') . " $i");
 
 831   $main::lxdebug->leave_sub();
 
 835   $main::lxdebug->enter_sub();
 
 837   my $form     = $main::form;
 
 838   my %myconfig = %main::myconfig;
 
 839   my $locale   = $main::locale;
 
 843   if ($form->{second_run}) {
 
 844     $form->{print_and_post} = 0;
 
 846   $form->{ordnumber} = $form->{invnumber};
 
 848   $form->{old_employee_id} = $form->{employee_id};
 
 849   $form->{old_salesman_id} = $form->{salesman_id};
 
 851   map { delete $form->{$_} } qw(id printed emailed queued);
 
 853   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
 
 854     $form->{title} = $locale->text('Add Purchase Order');
 
 855     $form->{vc}    = 'vendor';
 
 856     $form->{type}  = 'purchase_order';
 
 859   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
 
 860     $form->{title} = $locale->text('Add Sales Order');
 
 861     $form->{vc}    = 'customer';
 
 862     $form->{type}  = 'sales_order';
 
 865   $form->{script} = 'oe.pl';
 
 873   require "bin/mozilla/$form->{script}";
 
 874   my $script = $form->{"script"};
 
 877   $locale = new Locale($::lx_office_conf{system}->{language}, $script);
 
 879   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
 881   my $currency = $form->{currency};
 
 885   $form->{currency}     = $currency;
 
 886   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
 887   $form->{exchangerate} = $form->{forex} || '';
 
 889   for my $i (1 .. $form->{rowcount}) {
 
 890     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
 
 891             if ($form->{"${_}_${i}"}) }
 
 892         qw(ship qty sellprice listprice basefactor discount));
 
 898   $main::lxdebug->leave_sub();
 
 902   $main::lxdebug->enter_sub();
 
 904   my $form     = $main::form;
 
 905   my %myconfig = %main::myconfig;
 
 906   my $locale   = $main::locale;
 
 910   if ($form->{second_run}) {
 
 911     $form->{print_and_post} = 0;
 
 913   map { delete $form->{$_} } qw(id printed emailed queued);
 
 916   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
 
 917     $form->{title} = $locale->text('Add Request for Quotation');
 
 918     $form->{vc}    = 'vendor';
 
 919     $form->{type}  = 'request_quotation';
 
 922   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
 
 923     $form->{title} = $locale->text('Add Quotation');
 
 924     $form->{vc}    = 'customer';
 
 925     $form->{type}  = 'sales_quotation';
 
 931   $form->{script} = 'oe.pl';
 
 937   require "bin/mozilla/$form->{script}";
 
 939   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
 
 941   my $currency = $form->{currency};
 
 945   $form->{currency}     = $currency;
 
 946   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
 
 947   $form->{exchangerate} = $form->{forex} || '';
 
 949   for my $i (1 .. $form->{rowcount}) {
 
 950     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
 
 951                                                      $form->{"${_}_${i}"})
 
 952             if ($form->{"${_}_${i}"}) }
 
 953         qw(ship qty sellprice listprice basefactor discount));
 
 959   $main::lxdebug->leave_sub();
 
 962 sub request_for_quotation {
 
 967   $main::lxdebug->enter_sub();
 
 969   my $form     = $main::form;
 
 970   my %myconfig = %main::myconfig;
 
 971   my $locale   = $main::locale;
 
 975   if ($form->{second_run}) {
 
 976     $form->{print_and_post} = 0;
 
 977     $form->{resubmit}       = 0;
 
 980   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
 
 982   if ($form->{"cp_id"}) {
 
 983     CT->get_contact(\%myconfig, $form);
 
 984     $form->{"email"} = $form->{"cp_email"} if $form->{"cp_email"};
 
 987   $form->{language} = $form->get_template_language(\%myconfig);
 
 988   $form->{language} = "_" . $form->{language} if $form->{language};
 
 990   my $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
 
 992   $form->{oldmedia} = $form->{media};
 
 993   $form->{media}    = "email";
 
 995   my $attachment_filename = $form->generate_attachment_filename();
 
 996   my $subject             = $form->{subject} || $form->generate_email_subject();
 
 998   $::request->{layout}->focus($form->{"email"} ? "#subject" : "#email");
 
1001   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
 
1002   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override login password);
 
1003   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
 
1004   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
 
1006   print $form->parse_html_template('generic/edit_email',
 
1008                                      a_filename    => $attachment_filename,
 
1009                                      subject       => $subject,
 
1010                                      print_options => print_options('inline' => 1),
 
1011                                      HIDDEN        => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
 
1012                                      SHOW_BCC      => $::auth->assert('email_bcc', 'may fail') });
 
1014   $main::lxdebug->leave_sub();
 
1018   $main::lxdebug->enter_sub();
 
1020   my $form     = $main::form;
 
1021   my %myconfig = %main::myconfig;
 
1025   my $callback = $form->{script} . "?action=edit";
 
1026   map({ $callback .= "\&${_}=" . E($form->{$_}); } qw(type id));
 
1028   print_form("return");
 
1030   Common->save_email_status(\%myconfig, $form);
 
1032   $form->{callback} = $callback;
 
1035   $main::lxdebug->leave_sub();
 
1038 # generate the printing options displayed at the bottom of oe and is forms.
 
1039 # this function will attempt to guess what type of form is displayed, and will generate according options
 
1042 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
 
1043 # the opthash function builds hashrefs which are then pieced together for the template arrays.
 
1044 # unneeded options are "undef"ed out, and then grepped out.
 
1046 # the inline options is untested, but intended to be used later in metatemplating
 
1048   $main::lxdebug->enter_sub();
 
1050   my $form     = $main::form;
 
1051   my %myconfig = %main::myconfig;
 
1052   my $locale   = $main::locale;
 
1058   # names 3 parameters and returns a hashref, for use in templates
 
1059   sub opthash { +{ value => shift, selected => shift, oname => shift } }
 
1060   my (@FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
 
1062   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
 
1063   $form->{sendmode}   = "attachment";
 
1064   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
 
1065   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
 
1066   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
 
1067   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
 
1068                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
 
1070   $form->{PD}{ $form->{formname} } = "selected";
 
1071   $form->{DF}{ $form->{format} }   = "selected";
 
1072   $form->{OP}{ $form->{media} }    = "selected";
 
1073   $form->{SM}{ $form->{formname} } = "selected";
 
1075   push @FORMNAME, grep $_,
 
1076     ($form->{type} eq 'purchase_order') ? (
 
1077       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
 
1078       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List'))
 
1080     ($form->{type} eq 'credit_note') ?
 
1081       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
 
1082     ($form->{type} eq 'sales_order') ? (
 
1083       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
 
1084       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
 
1086     ($form->{type} =~ /sales_quotation$/) ?
 
1087       opthash('sales_quotation',     $form->{PD}{sales_quotation},     $locale->text('Quotation')) : undef,
 
1088     ($form->{type} =~ /request_quotation$/) ?
 
1089       opthash('request_quotation',   $form->{PD}{request_quotation},   $locale->text('Request for Quotation')) : undef,
 
1090     ($form->{type} eq 'invoice') ? (
 
1091       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
 
1092       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
 
1094     ($form->{type} eq 'invoice' && $form->{storno}) ? (
 
1095       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
 
1097     ($form->{type} =~ /_delivery_order$/) ? (
 
1098       opthash($form->{type},         $form->{PD}{$form->{type}},       $locale->text('Delivery Order')),
 
1099       opthash('pick_list',           $form->{PD}{pick_list},           $locale->text('Pick List')),
 
1103     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
 
1104     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
 
1105       if ($form->{media} eq 'email');
 
1107   my $printable_templates = any { $::lx_office_conf{print_templates}->{$_} } qw(latex opendocument);
 
1108   push @MEDIA, grep $_,
 
1109       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
 
1110     ($printable_templates && $form->{printers} && scalar @{ $form->{printers} }) ?
 
1111       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
 
1112     ($printable_templates && !$options{no_queue}) ?
 
1113       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
 
1114         if ($form->{media} ne 'email');
 
1116   push @FORMAT, grep $_,
 
1117     ($::lx_office_conf{print_templates}->{opendocument} &&     $::lx_office_conf{applications}->{openofficeorg_writer}  &&     $::lx_office_conf{applications}->{xvfb}
 
1118                                                         && (-x $::lx_office_conf{applications}->{openofficeorg_writer}) && (-x $::lx_office_conf{applications}->{xvfb})
 
1119      && !$options{no_opendocument_pdf}) ?
 
1120       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
 
1121     ($::lx_office_conf{print_templates}->{latex}) ?
 
1122       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
 
1123     ($::lx_office_conf{print_templates}->{latex} && !$options{no_postscript}) ?
 
1124       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
 
1125     (!$options{no_html}) ?
 
1126       opthash("html", $form->{DF}{html}, "HTML") : undef,
 
1127     ($::lx_office_conf{print_templates}->{opendocument} && !$options{no_opendocument}) ?
 
1128       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef,
 
1129     ($::lx_office_conf{print_templates}->{excel} && !$options{no_excel}) ?
 
1130       opthash("excel",               $form->{DF}{excel},               $locale->text("Excel")) : undef;
 
1133     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
 
1134       if (ref $form->{languages} eq 'ARRAY');
 
1137     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
 
1138       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
 
1143     show  => !$options{"hide_" . $_->[1]} && scalar @{ $_->[0] }
 
1145   [ \@FORMNAME,    'formname',    ],
 
1146   [ \@LANGUAGE_ID, 'language_id', ],
 
1147   [ \@FORMAT,      'format',      ],
 
1148   [ \@SENDMODE,    'sendmode',    ],
 
1149   [ \@MEDIA,       'media',       ],
 
1150   [ \@PRINTER_ID,  'printer_id',  ];
 
1152   my %dont_display_groupitems = (
 
1156   my %template_vars = (
 
1157     display_copies       => scalar @{ $form->{printers} || [] } && $::lx_office_conf{print_templates}->{latex} && $form->{media} ne 'email',
 
1158     display_remove_draft => (!$form->{id} && $form->{draft_id}),
 
1159     display_groupitems   => !$dont_display_groupitems{$form->{type}},
 
1160     groupitems_checked   => $form->{groupitems} ? "checked" : '',
 
1161     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
 
1164   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
 
1166   if ($options{inline}) {
 
1167     $main::lxdebug->leave_sub();
 
1168     return $print_options;
 
1171   print $print_options;
 
1173   $main::lxdebug->leave_sub();
 
1177   $main::lxdebug->enter_sub();
 
1179   my $form     = $main::form;
 
1180   my $locale   = $main::locale;
 
1184   if ($form->{print_nextsub}) {
 
1185     call_sub($form->{print_nextsub});
 
1186     $main::lxdebug->leave_sub();
 
1190   # if this goes to the printer pass through
 
1192   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
 
1193     $form->error($locale->text('Select postscript or PDF!'))
 
1194       if ($form->{format} !~ /(postscript|pdf)/);
 
1196     $old_form = new Form;
 
1197     map { $old_form->{$_} = $form->{$_} } keys %$form;
 
1200   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
 
1201     if ($form->{formname} eq "proforma") {
 
1202       $form->{proforma} = 1;
 
1204     $form->{print_and_save} = 1;
 
1205     my $formname = $form->{formname};
 
1207     $form->{formname} = $formname;
 
1209     $::lxdebug->leave_sub();
 
1213   &print_form($old_form);
 
1215   $main::lxdebug->leave_sub();
 
1219   $main::lxdebug->enter_sub();
 
1221   my $form     = $main::form;
 
1222   my %myconfig = %main::myconfig;
 
1223   my $locale   = $main::locale;
 
1227   my ($old_form) = @_;
 
1231   my $numberfld = "invnumber";
 
1235     ($form->{display_form}) ? $form->{display_form} : "display_form";
 
1237   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
 
1238   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
 
1240   if ($form->{formname} eq "invoice") {
 
1241     $form->{label} = $locale->text('Invoice');
 
1243   if ($form->{formname} eq 'sales_order') {
 
1246     $form->{"${inv}date"} = $form->{transdate};
 
1247     $form->{label}        = $locale->text('Confirmation');
 
1248     $numberfld            = "sonumber";
 
1252   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
 
1255     $form->{"${inv}date"} = $form->{invdate};
 
1256     $form->{label}        = $locale->text('Proforma Invoice');
 
1257     $numberfld            = "sonumber";
 
1261   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
 
1264     $form->{"${inv}date"} = $form->{transdate};
 
1265     $form->{"invdate"}    = $form->{transdate};
 
1266     $form->{invnumber}    = $form->{ordnumber};
 
1267     $form->{label}        = $locale->text('Proforma Invoice');
 
1268     $numberfld            = "sonumber";
 
1272   if ($form->{formname} eq 'purchase_order') {
 
1275     $form->{"${inv}date"} = $form->{transdate};
 
1276     $form->{label}        = $locale->text('Purchase Order');
 
1277     $numberfld            = "ponumber";
 
1280   if ($form->{formname} eq 'bin_list') {
 
1283     $form->{"${inv}date"} = $form->{transdate};
 
1284     $form->{label}        = $locale->text('Bin List');
 
1287   if ($form->{formname} eq 'sales_quotation') {
 
1290     $form->{"${inv}date"} = $form->{transdate};
 
1291     $form->{label}        = $locale->text('Quotation');
 
1292     $numberfld            = "sqnumber";
 
1296   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
 
1299     $form->{"${inv}date"} = $form->{transdate};
 
1300     $form->{"invdate"}    = $form->{transdate};
 
1301     $form->{label}        = $locale->text('Proforma Invoice');
 
1302     $numberfld            = "sqnumber";
 
1306   if ($form->{formname} eq 'request_quotation') {
 
1309     $form->{"${inv}date"} = $form->{transdate};
 
1310     $form->{label}        = $locale->text('RFQ');
 
1311     $numberfld            = "rfqnumber";
 
1315   if ($form->{type} =~ /_delivery_order$/) {
 
1318     $form->{"${inv}date"} = $form->{transdate};
 
1319     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
 
1320     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
 
1323   $form->isblank("email", $locale->text('E-mail address missing!'))
 
1324     if ($form->{media} eq 'email');
 
1325   $form->isblank("${inv}date",
 
1326            $locale->text($form->{label})
 
1328            . $locale->text(' Date missing!'));
 
1330   # $locale->text('Invoice Number missing!')
 
1331   # $locale->text('Invoice Date missing!')
 
1332   # $locale->text('Order Number missing!')
 
1333   # $locale->text('Order Date missing!')
 
1334   # $locale->text('Quotation Number missing!')
 
1335   # $locale->text('Quotation Date missing!')
 
1338   $form->{what_done} = $form->{formname};
 
1339   if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) {
 
1340     $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld);
 
1341     if ($form->{media} ne 'email') {
 
1343       # get pricegroups for parts
 
1344       IS->get_pricegroups_for_parts(\%myconfig, \%$form);
 
1346       # build up html code for prices_$i
 
1347       set_pricegroup($form->{rowcount});
 
1349       $form->{rowcount}--;
 
1351       call_sub($display_form);
 
1352       # saving the history
 
1353       if(!exists $form->{addition}) {
 
1354         $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
 
1355         $form->{addition} = "PRINTED";
 
1356         $form->save_history;
 
1358       # /saving the history
 
1365   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
 
1366   my ($saved_email, $saved_cc, $saved_bcc) =
 
1367     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
 
1369   my $language_saved = $form->{language_id};
 
1370   my $payment_id_saved = $form->{payment_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->{taxzone_id} = $taxzone_id_saved;
 
1381   $form->{currency} = $currency_saved;
 
1383   $form->{"email"} = $saved_email if ($saved_email);
 
1384   $form->{"cc"}    = $saved_cc    if ($saved_cc);
 
1385   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
 
1387   if (!$cp_id_saved) {
 
1388     # No contact was selected. Delete all contact variables because
 
1389     # IS->customer_details() and IR->vendor_details() get the default
 
1391     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
 
1394   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
1395   if ($form->{"language_id"}) {
 
1396     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
 
1397       AM->get_language_details(\%myconfig, $form, $form->{language_id});
 
1399     $output_dateformat = $myconfig{"dateformat"};
 
1400     $output_numberformat = $myconfig{"numberformat"};
 
1401     $output_longdates = 1;
 
1404   # Store the output number format so that the template modules know
 
1405   # how to parse the amounts back if requested.
 
1406   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
 
1408   ($form->{employee}) = split /--/, $form->{employee};
 
1410   # create the form variables
 
1411   if ($form->{type} =~ /_delivery_order$/) {
 
1412     DO->order_details(\%myconfig, \%$form);
 
1414     OE->order_details(\%myconfig, \%$form);
 
1416     IS->invoice_details(\%myconfig, \%$form, $locale);
 
1419   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
 
1420   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
 
1422   if ($form->{shipto_id}) {
 
1423     $form->get_shipto(\%myconfig);
 
1426   my @a = qw(name department_1 department_2 street zipcode city country contact phone fax email);
 
1430   # if there is no shipto fill it in from billto
 
1431   foreach my $item (@a) {
 
1432     if ($form->{"shipto$item"}) {
 
1439     if (   $form->{formname} eq 'purchase_order'
 
1440         || $form->{formname} eq 'request_quotation') {
 
1441       $form->{shiptoname}   = $myconfig{company};
 
1442       $form->{shiptostreet} = $myconfig{address};
 
1444       map { $form->{"shipto$_"} = $form->{$_} } @a;
 
1448   $form->{notes} =~ s/^\s+//g;
 
1450   $form->{templates} = "$myconfig{templates}";
 
1452   delete $form->{printer_command};
 
1454   $form->{language} = $form->get_template_language(\%myconfig);
 
1457   if ($form->{media} ne 'email') {
 
1458     $printer_code = $form->get_printer_code(\%myconfig);
 
1459     if ($printer_code ne "") {
 
1460       $printer_code = "_" . $printer_code;
 
1464   if ($form->{language} ne "") {
 
1465     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
 
1466     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
 
1468     $form->{language} = "_" . $form->{language};
 
1472   format_dates($output_dateformat, $output_longdates,
 
1473                qw(invdate orddate quodate pldate duedate reqdate transdate
 
1474                   shippingdate deliverydate validitydate paymentdate
 
1475                   datepaid transdate_oe deliverydate_oe dodate
 
1476                   employee_startdate employee_enddate
 
1478                grep({ /^datepaid_\d+$/ ||
 
1479                         /^transdate_oe_\d+$/ ||
 
1480                         /^deliverydate_oe_\d+$/ ||
 
1482                         /^deliverydate_\d+$/ ||
 
1486   reformat_numbers($output_numberformat, 2,
 
1487                    qw(invtotal ordtotal quototal subtotal linetotal
 
1488                       listprice sellprice netprice discount
 
1489                       tax taxbase total paid payment),
 
1490                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
 
1492   reformat_numbers($output_numberformat, undef,
 
1493                    qw(qty price_factor),
 
1497   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
 
1499   if (scalar @{ $cvar_date_fields }) {
 
1500     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
 
1503   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
 
1504     reformat_numbers($output_numberformat, $precision, @{ $field_list });
 
1507   my $extension = 'html';
 
1508   if ($form->{format} eq 'postscript') {
 
1509     $form->{postscript}   = 1;
 
1512   } elsif ($form->{"format"} =~ /pdf/) {
 
1514     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
1516   } elsif ($form->{"format"} =~ /opendocument/) {
 
1517     $form->{opendocument} = 1;
 
1519   } elsif ($form->{"format"} =~ /excel/) {
 
1524   # search for the template
 
1526   push @template_files, "$form->{formname}_email$form->{language}$printer_code.$extension" if $form->{media} eq 'email';
 
1527   push @template_files, "$form->{formname}$form->{language}$printer_code.$extension";
 
1528   push @template_files, "$form->{formname}.$extension";
 
1529   push @template_files, "default.$extension";
 
1530   @template_files = uniq @template_files;
 
1531   $form->{IN}     = first { -f "$myconfig{templates}/$_" } @template_files;
 
1533   if (!defined $form->{IN}) {
 
1534     $::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));
 
1537   delete $form->{OUT};
 
1539   if ($form->{media} eq 'printer') {
 
1540     $form->{OUT}      = $form->{printer_command};
 
1541     $form->{OUT_MODE} = '|-';
 
1542     $form->{printed} .= " $form->{formname}";
 
1543     $form->{printed}  =~ s/^ //;
 
1545   my $printed = $form->{printed};
 
1547   if ($form->{media} eq 'email') {
 
1548     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
 
1549       unless $form->{subject};
 
1551     $form->{emailed} .= " $form->{formname}";
 
1552     $form->{emailed} =~ s/^ //;
 
1554   my $emailed = $form->{emailed};
 
1556   if ($form->{media} eq 'queue') {
 
1557     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
 
1560     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
 
1561     if ($filename = $queued{ $form->{formname} }) {
 
1562       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
 
1563       delete $queued{ $form->{formname} };
 
1565       $form->{queued}    =  join ' ', %queued;
 
1566       $filename          =~ s/\..*$//g;
 
1567       $filename         .=  $suffix;
 
1568       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
 
1569       $form->{OUT_MODE}  =  '>';
 
1573       ($temp_fh, $filename) = File::Temp::tempfile(
 
1574         'kivitendo-spoolXXXXXX',
 
1575         SUFFIX => "$suffix",
 
1576         DIR    => $::lx_office_conf{paths}->{spool},
 
1580       $form->{OUT} = "$filename";
 
1581       # use >> for OUT_MODE because file is already created by File::Temp
 
1582       $form->{OUT_MODE} = '>>';
 
1583       # strip directory so that only filename is stored in table status
 
1584       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
 
1588     $form->{queued} .= " $form->{formname} $filename";
 
1589     $form->{queued} =~ s/^ //;
 
1591   my $queued = $form->{queued};
 
1593 # saving the history
 
1594   if(!exists $form->{addition}) {
 
1595     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
 
1596     if($form->{media} =~ /printer/) {
 
1597       $form->{addition} = "PRINTED";
 
1599     elsif($form->{media} =~ /email/) {
 
1600       $form->{addition} = "MAILED";
 
1602     elsif($form->{media} =~ /queue/) {
 
1603       $form->{addition} = "QUEUED";
 
1605     elsif($form->{media} =~ /screen/) {
 
1606       $form->{addition} = "SCREENED";
 
1608     $form->save_history;
 
1610   # /saving the history
 
1612   # prepare meta information for template introspection
 
1613   $form->{template_meta} = {
 
1614     formname  => $form->{formname},
 
1615     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
 
1616     format    => $form->{format},
 
1617     media     => $form->{media},
 
1618     extension => $extension,
 
1619     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
 
1620     today     => DateTime->today,
 
1623   $form->parse_template(\%myconfig);
 
1625   $form->{callback} = "";
 
1627   if ($form->{media} eq 'email') {
 
1628     $form->{message} = $locale->text('sent') unless $form->{message};
 
1630   my $message = $form->{message};
 
1632   # if we got back here restore the previous form
 
1633   if ($form->{media} =~ /(printer|email|queue)/) {
 
1635     $form->update_status(\%myconfig)
 
1636       if ($form->{media} eq 'queue' && $form->{id});
 
1638     return $main::lxdebug->leave_sub() if ($old_form eq "return");
 
1642       $old_form->{"${inv}number"} = $form->{"${inv}number"};
 
1644       # restore and display form
 
1645       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
 
1647       $form->{queued}  = $queued;
 
1648       $form->{printed} = $printed;
 
1649       $form->{emailed} = $emailed;
 
1650       $form->{message} = $message;
 
1652       $form->{rowcount}--;
 
1653       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
 
1654         qw(exchangerate creditlimit creditremaining);
 
1656       for my $i (1 .. $form->{paidaccounts}) {
 
1658           $form->{"${_}_$i"} =
 
1659             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
 
1660         } qw(paid exchangerate);
 
1663       call_sub($display_form);
 
1668       ($form->{media} eq 'printer')
 
1669       ? $locale->text('sent to printer')
 
1670       : $locale->text('emailed to') . " $form->{email}";
 
1671     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
 
1673   if ($form->{printing}) {
 
1674    call_sub($display_form);
 
1678   $main::lxdebug->leave_sub();
 
1681 sub customer_details {
 
1682   $main::lxdebug->enter_sub();
 
1684   my $form     = $main::form;
 
1685   my %myconfig = %main::myconfig;
 
1687   IS->customer_details(\%myconfig, \%$form, @_);
 
1689   $main::lxdebug->leave_sub();
 
1692 sub vendor_details {
 
1693   $main::lxdebug->enter_sub();
 
1695   my $form     = $main::form;
 
1696   my %myconfig = %main::myconfig;
 
1698   IR->vendor_details(\%myconfig, \%$form, @_);
 
1700   $main::lxdebug->leave_sub();
 
1704   $main::lxdebug->enter_sub();
 
1706   my $form     = $main::form;
 
1710   $form->{postasnew} = 1;
 
1711   map { delete $form->{$_} } qw(printed emailed queued);
 
1715   $main::lxdebug->leave_sub();
 
1719   $main::lxdebug->enter_sub();
 
1723   $::form->{print_and_post} = 0 if $::form->{second_run};
 
1725   map { $::form->{$_} = $::form->parse_amount(\%::myconfig, $::form->{$_}) } qw(exchangerate creditlimit creditremaining);
 
1727   # get details for customer/vendor
 
1728   call_sub($::form->{vc} . "_details", qw(name department_1 department_2 street zipcode city country contact email phone fax), $::form->{vc} . "number");
 
1730   # get pricegroups for parts
 
1731   IS->get_pricegroups_for_parts(\%::myconfig, \%$::form);
 
1733   # build up html code for prices_$i
 
1734   set_pricegroup($::form->{rowcount});
 
1736   $::form->{rowcount}--;
 
1738   my @shipto_vars   = qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
 
1739                          shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail
 
1740                          shiptodepartment_1 shiptodepartment_2);
 
1741   my $previous_form = $::auth->save_form_in_session(skip_keys => [ @shipto_vars, qw(header shipto_id) ]);
 
1742   $::form->{title}  = $::locale->text('Ship to');
 
1745   print $::form->parse_html_template('io/ship_to', { previousform => $previous_form,
 
1746                                                      nextsub      => $::form->{display_form} || 'display_form',
 
1749   $main::lxdebug->leave_sub();
 
1752 sub ship_to_entered {
 
1753   $::auth->restore_form_from_session(delete $::form->{previousform});
 
1754   call_sub($::form->{nextsub});
 
1757 sub relink_accounts {
 
1758   $main::lxdebug->enter_sub();
 
1760   my $form     = $main::form;
 
1761   my %myconfig = %main::myconfig;
 
1765   $form->{"taxaccounts"} =~ s/\s*$//;
 
1766   $form->{"taxaccounts"} =~ s/^\s*//;
 
1767   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
 
1768     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
 
1770   $form->{"taxaccounts"} = "";
 
1772   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
 
1774   $main::lxdebug->leave_sub();
 
1778   $main::lxdebug->enter_sub();
 
1780   my $form     = $main::form;
 
1781   my %myconfig = %main::myconfig;
 
1785   my $invdate = $form->{invdate} eq 'undefined' ? undef : $form->{invdate};
 
1786   my $duedate = $form->get_duedate(\%myconfig, $invdate);
 
1788   print $form->ajax_response_header() . ($duedate || $invdate);
 
1790   $main::lxdebug->leave_sub();
 
1793 sub _update_part_information {
 
1794   $main::lxdebug->enter_sub();
 
1796   my $form     = $main::form;
 
1798   my %part_information = IC->get_basic_part_info('id'        => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ],
 
1799                                                  'vendor_id' => $form->{vendor_id});
 
1801   $form->{PART_INFORMATION} = \%part_information;
 
1803   foreach my $i (1..$form->{rowcount}) {
 
1804     next unless ($form->{"id_${i}"});
 
1806     my $info                 = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
 
1807     $form->{"partunit_${i}"} = $info->{unit};
 
1808     $form->{"weight_$i"}     = $info->{weight};
 
1811   $main::lxdebug->leave_sub();
 
1815   $main::lxdebug->enter_sub();
 
1817   my $form     = $main::form;
 
1818   my %myconfig = %main::myconfig;
 
1820   if (!$form->{ordnumber} || !$form->{id}) {
 
1821     map { $form->{"ship_$_"} = 0 } (1..$form->{rowcount});
 
1822     $main::lxdebug->leave_sub();
 
1826   my $all_units = AM->retrieve_all_units();
 
1828   my %ship = DO->get_shipped_qty('type'  => ($form->{type} eq 'purchase_order') ? 'purchase' : 'sales',
 
1829                                  'oe_id' => $form->{id},);
 
1831   foreach my $i (1..$form->{rowcount}) {
 
1832     next unless ($form->{"id_${i}"});
 
1834     $form->{"ship_$i"} = 0;
 
1836     my $ship_entry = $ship{$form->{"id_$i"}};
 
1838     next if (!$ship_entry || ($ship_entry->{qty} <= 0));
 
1841       ($form->{simple_save} ? $form->{"qty_$i"} : $form->parse_amount(\%myconfig, $form->{"qty_$i"}))
 
1842       * $all_units->{$form->{"unit_$i"}}->{factor}
 
1843       / $all_units->{$form->{"partunit_$i"}}->{factor};
 
1845     $form->{"ship_$i"}  = min($rowqty, $ship_entry->{qty});
 
1846     $ship_entry->{qty} -= $form->{"ship_$i"};
 
1849   foreach my $i (1..$form->{rowcount}) {
 
1850     next unless ($form->{"id_${i}"});
 
1852     my $ship_entry = $ship{$form->{"id_$i"}};
 
1854     next if (!$ship_entry || ($ship_entry->{qty} <= 0.01));
 
1856     $form->{"ship_$i"} += $ship_entry->{qty};
 
1857     $ship_entry->{qty}  = 0;
 
1860   $main::lxdebug->leave_sub();
 
1863 sub _update_custom_variables {
 
1864   $main::lxdebug->enter_sub();
 
1866   my $form     = $main::form;
 
1868   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
 
1869   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
 
1871   $main::lxdebug->leave_sub();
 
1874 sub _render_custom_variables_inputs {
 
1875   $main::lxdebug->enter_sub(2);
 
1877   my $form     = $main::form;
 
1881   if (!$form->{CVAR_CONFIGS}->{IC}) {
 
1882     $main::lxdebug->leave_sub();
 
1886   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
 
1888   my $num_visible_cvars = 0;
 
1889   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
 
1890     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
 
1892     my $description = '';
 
1893     if ($cvar->{flag_editable} && $cvar->{valid}) {
 
1894       $num_visible_cvars++;
 
1895       $description = $cvar->{description} . ' ';
 
1898     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
 
1900     push @{ $params{ROW2} }, {
 
1901       line_break     => $num_visible_cvars == 1,
 
1902       description    => $description,
 
1905          hide_non_editable => 1,
 
1907          name_prefix       => 'ic_',
 
1908          name_postfix      => "_$params{row}",
 
1909          valid             => $cvar->{valid},
 
1910          value             => CVar->parse($::form->{$form_key}, $cvar),
 
1915   $main::lxdebug->leave_sub(2);
 
1918 sub _remove_billed_or_delivered_rows {
 
1921   croak "Missing parameter 'quantities'" if !$params{quantities};
 
1923   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
 
1926   my $removed_rows = 0;
 
1928   while ($row < $::form->{rowcount}) {
 
1930     next unless $::form->{"id_$row"};
 
1932     my $parts_id                      = $::form->{"id_$row"};
 
1933     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
 
1935     my $sub_qty                       = min($base_qty, $params{quantities}->{$parts_id});
 
1936     $params{quantities}->{$parts_id} -= $sub_qty;
 
1938     if (!$sub_qty || ($sub_qty != $base_qty)) {
 
1939       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
 
1940       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
 
1947   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
 
1948   $::form->{rowcount} -= $removed_rows;