16d51bba137fef31fd8089d1598ad3de060803f9
[kivitendo-erp.git] / bin / mozilla / io.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #############################################################################
7 # Veraendert 2005-01-05 - Marco Welter <mawe@linux-studio.de> - Neue Optik  #
8 #############################################################################
9 # SQL-Ledger, Accounting
10 # Copyright (c) 1998-2002
11 #
12 #  Author: Dieter Simader
13 #   Email: dsimader@sql-ledger.org
14 #     Web: http://www.sql-ledger.org
15 #
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #
30 #######################################################################
31 #
32 # common routines used in is, ir, oe
33 #
34 #######################################################################
35
36 use CGI;
37 use CGI::Ajax;
38 use List::Util qw(min max first);
39
40 use SL::CVar;
41 use SL::Common;
42 use SL::CT;
43 use SL::IC;
44 use SL::IO;
45
46 require "bin/mozilla/common.pl";
47
48 # any custom scripts for this one
49 if (-f "bin/mozilla/custom_io.pl") {
50   eval { require "bin/mozilla/custom_io.pl"; };
51 }
52 if (-f "bin/mozilla/$form->{login}_io.pl") {
53   eval { require "bin/mozilla/$form->{login}_io.pl"; };
54 }
55
56 1;
57
58 # end of main
59
60 # this is for our long dates
61 # $locale->text('January')
62 # $locale->text('February')
63 # $locale->text('March')
64 # $locale->text('April')
65 # $locale->text('May ')
66 # $locale->text('June')
67 # $locale->text('July')
68 # $locale->text('August')
69 # $locale->text('September')
70 # $locale->text('October')
71 # $locale->text('November')
72 # $locale->text('December')
73
74 # this is for our short month
75 # $locale->text('Jan')
76 # $locale->text('Feb')
77 # $locale->text('Mar')
78 # $locale->text('Apr')
79 # $locale->text('May')
80 # $locale->text('Jun')
81 # $locale->text('Jul')
82 # $locale->text('Aug')
83 # $locale->text('Sep')
84 # $locale->text('Oct')
85 # $locale->text('Nov')
86 # $locale->text('Dec')
87 use SL::IS;
88 use SL::PE;
89 use SL::AM;
90 use Data::Dumper;
91
92 sub _check_io_auth {
93   $auth->assert('part_service_assembly_edit   | vendor_invoice_edit       | sales_order_edit    | invoice_edit |' .
94                 'request_quotation_edit       | sales_quotation_edit      | purchase_order_edit | ' .
95                 'purchase_delivery_order_edit | sales_delivery_order_edit');
96 }
97
98 ########################################
99 # Eintrag fuer Version 2.2.0 geaendert #
100 # neue Optik im Rechnungsformular      #
101 ########################################
102 sub display_row {
103   $lxdebug->enter_sub();
104
105   _check_io_auth();
106
107   my $numrows = shift;
108
109   my ($readonly, $stock_in_out, $stock_in_out_title);
110
111   my $is_purchase        = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
112   my $show_min_order_qty =  first { $_ eq $form->{type} } qw(request_quotation purchase_order);
113   my $is_delivery_order  = $form->{type} =~ /_delivery_order$/;
114   my $is_s_p_order       = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
115
116   if ($is_delivery_order) {
117     $readonly             = ' readonly' if ($form->{closed});
118
119     if ($form->{type} eq 'sales_delivery_order') {
120       $stock_in_out_title = $locale->text('Release From Stock');
121       $stock_in_out       = 'out';
122     } else {
123       $stock_in_out_title = $locale->text('Transfer To Stock');
124       $stock_in_out       = 'in';
125     }
126
127     retrieve_partunits();
128   }
129
130   # column_index
131   my @header_sort = qw(runningnumber partnumber description ship qty unit sellprice_pg sellprice discount linetotal);
132   my @HEADER = (
133     {  id => 'runningnumber', width => 5,     value => $locale->text('No.'),                  display => 1, },
134     {  id => 'partnumber',    width => 8,     value => $locale->text('Number'),               display => 1, },
135     {  id => 'description',   width => 30,    value => $locale->text('Part Description'),     display => 1, },
136     {  id => 'ship',          width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
137     {  id => 'qty',           width => 5,     value => $locale->text('Qty'),                  display => 1, },
138     {  id => 'price_factor',  width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
139     {  id => 'unit',          width => 5,     value => $locale->text('Unit'),                 display => 1, },
140     {  id => 'license',       width => 10,    value => $locale->text('License'),              display => 0, },
141     {  id => 'serialnr',      width => 10,    value => $locale->text('Serial No.'),           display => 0, },
142     {  id => 'projectnr',     width => 10,    value => $locale->text('Project'),              display => 0, },
143     {  id => 'sellprice',     width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
144     {  id => 'sellprice_pg',  width => 8,    value => $locale->text('Pricegroup'),           display => ($form->{type} =~ /^sales_/) && !$is_delivery_order,  },
145     {  id => 'discount',      width => 5,     value => $locale->text('Discount'),             display => ($form->{vc} eq 'customer') && !$is_delivery_order, },
146     {  id => 'linetotal',     width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
147     {  id => 'bin',           width => 10,    value => $locale->text('Bin'),                  display => 0, },
148     {  id => 'stock_in_out',  width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
149   ); 
150   my @column_index = map { $_->{id} } grep { $_->{display} } @HEADER;
151
152   # cache units
153   my $all_units       = AM->retrieve_units(\%myconfig, $form);
154
155   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
156
157   my $colspan = scalar @column_index;
158
159   $form->{invsubtotal} = 0;
160   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
161
162   # about details 
163   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
164   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
165   # /about details
166
167   # translations, unused commented out
168 #  $runningnumber = $locale->text('No.');
169   $deliverydate  = $locale->text('Delivery Date');
170   $serialnumber  = $locale->text('Serial No.');
171   $projectnumber = $locale->text('Project');
172 #  $partsgroup    = $locale->text('Group');
173   $reqdate       = $locale->text('Reqdate');
174   $deliverydate  = $locale->text('Required by');
175
176   # special alignings
177   my %align  = map { $_ => 'right' } qw(qty ship right sellprice_pg discount linetotal stock_in_out);
178   my %nowrap = map { $_ => 1 }       qw(description unit);
179
180   $form->{marge_total}           = 0;
181   $form->{sellprice_total}       = 0;
182   $form->{lastcost_total}        = 0;
183   my %projectnumber_labels = ();
184   my @projectnumber_values = ("");
185
186   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
187     push(@projectnumber_values, $item->{"id"});
188     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
189   }
190
191   _update_part_information();
192   _update_ship() if ($is_s_p_order);
193
194   # rows
195   for $i (1 .. $numrows) {
196
197     # undo formatting
198     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(qty discount sellprice price_new price_old) unless ($form->{simple_save});
199
200 # unit begin
201     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
202     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
203
204     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
205         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
206       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
207     }
208     # adjust prices by unit, ignore if pricegroup changed
209     if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) {
210         $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
211         $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
212     }
213     my $this_unit = $form->{"unit_$i"};
214     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
215     $this_unit  ||= "kg";
216
217     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
218       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
219       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
220
221       $column_data{price_factor} =
222         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
223                              '-default' => $form->{"price_factor_id_$i"},
224                              '-values'  => \@values,
225                              '-labels'  => \%labels,
226                              '-style'   => 'width:90px'));
227     } else {
228       $column_data{price_factor} = '&nbsp;';
229     }
230
231     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
232 # / unit ending
233
234     $form->{"sellprice_$i"} =~ /\.(\d+)/;
235     $decimalplaces = max 2, length $1;
236
237     $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
238     $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
239     $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
240
241     $column_data{runningnumber} = $cgi->textfield(-name => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
242     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
243     $column_data{description} = ((($rows = $form->numtextrows($form->{"description_$i"}, 30, 6)) > 1) # if description is too large, use a textbox instead
244                                 ? $cgi->textarea( -name => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
245                                 : $cgi->textfield(-name => "description_$i",   -size => 30, -value => $form->{"description_$i"}))
246                                 . $cgi->button(-value => $locale->text('L'), -onClick => "set_longdescription_window('longdescription_$i')");
247
248     $form->{"qty_$i"} =~ /\.(\d+)/;
249     my $qty_dec = length $1;
250
251     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
252     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_window('qty_$i','alu_$i', 'formel_$i', $i)", -value => $locale->text('*/'))
253                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"}) . $cgi->hidden("-name" => "alu_$i", "-value" => $form->{"alu_$i"})
254       if $form->{"formel_$i"};
255
256     $column_data{ship} = '';
257     if ($form->{"id_$i"}) {
258       my $ship_qty        = $form->{"ship_$i"} * 1;
259       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
260       $ship_qty          /= $all_units->{$form->{"unit_$i"}}->{factor};
261
262       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"};
263     }
264
265     # build in drop down list for pricesgroups
266     if ($form->{"prices_$i"}) {
267       $column_data{sellprice_pg} = qq|<select name="sellprice_pg_$i" style="width: 8em">$form->{"prices_$i"}</select>|;
268       $column_data{sellprice}    = $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => 'check_right_number_format(this)', -value =>
269                                    (($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})
270                                       ? $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces)
271                                       : $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces)));
272     } else {
273       # for last row and report
274       # set pricegroup drop down list from report menu
275       if ($form->{"sellprice_$i"} != 0) {
276         $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"};
277         my $default_option           = $form->{"sellprice_$i"}.'--'.$form->{"pricegroup_id_$i"};
278         $column_data{sellprice_pg}   = NTI($cgi->popup_menu("sellpricepg_$i", [ $default_option ], $default_option, { $default_option => $form->{"pricegroup_$i"} || '' }));
279       } else {
280         $column_data{sellprice_pg} = qq|&nbsp;|;
281       }
282       $column_data{sellprice} = $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value =>
283                                                 $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces));
284     }
285     $column_data{discount}    = $cgi->textfield(-name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}));
286     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
287     $column_data{bin}         = $form->{"bin_$i"};
288
289     if ($is_delivery_order) {
290       $column_data{stock_in_out} = (!$form->{"assembly_$i"} && $form->{"inventory_accno_$i"}) ? calculate_stock_in_out($i) : '&nbsp;';
291     }
292
293     my @ROW1 = map { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} }, @column_index;
294
295     # second row
296     my @ROW2 = ();
297     push @ROW2, { value => qq|<b>$serialnumber</b> <input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">| } 
298       if $form->{type} !~ /_quotation/;
299     push @ROW2, { value => qq|<b>$projectnumber</b> | . NTI($cgi->popup_menu('-name'  => "project_id_$i",        '-values'  => \@projectnumber_values,
300                                                                              '-labels' => \%projectnumber_labels, '-default' => $form->{"project_id_$i"})) };
301     push @ROW2, { value => qq|<b>$reqdate</b> <input name="reqdate_$i" size="11" onBlur="check_right_date_format(this)" value="$form->{"reqdate_$i"}">| }
302       if ($form->{type} =~ /order/ ||  $form->{type} =~ /invoice/);
303     push @ROW2, { value => sprintf qq|<b>%s</b>&nbsp;<input type="checkbox" name="subtotal_$i" value="1" %s>|, 
304                    $locale->text('Subtotal'), $form->{"subtotal_$i"} ? 'checked' : '' };
305
306 # begin marge calculations
307     my $marge_color;
308     my $real_sellprice     = ($form->{"sellprice_$i"} - $discount) / $price_factor;
309     my $marge_price_factor = $form->{"marge_price_factor_$i"} * 1 || 1;
310
311     $form->{"lastcost_$i"} *= 1;
312     $form->{"marge_percent_$i"} = 0;
313
314     if ($real_sellprice && ($form->{"qty_$i"} * 1)) {
315       $form->{"marge_percent_$i"}     = ($real_sellprice - $form->{"lastcost_$i"} / $marge_price_factor) * 100 / $real_sellprice;
316       $myconfig{marge_percent_warn} ||= 15;
317       $marge_color                    = 'color="#ff0000"' if $form->{"id_$i"} && ($form->{"marge_percent_$i"} < (1 * $myconfig{marge_percent_warn}));
318     }
319
320     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
321     $form->{"marge_absolut_$i"}  = ($real_sellprice - $form->{"lastcost_$i"} / $marge_price_factor) * $form->{"qty_$i"} * $marge_adjust_credit_note;
322     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
323     $form->{"lastcost_total"}   += $form->{"lastcost_$i"} * $form->{"qty_$i"} / $marge_price_factor;
324     $form->{"sellprice_total"}  += $real_sellprice * $form->{"qty_$i"};
325
326     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
327
328     push @ROW2, { value => sprintf qq|<font %s><b>%s</b> %s &nbsp;%s%% </font> &nbsp;<b>%s</b> %s &nbsp;<b>%s</b> %s|,
329                    $marge_color, $locale->text('Ertrag'),$form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"},
330                    $locale->text('LP'), $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2),
331                    $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, 2) }
332       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/) && !$is_delivery_order;
333 # / marge calculations ending
334
335     my @hidden_vars;
336
337     if ($is_delivery_order) {
338       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount);
339       push @hidden_vars, qw(sellprice discount price_factor_id);
340       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
341     }
342
343     my @HIDDENS = map { value => $_}, (
344           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
345           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
346           map { ($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } map { $_."_$i" } 
347             (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes
348                 income_accno expense_accno listprice assembly taxaccounts ordnumber transdate cusordnumber
349                 longdescription basefactor marge_absolut marge_percent marge_price_factor lastcost), @hidden_vars)
350     );
351
352     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
353
354     $form->{invsubtotal} += $linetotal;
355
356     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, };
357   }
358
359   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
360                                                        HEADER => \@HEADER,
361                                                      });
362
363   if (0 != ($form->{sellprice_total} * 1)) {
364     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
365   }
366
367   $lxdebug->leave_sub();
368 }
369
370 ##################################################
371 # build html-code for pricegroups in variable $form->{prices_$j}
372
373 sub set_pricegroup {
374   $lxdebug->enter_sub();
375
376   _check_io_auth();
377
378   my $rowcount = shift;
379   for $j (1 .. $rowcount) {
380     next unless $form->{PRICES}{$j};
381     # build drop down list for pricegroups
382     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
383     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} } 
384                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
385
386     foreach $item (@{ $form->{PRICES}{$j} }) {
387       # set new selectedpricegroup_id and prices for "Preis"
388       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
389       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
390       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
391     }
392   }
393   $lxdebug->leave_sub();
394 }
395
396 sub select_item {
397   $lxdebug->enter_sub();
398
399   _check_io_auth();
400
401   @column_index = qw(ndx partnumber description onhand unit sellprice);
402
403   $column_data{ndx}        = qq|<th>&nbsp;</th>|;
404   $column_data{partnumber} =
405     qq|<th class="listheading">| . $locale->text('Number') . qq|</th>|;
406   $column_data{description} =
407     qq|<th class="listheading">| . $locale->text('Part Description') . qq|</th>|;
408   $column_data{sellprice} =
409     qq|<th class="listheading">| . $locale->text('Price') . qq|</th>|;
410   $column_data{onhand} =
411     qq|<th class="listheading">| . $locale->text('Qty') . qq|</th>|;
412   $column_data{unit} =
413     qq|<th class="listheading">| . $locale->text('Unit') . qq|</th>|;
414   # list items with radio button on a form
415   $form->header;
416
417   $title   = $locale->text('Select from one of the items below');
418   $colspan = $#column_index + 1;
419
420   print qq|
421   <body>
422
423 <form method="post" action="$form->{script}">
424
425 <table width="100%">
426   <tr>
427     <th class="listtop" colspan="$colspan">$title</th>
428   </tr>
429   <tr height="5"></tr>
430   <tr class="listheading">|;
431
432   map { print "\n$column_data{$_}" } @column_index;
433
434   print qq|</tr>|;
435
436   my $i = 0;
437   foreach $ref (@{ $form->{item_list} }) {
438     $checked = ($i++) ? "" : "checked";
439
440     if ($lizenzen) {
441       if ($ref->{inventory_accno} > 0) {
442         $ref->{"lizenzen"} = qq|<option></option>|;
443         foreach $item (@{ $form->{LIZENZEN}{ $ref->{"id"} } }) {
444           $ref->{"lizenzen"} .=
445             qq|<option value=\"$item->{"id"}\">$item->{"licensenumber"}</option>|;
446         }
447         $ref->{"lizenzen"} .= qq|<option value="-1">Neue Lizenz</option>|;
448         $ref->{"lizenzen"} =~ s/\"/&quot;/g;
449       }
450     }
451
452     map { $ref->{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
453
454     my $display_sellprice  = $ref->{sellprice} * (1 - $form->{tradediscount});
455     $display_sellprice    /= $ref->{price_factor} if ($ref->{price_factor});
456     $display_sellprice     = $form->format_amount(\%myconfig, $display_sellprice, 2);
457
458     $column_data{ndx} =
459       qq|<td><input name="ndx" class="radio" type="radio" value="$i" $checked></td>|;
460     $column_data{partnumber} =
461       qq|<td><input name="new_partnumber_$i" type="hidden" value="$ref->{partnumber}">$ref->{partnumber}</td>|;
462     $column_data{description} =
463       qq|<td><input name="new_description_$i" type="hidden" value="$ref->{description}">$ref->{description}</td>|;
464     $column_data{sellprice} =
465       qq|<td align="right"><input name="new_sellprice_$i" type="hidden" value="$ref->{sellprice}">|
466       . $display_sellprice
467       . qq|</td>|;
468     $column_data{onhand} =
469       qq|<td align="right"><input name="new_onhand_$i" type="hidden" value="$ref->{onhand}">|
470       . $form->format_amount(\%myconfig, $ref->{onhand}, '', "&nbsp;")
471       . qq|</td>|;
472     $column_data{unit} =
473       qq|<td>$ref->{unit}</td>|;
474     $j++;
475     $j %= 2;
476     print qq|
477 <tr class=listrow$j>|;
478
479     map { print "\n$column_data{$_}" } @column_index;
480
481     print("</tr>\n");
482
483     my @new_fields =
484       qw(bin listprice inventory_accno income_accno expense_accno unit weight
485          assembly taxaccounts partsgroup formel longdescription not_discountable
486          part_payment_id partnotes id lastcost price_factor_id price_factor);
487     push(@new_fields, "lizenzen") if ($lizenzen);
488
489     print join "\n", map { $cgi->hidden("-name" => "new_${_}_$i", "-value" => $ref->{$_}) } @new_fields;
490     print "\n";
491   }
492
493   print qq|
494 <tr><td colspan="8"><hr size="3" noshade></td></tr>
495 </table>
496
497 <input name="lastndx" type="hidden" value="$i">
498
499 |;
500
501   # delete action variable
502   map { delete $form->{$_} } qw(action item_list header);
503
504   # save all other form variables
505   foreach $key (keys %${form}) {
506     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
507     $form->{$key} =~ s/\"/&quot;/g;
508     print qq|<input name="$key" type="hidden" value="$form->{$key}">\n|;
509   }
510
511   print qq|
512 <input type="hidden" name="nextsub" value="item_selected">
513
514 <br>
515 <input class="submit" type="submit" name="action" value="|
516     . $locale->text('Continue') . qq|">
517 </form>
518
519 </body>
520 </html>
521 |;
522
523   $lxdebug->leave_sub();
524 }
525
526 sub item_selected {
527   $lxdebug->enter_sub();
528
529   _check_io_auth();
530
531   # replace the last row with the checked row
532   $i = $form->{rowcount};
533   $i = $form->{assembly_rows} if ($form->{item} eq 'assembly');
534
535   # index for new item
536   $j = $form->{ndx};
537
538   #sk
539   #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
540   #$form->{"sellprice_$i"} = $form->{"sellprice_$i"};
541
542   # if there was a price entered, override it
543   $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
544
545   my @new_fields =
546     qw(id partnumber description sellprice listprice inventory_accno
547        income_accno expense_accno bin unit weight assembly taxaccounts
548        partsgroup formel longdescription not_discountable partnotes lastcost
549        price_factor_id price_factor);
550
551   map { $form->{"${_}_$i"} = $form->{"new_${_}_$j"} } @new_fields;
552
553   $form->{"marge_price_factor_$i"} = $form->{"new_price_factor_$j"};
554
555   if ($form->{"part_payment_id_$i"} ne "") {
556     $form->{payment_id} = $form->{"part_payment_id_$i"};
557   }
558
559   if ($lizenzen) {
560     map { $form->{"${_}_$i"} = $form->{"new_${_}_$j"} } qw(lizenzen);
561   }
562
563   ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
564   $dec           = length $dec;
565   $decimalplaces = ($dec > 2) ? $dec : 2;
566
567   if ($sellprice) {
568     $form->{"sellprice_$i"} = $sellprice;
569   } else {
570
571     # if there is an exchange rate adjust sellprice
572     if (($form->{exchangerate} * 1) != 0) {
573       $form->{"sellprice_$i"} /= $form->{exchangerate};
574       $form->{"sellprice_$i"} =
575         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
576     }
577   }
578
579   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
580     qw(sellprice listprice weight);
581
582   $form->{sellprice} += ($form->{"sellprice_$i"} * $form->{"qty_$i"});
583   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
584   
585   if ($form->{"not_discountable_$i"}) {
586     $form->{"discount_$i"} = 0;
587   }
588
589   $amount =
590     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
591     $form->{"qty_$i"};
592   map { $form->{"${_}_base"} += $amount }
593     (split / /, $form->{"taxaccounts_$i"});
594   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
595     $form->{"taxaccounts_$i"}
596     if !$form->{taxincluded};
597
598   $form->{creditremaining} -= $amount;
599
600   $form->{"runningnumber_$i"} = $i;
601
602   # delete all the new_ variables
603   for $i (1 .. $form->{lastndx}) {
604     map { delete $form->{"new_${_}_$i"} } @new_fields;
605   }
606
607   map { delete $form->{$_} } qw(ndx lastndx nextsub);
608
609   # format amounts
610   map {
611     $form->{"${_}_$i"} =
612       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
613   } qw(sellprice listprice) if $form->{item} ne 'assembly';
614
615   # get pricegroups for parts
616   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
617
618   # build up html code for prices_$i
619   set_pricegroup($form->{rowcount});
620
621   &display_form;
622
623   $lxdebug->leave_sub();
624 }
625
626 sub new_item {
627   $lxdebug->enter_sub();
628
629   _check_io_auth();
630
631   my $price_key = ($form->{type} =~ m/request_quotation|purchase_order/) || ($form->{script} eq 'ir.pl') ? 'lastcost' : 'sellprice';
632
633   # change callback
634   $form->{old_callback} = $form->escape($form->{callback}, 1);
635   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
636
637   # save all form variables except action in a previousform variable
638   my $previousform = join '&', map { my $value = $form->{$_}; $value =~ s/&/%26/; "$_=$value" } grep { !/action/ } keys %$form;
639
640   push @HIDDENS,      { 'name' => 'previousform', 'value' => $form->escape($previousform, 1) };
641   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc);
642   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit);
643   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
644   push @HIDDENS,      { 'name' => $price_key,     'value' => $form->parse_amount(\%myconfig, $form->{"sellprice_$form->{rowcount}"}) };
645   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{"longdescription_$form->{rowcount}"} };
646
647   $form->header();
648   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
649
650   $lxdebug->leave_sub();
651 }
652
653 sub check_form {
654   $lxdebug->enter_sub();
655
656   _check_io_auth();
657
658   my @a     = ();
659   my $count = 0;
660
661   my @flds = qw(id partnumber description qty ship sellprice unit
662                 discount inventory_accno income_accno expense_accno listprice
663                 taxaccounts bin assembly weight projectnumber project_id
664                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
665                 not_discountable shop ve gv buchungsgruppen_id language_values
666                 sellprice_pg pricegroup_old price_old price_new unit_old ordnumber
667                 transdate longdescription basefactor marge_total marge_percent
668                 marge_price_factor lastcost price_factor_id
669                 stock_out stock_in);
670
671   # remove any makes or model rows
672   if ($form->{item} eq 'part') {
673     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
674       qw(listprice sellprice lastcost weight rop);
675
676   } elsif ($form->{item} eq 'assembly') {
677
678     $form->{sellprice} = 0;
679     $form->{weight}    = 0;
680     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
681       qw(listprice rop stock);
682
683     @flds =
684       qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup);
685
686     for my $i (1 .. ($form->{assembly_rows} - 1)) {
687       if ($form->{"qty_$i"}) {
688         push @a, {};
689         my $j = $#a;
690
691         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
692
693         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
694
695         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
696
697         $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"});
698         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"});
699         $count++;
700       }
701     }
702
703     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
704
705     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
706     $form->{assembly_rows} = $count;
707
708   } elsif ($form->{item} eq 'service') {
709     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(listprice sellprice lastcost);
710
711   } else {
712
713     # this section applies to invoices and orders
714     # remove any empty numbers
715     if ($form->{rowcount}) {
716       for my $i (1 .. $form->{rowcount} - 1) {
717         if ($form->{"partnumber_$i"}) {
718           push @a, {};
719           my $j = $#a;
720
721           map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
722           $count++;
723           if ($lizenzen) {
724             if ($form->{"licensenumber_$i"} == -1) {
725               &new_license($i);
726               exit;
727             }
728           }
729         }
730       }
731
732       $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
733       $form->{rowcount} = $count;
734
735       $form->{creditremaining} -= &invoicetotal;
736
737     }
738   }
739
740   #sk
741   # if pricegroups
742   if (   $form->{type} =~ (/sales_quotation/)
743       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
744       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
745       or ($form->{type} =~ /sales_order/)) {
746
747     # get pricegroups for parts
748     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
749
750     # build up html code for prices_$i
751     set_pricegroup($form->{rowcount});
752
753   }
754
755   &display_form;
756
757   $lxdebug->leave_sub();
758 }
759
760 sub invoicetotal {
761   $lxdebug->enter_sub();
762
763   _check_io_auth();
764
765   $form->{oldinvtotal} = 0;
766
767   # add all parts and deduct paid
768   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
769
770   my ($amount, $sellprice, $discount, $qty);
771
772   for my $i (1 .. $form->{rowcount}) {
773     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
774     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
775     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
776
777     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
778
779     $amount = $sellprice * (1 - $discount / 100) * $qty;
780     map { $form->{"${_}_base"} += $amount }
781       (split (/ /, $form->{"taxaccounts_$i"}));
782     $form->{oldinvtotal} += $amount;
783   }
784
785   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
786     split(/ /, $form->{taxaccounts})
787     if !$form->{taxincluded};
788
789   $form->{oldtotalpaid} = 0;
790   for $i (1 .. $form->{paidaccounts}) {
791     $form->{oldtotalpaid} += $form->{"paid_$i"};
792   }
793
794   $lxdebug->leave_sub();
795
796   # return total
797   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
798 }
799
800 sub validate_items {
801   $lxdebug->enter_sub();
802
803   _check_io_auth();
804
805   # check if items are valid
806   if ($form->{rowcount} == 1) {
807     &update;
808     exit;
809   }
810
811   for $i (1 .. $form->{rowcount} - 1) {
812     $form->isblank("partnumber_$i",
813                    $locale->text('Number missing in Row') . " $i");
814   }
815
816   $lxdebug->leave_sub();
817 }
818
819 sub order {
820   $lxdebug->enter_sub();
821
822   _check_io_auth();
823
824   if ($form->{second_run}) {
825     $form->{print_and_post} = 0;
826   }
827   $form->{ordnumber} = $form->{invnumber};
828
829   $form->{old_employee_id} = $form->{employee_id};
830   $form->{old_salesman_id} = $form->{salesman_id};
831
832   map { delete $form->{$_} } qw(id printed emailed queued);
833   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
834     $form->{title} = $locale->text('Add Purchase Order');
835     $form->{vc}    = 'vendor';
836     $form->{type}  = 'purchase_order';
837     $buysell       = 'sell';
838   }
839   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
840     $form->{title} = $locale->text('Add Sales Order');
841     $form->{vc}    = 'customer';
842     $form->{type}  = 'sales_order';
843     $buysell       = 'buy';
844   }
845   $form->{script} = 'oe.pl';
846
847   $form->{shipto} = 1;
848
849   $form->{rowcount}--;
850
851   $form->{cp_id} *= 1;
852
853   require "bin/mozilla/$form->{script}";
854   my $script = $form->{"script"};
855   $script =~ s|.*/||;
856   $script =~ s|.pl$||;
857   $locale = new Locale($language, $script);
858
859   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
860
861   $currency = $form->{currency};
862
863   &order_links;
864
865   $form->{currency}     = $currency;
866   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
867   $form->{exchangerate} = $form->{forex} || '';
868
869   for $i (1 .. $form->{rowcount}) {
870     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
871             if ($form->{"${_}_${i}"}) }
872         qw(ship qty sellprice listprice basefactor));
873   }
874
875   &prepare_order;
876   &display_form;
877
878   $lxdebug->leave_sub();
879 }
880
881 sub quotation {
882   $lxdebug->enter_sub();
883
884   _check_io_auth();
885
886   if ($form->{second_run}) {
887     $form->{print_and_post} = 0;
888   }
889   map { delete $form->{$_} } qw(id printed emailed queued);
890
891   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
892     $form->{title} = $locale->text('Add Request for Quotation');
893     $form->{vc}    = 'vendor';
894     $form->{type}  = 'request_quotation';
895     $buysell       = 'sell';
896   }
897   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
898     $form->{title} = $locale->text('Add Quotation');
899     $form->{vc}    = 'customer';
900     $form->{type}  = 'sales_quotation';
901     $buysell       = 'buy';
902   }
903
904   $form->{cp_id} *= 1;
905
906   $form->{script} = 'oe.pl';
907
908   $form->{shipto} = 1;
909
910   $form->{rowcount}--;
911
912   require "bin/mozilla/$form->{script}";
913
914   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
915
916   $currency = $form->{currency};
917
918   &order_links;
919
920   $form->{currency}     = $currency;
921   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
922   $form->{exchangerate} = $form->{forex} || '';
923
924   for $i (1 .. $form->{rowcount}) {
925     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
926                                                      $form->{"${_}_${i}"})
927             if ($form->{"${_}_${i}"}) }
928         qw(ship qty sellprice listprice basefactor));
929   }
930
931   &prepare_order;
932   &display_form;
933
934   $lxdebug->leave_sub();
935 }
936
937 sub request_for_quotation {
938   quotation();
939 }
940
941 sub edit_e_mail {
942   $lxdebug->enter_sub();
943
944   _check_io_auth();
945
946   if ($form->{second_run}) {
947     $form->{print_and_post} = 0;
948     $form->{resubmit}       = 0;
949   }
950
951   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
952
953   if ($form->{"cp_id"} && !$form->{"email"}) {
954     CT->get_contact(\%myconfig, $form);
955     $form->{"email"} = $form->{"cp_email"};
956   }
957
958   $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
959
960   $form->{oldmedia} = $form->{media};
961   $form->{media}    = "email";
962
963   my $attachment_filename = $form->generate_attachment_filename();
964   my $subject             = $form->{subject} || $form->generate_email_subject();
965
966   $form->{"fokus"} = $form->{"email"} ? "Form.subject" : "Form.email";
967   $form->header;
968
969   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
970   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override login password);
971   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
972   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
973
974   print $form->parse_html_template('generic/edit_email',
975                                    { title           => $title,
976                                      a_filename      => $attachment_filename,
977                                      subject         => $subject,
978                                      _print_options_ => print_options('inline' => 1),
979                                      HIDDEN          => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
980                                      SHOW_BCC        => $myconfig{role} eq 'admin' });
981
982   $lxdebug->leave_sub();
983 }
984
985 sub send_email {
986   $lxdebug->enter_sub();
987
988   _check_io_auth();
989
990   my $callback = $form->{script} . "?action=edit";
991   map({ $callback .= "\&${_}=" . E($form->{$_}); } qw(type id));
992
993   print_form("return");
994
995   Common->save_email_status(\%myconfig, $form);
996
997   $form->{callback} = $callback;
998   $form->redirect();
999
1000   $lxdebug->leave_sub();
1001 }
1002
1003 # generate the printing options displayed at the bottom of oe and is forms.
1004 # this function will attempt to guess what type of form is displayed, and will generate according options
1005 #
1006 # about the coding: 
1007 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
1008 # the opthash function builds hashrefs which are then pieced together for the template arrays.
1009 # unneeded options are "undef"ed out, and then grepped out. 
1010 #
1011 # the inline options is untested, but intended to be used later in metatemplating
1012 sub print_options {
1013   $lxdebug->enter_sub();
1014
1015   _check_io_auth();
1016
1017   my %options = @_;
1018
1019   # names 3 parameters and returns a hashref, for use in templates
1020   sub opthash { +{ value => shift, selected => shift, oname => shift } }
1021   (@FORMNAME, @FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
1022
1023   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
1024   $form->{sendmode}   = "attachment";
1025   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
1026   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
1027   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
1028   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
1029                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
1030
1031   $form->{PD}{ $form->{formname} } = "selected";
1032   $form->{DF}{ $form->{format} }   = "selected";
1033   $form->{OP}{ $form->{media} }    = "selected";
1034   $form->{SM}{ $form->{formname} } = "selected";
1035
1036   push @FORMNAME, grep $_,
1037     ($form->{type} eq 'purchase_order') ? (
1038       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
1039       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List')) 
1040     ) : undef,
1041     ($form->{type} eq 'credit_note') ?
1042       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
1043     ($form->{type} eq 'sales_order') ? (
1044       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
1045       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
1046     ) : undef,
1047     ($form->{type} =~ /sales_quotation$/) ?
1048       opthash('sales_quotation',     $form->{PD}{sales_quotation},     $locale->text('Quotation')) : undef,
1049     ($form->{type} =~ /request_quotation$/) ?
1050       opthash('request_quotation',   $form->{PD}{request_quotation},   $locale->text('Request for Quotation')) : undef,
1051     ($form->{type} eq 'invoice') ? (
1052       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
1053       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
1054     ) : undef,
1055     ($form->{type} eq 'invoice' && $form->{storno}) ? (
1056       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
1057       opthash("storno_packing_list", $form->{PD}{storno_packing_list}, $locale->text('Storno Packing List')) 
1058     ) : undef,
1059     ($form->{type} =~ /_delivery_order$/) ? (
1060       opthash($form->{type},         $form->{PD}{$form->{type}},       $locale->text('Delivery Order')),
1061       opthash('pick_list',           $form->{PD}{pick_list},           $locale->text('Pick List')),
1062     ) : undef;
1063     ($form->{type} eq 'credit_note') ?
1064       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef;
1065
1066   push @SENDMODE, 
1067     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
1068     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
1069       if ($form->{media} eq 'email');
1070
1071   push @MEDIA, grep $_,
1072       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
1073     (scalar @{ $form->{printers} } && $latex_templates) ?
1074       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
1075     ($latex_templates && !$options{no_queue}) ?
1076       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
1077         if ($form->{media} ne 'email');
1078
1079   push @FORMAT, grep $_,
1080     ($opendocument_templates && $openofficeorg_writer_bin && $xvfb_bin && (-x $openofficeorg_writer_bin) && (-x $xvfb_bin)
1081      && !$options{no_opendocument_pdf}) ?
1082       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
1083     ($latex_templates) ?
1084       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
1085     ($latex_templates && !$options{no_postscript}) ?
1086       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
1087     (!$options{no_html}) ?
1088       opthash("html", $form->{DF}{html}, "HTML") : undef,
1089     ($opendocument_templates && !$options{no_opendocument}) ?
1090       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef;
1091
1092   push @LANGUAGE_ID, 
1093     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
1094       if (ref $form->{languages} eq 'ARRAY');
1095
1096   push @PRINTER_ID, 
1097     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
1098       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
1099
1100   @SELECTS = map { sname => lc $_, DATA => \@$_, show => !$options{"hide_" . lc($_)} && scalar @$_ }, qw(FORMNAME LANGUAGE_ID FORMAT SENDMODE MEDIA PRINTER_ID);
1101
1102   my %dont_display_groupitems = (
1103     'dunning' => 1,
1104     );
1105
1106   %template_vars = (
1107     display_copies       => scalar @{ $form->{printers} } && $latex_templates && $form->{media} ne 'email',
1108     display_remove_draft => (!$form->{id} && $form->{draft_id}),
1109     display_groupitems   => !$dont_display_groupitems{$form->{type}},
1110     groupitems_checked   => $form->{groupitems} ? "checked" : '',
1111     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
1112   );
1113
1114   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
1115
1116   if ($options{inline}) {
1117     $lxdebug->leave_sub();
1118     return $print_options;
1119   }
1120
1121   print $print_options;
1122
1123   $lxdebug->leave_sub();
1124 }
1125
1126 sub print {
1127   $lxdebug->enter_sub();
1128
1129   _check_io_auth();
1130
1131   if ($form->{print_nextsub}) {
1132     call_sub($form->{print_nextsub});
1133     $lxdebug->leave_sub();
1134     return;
1135   }
1136
1137   # if this goes to the printer pass through
1138   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1139     $form->error($locale->text('Select postscript or PDF!'))
1140       if ($form->{format} !~ /(postscript|pdf)/);
1141
1142     $old_form = new Form;
1143     map { $old_form->{$_} = $form->{$_} } keys %$form;
1144   }
1145
1146   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1147     if ($form->{formname} eq "proforma") {
1148       $form->{proforma} = 1;
1149     }
1150     $form->{print_and_save} = 1;
1151     my $formname = $form->{formname};
1152     &save();
1153     $form->{formname} = $formname;
1154     &edit();
1155     exit;
1156   }
1157
1158   &print_form($old_form);
1159
1160   $lxdebug->leave_sub();
1161 }
1162
1163 sub print_form {
1164   $lxdebug->enter_sub();
1165
1166   _check_io_auth();
1167
1168   my ($old_form) = @_;
1169
1170   $inv       = "inv";
1171   $due       = "due";
1172   $numberfld = "invnumber";
1173
1174   $display_form =
1175     ($form->{display_form}) ? $form->{display_form} : "display_form";
1176
1177   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1178   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1179
1180   if ($form->{formname} eq "invoice") {
1181     $form->{label} = $locale->text('Invoice');
1182   }
1183   if ($form->{formname} eq "packing_list") {
1184
1185     # this is from an invoice
1186     $form->{label} = $locale->text('Packing List');
1187   }
1188   if ($form->{formname} eq 'sales_order') {
1189     $inv                  = "ord";
1190     $due                  = "req";
1191     $form->{"${inv}date"} = $form->{transdate};
1192     $form->{label}        = $locale->text('Confirmation');
1193     $numberfld            = "sonumber";
1194     $order                = 1;
1195   }
1196
1197   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1198     $inv                  = "inv";
1199     $due                  = "due";
1200     $form->{"${inv}date"} = $form->{invdate};
1201     $form->{label}        = $locale->text('Proforma Invoice');
1202     $numberfld            = "sonumber";
1203     $order                = 0;
1204   }
1205
1206   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1207     $inv                  = "inv";
1208     $due                  = "due";
1209     $form->{"${inv}date"} = $form->{transdate};
1210     $form->{"invdate"}    = $form->{transdate};
1211     $form->{invnumber}    = $form->{ordnumber};
1212     $form->{label}        = $locale->text('Proforma Invoice');
1213     $numberfld            = "sonumber";
1214     $order                = 1;
1215   }
1216
1217   if ($form->{formname} eq 'packing_list' && $form->{type} ne 'invoice') {
1218
1219     # we use the same packing list as from an invoice
1220     $inv = "ord";
1221     $due = "req";
1222     $form->{invdate} = $form->{"${inv}date"} = $form->{transdate};
1223     $form->{label} = $locale->text('Packing List');
1224     $order = 1;
1225     # set invnumber for template packing_list 
1226     $form->{invnumber}   = $form->{ordnumber};
1227   }
1228   if ($form->{formname} eq 'purchase_order') {
1229     $inv                  = "ord";
1230     $due                  = "req";
1231     $form->{"${inv}date"} = $form->{transdate};
1232     $form->{label}        = $locale->text('Purchase Order');
1233     $numberfld            = "ponumber";
1234     $order                = 1;
1235   }
1236   if ($form->{formname} eq 'bin_list') {
1237     $inv                  = "ord";
1238     $due                  = "req";
1239     $form->{"${inv}date"} = $form->{transdate};
1240     $form->{label}        = $locale->text('Bin List');
1241     $order                = 1;
1242   }
1243   if ($form->{formname} eq 'sales_quotation') {
1244     $inv                  = "quo";
1245     $due                  = "req";
1246     $form->{"${inv}date"} = $form->{transdate};
1247     $form->{label}        = $locale->text('Quotation');
1248     $numberfld            = "sqnumber";
1249     $order                = 1;
1250   }
1251
1252   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1253     $inv                  = "quo";
1254     $due                  = "req";
1255     $form->{"${inv}date"} = $form->{transdate};
1256     $form->{"invdate"}    = $form->{transdate};
1257     $form->{label}        = $locale->text('Proforma Invoice');
1258     $numberfld            = "sqnumber";
1259     $order                = 1;
1260   }
1261
1262   if ($form->{formname} eq 'request_quotation') {
1263     $inv                  = "quo";
1264     $due                  = "req";
1265     $form->{"${inv}date"} = $form->{transdate};
1266     $form->{label}        = $locale->text('RFQ');
1267     $numberfld            = "rfqnumber";
1268     $order                = 1;
1269   }
1270
1271   if ($form->{type} =~ /_delivery_order$/) {
1272     undef $due;
1273     $inv                  = "do";
1274     $form->{"${inv}date"} = $form->{transdate};
1275     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1276     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1277   }
1278
1279   $form->isblank("email", $locale->text('E-mail address missing!'))
1280     if ($form->{media} eq 'email');
1281   $form->isblank("${inv}date",
1282            $locale->text($form->{label}) 
1283            . ": "
1284            . $locale->text(' Date missing!'));
1285
1286   # $locale->text('Invoice Number missing!')
1287   # $locale->text('Invoice Date missing!')
1288   # $locale->text('Packing List Number missing!')
1289   # $locale->text('Packing List Date missing!')
1290   # $locale->text('Order Number missing!')
1291   # $locale->text('Order Date missing!')
1292   # $locale->text('Quotation Number missing!')
1293   # $locale->text('Quotation Date missing!')
1294
1295   # assign number
1296   $form->{what_done} = $form->{formname};
1297   if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) {
1298     $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld);
1299     if ($form->{media} ne 'email') {
1300
1301       # get pricegroups for parts
1302       IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1303
1304       # build up html code for prices_$i
1305       set_pricegroup($form->{rowcount});
1306
1307       $form->{rowcount}--;
1308
1309       call_sub($display_form);
1310       # saving the history
1311           if(!exists $form->{addition}) {
1312         $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber}; 
1313             $form->{addition} = "PRINTED";
1314             $form->save_history($form->dbconnect(\%myconfig));
1315       }
1316       # /saving the history
1317       exit;
1318     }
1319   }
1320
1321   &validate_items;
1322
1323   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1324   my ($saved_email, $saved_cc, $saved_bcc) =
1325     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1326
1327   $language_saved = $form->{language_id};
1328   $payment_id_saved = $form->{payment_id};
1329   $salesman_id_saved = $form->{salesman_id};
1330   $cp_id_saved = $form->{cp_id};
1331
1332   call_sub("$form->{vc}_details") if ($form->{vc});
1333
1334   $form->{language_id} = $language_saved;
1335   $form->{payment_id} = $payment_id_saved;
1336
1337   $form->{"email"} = $saved_email if ($saved_email);
1338   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1339   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1340
1341   if (!$cp_id_saved) {
1342     # No contact was selected. Delete all contact variables because
1343     # IS->customer_details() and IR->vendor_details() get the default
1344     # contact anyway.
1345     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1346   }
1347
1348   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1349   if ($form->{"language_id"}) {
1350     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1351       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1352   } else {
1353     $output_dateformat = $myconfig{"dateformat"};
1354     $output_numberformat = $myconfig{"numberformat"};
1355     $output_longdates = 1;
1356   }
1357
1358   ($form->{employee}) = split /--/, $form->{employee};
1359
1360   # create the form variables
1361   if ($form->{type} =~ /_delivery_order$/) {
1362     DO->order_details();
1363   } elsif ($order) {
1364     OE->order_details(\%myconfig, \%$form);
1365   } else {
1366     IS->invoice_details(\%myconfig, \%$form, $locale);
1367   }
1368
1369   $form->get_salesman(\%myconfig, $salesman_id_saved);
1370
1371   if ($form->{shipto_id}) {
1372     $form->get_shipto(\%myconfig);
1373   }
1374
1375   @a = qw(name street zipcode city country);
1376
1377   $shipto = 1;
1378
1379   # if there is no shipto fill it in from billto
1380   foreach $item (@a) {
1381     if ($form->{"shipto$item"}) {
1382       $shipto = 0;
1383       last;
1384     }
1385   }
1386
1387   if ($shipto) {
1388     if (   $form->{formname} eq 'purchase_order'
1389         || $form->{formname} eq 'request_quotation') {
1390       $form->{shiptoname}   = $myconfig{company};
1391       $form->{shiptostreet} = $myconfig{address};
1392     } else {
1393       map { $form->{"shipto$_"} = $form->{$_} } @a;
1394     }
1395   }
1396
1397   $form->{notes} =~ s/^\s+//g;
1398
1399   $form->{templates} = "$myconfig{templates}";
1400
1401   delete $form->{printer_command};
1402
1403   $form->{language} = $form->get_template_language(\%myconfig);
1404
1405   my $printer_code;
1406   if ($form->{media} ne 'email') {
1407     $printer_code = $form->get_printer_code(\%myconfig);
1408     if ($printer_code ne "") {
1409       $printer_code = "_" . $printer_code;
1410     }
1411   }
1412
1413   if ($form->{language} ne "") {
1414     map({ $form->{"unit"}->[$_] =
1415             AM->translate_units($form, $form->{"language"},
1416                                 $form->{"unit"}->[$_], $form->{"qty"}->[$_]); }
1417         (0..scalar(@{$form->{"unit"}}) - 1));
1418     $form->{language} = "_" . $form->{language};
1419   }
1420
1421   # Format dates.
1422   format_dates($output_dateformat, $output_longdates,
1423                qw(invdate orddate quodate pldate duedate reqdate transdate
1424                   shippingdate deliverydate validitydate paymentdate
1425                   datepaid transdate_oe deliverydate_oe
1426                   employee_startdate employee_enddate
1427                   ),
1428                grep({ /^datepaid_\d+$/ ||
1429                         /^transdate_oe_\d+$/ ||
1430                         /^deliverydate_oe_\d+$/ ||
1431                         /^reqdate_\d+$/ ||
1432                         /^deliverydate_\d+$/ ||
1433                         /^transdate_\d+$/
1434                     } keys(%{$form})));
1435
1436   reformat_numbers($output_numberformat, 2,
1437                    qw(invtotal ordtotal quototal subtotal linetotal
1438                       listprice sellprice netprice discount
1439                       tax taxbase total paid),
1440                    grep({ /^linetotal_\d+$/ ||
1441                             /^listprice_\d+$/ ||
1442                             /^sellprice_\d+$/ ||
1443                             /^netprice_\d+$/ ||
1444                             /^taxbase_\d+$/ ||
1445                             /^discount_\d+$/ ||
1446                             /^paid_\d+$/ ||
1447                             /^subtotal_\d+$/ ||
1448                             /^total_\d+$/ ||
1449                             /^tax_\d+$/
1450                         } keys(%{$form})));
1451
1452   reformat_numbers($output_numberformat, undef,
1453                    qw(qty price_factor),
1454                    grep({ /^qty_\d+$/
1455                         } keys(%{$form})));
1456
1457   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1458
1459   if (scalar @{ $cvar_date_fields }) {
1460     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1461   }
1462
1463   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1464     reformat_numbers($output_numberformat, $precision, @{ $field_list });
1465   }
1466
1467   $form->{IN} = "$form->{formname}$form->{language}${printer_code}.html";
1468   if ($form->{format} eq 'postscript') {
1469     $form->{postscript} = 1;
1470     $form->{IN} =~ s/html$/tex/;
1471   } elsif ($form->{"format"} =~ /pdf/) {
1472     $form->{pdf} = 1;
1473     if ($form->{"format"} =~ /opendocument/) {
1474       $form->{IN} =~ s/html$/odt/;
1475     } else {
1476       $form->{IN} =~ s/html$/tex/;
1477     }
1478   } elsif ($form->{"format"} =~ /opendocument/) {
1479     $form->{"opendocument"} = 1;
1480     $form->{"IN"} =~ s/html$/odt/;
1481   }
1482
1483   delete $form->{OUT};
1484
1485   if ($form->{media} eq 'printer') {
1486     $form->{OUT} = "| $form->{printer_command} &>/dev/null";
1487     $form->{printed} .= " $form->{formname}";
1488     $form->{printed} =~ s/^ //;
1489   }
1490   $printed = $form->{printed};
1491
1492   if ($form->{media} eq 'email') {
1493     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1494       unless $form->{subject};
1495
1496     $form->{emailed} .= " $form->{formname}";
1497     $form->{emailed} =~ s/^ //;
1498   }
1499   $emailed = $form->{emailed};
1500
1501   if ($form->{media} eq 'queue') {
1502     %queued = map { s|.*/|| } split / /, $form->{queued};
1503
1504     if ($filename = $queued{ $form->{formname} }) {
1505       $form->{queued} =~ s/\Q$form->{formname} $filename\E//;
1506       unlink "$spool/$filename";
1507       $filename =~ s/\..*$//g;
1508     } else {
1509       $filename = time;
1510       $filename .= $$;
1511     }
1512
1513     $filename .= ($form->{postscript}) ? '.ps' : '.pdf';
1514     $form->{OUT} = ">$spool/$filename";
1515
1516     # add type
1517     $form->{queued} .= " $form->{formname} $filename";
1518
1519     $form->{queued} =~ s/^ //;
1520   }
1521   $queued = $form->{queued};
1522
1523 # saving the history
1524   if(!exists $form->{addition}) {
1525     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1526     if($form->{media} =~ /printer/) {
1527         $form->{addition} = "PRINTED";
1528     }
1529     elsif($form->{media} =~ /email/) {
1530         $form->{addition} = "MAILED";
1531     }
1532     elsif($form->{media} =~ /queue/) {
1533         $form->{addition} = "QUEUED";
1534     }
1535     elsif($form->{media} =~ /screen/) {
1536         $form->{addition} = "SCREENED";
1537     }
1538     $form->save_history($form->dbconnect(\%myconfig));
1539   }
1540   # /saving the history
1541
1542   $form->parse_template(\%myconfig, $userspath);
1543
1544   $form->{callback} = "";
1545
1546   if ($form->{media} eq 'email') {
1547     $form->{message} = $locale->text('sent') unless $form->{message};
1548   }
1549   $message = $form->{message};
1550
1551   # if we got back here restore the previous form
1552   if ($form->{media} =~ /(printer|email|queue)/) {
1553
1554     $form->update_status(\%myconfig)
1555       if ($form->{media} eq 'queue' && $form->{id});
1556
1557     return $lxdebug->leave_sub() if ($old_form eq "return");
1558
1559     if ($old_form) {
1560
1561       $old_form->{"${inv}number"} = $form->{"${inv}number"};
1562
1563       # restore and display form
1564       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1565
1566       $form->{queued}  = $queued;
1567       $form->{printed} = $printed;
1568       $form->{emailed} = $emailed;
1569       $form->{message} = $message;
1570
1571       $form->{rowcount}--;
1572       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1573         qw(exchangerate creditlimit creditremaining);
1574
1575       for $i (1 .. $form->{paidaccounts}) {
1576         map {
1577           $form->{"${_}_$i"} =
1578             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1579         } qw(paid exchangerate);
1580       }
1581
1582       call_sub($display_form);
1583       exit;
1584     }
1585
1586     $msg =
1587       ($form->{media} eq 'printer')
1588       ? $locale->text('sent to printer')
1589       : $locale->text('emailed to') . " $form->{email}";
1590     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1591   }
1592   if ($form->{printing}) {
1593    call_sub($display_form);
1594    exit; 
1595   }
1596
1597   $lxdebug->leave_sub();
1598 }
1599
1600 sub customer_details {
1601   $lxdebug->enter_sub();
1602
1603   IS->customer_details(\%myconfig, \%$form, @_);
1604
1605   $lxdebug->leave_sub();
1606 }
1607
1608 sub vendor_details {
1609   $lxdebug->enter_sub();
1610
1611   IR->vendor_details(\%myconfig, \%$form, @_);
1612
1613   $lxdebug->leave_sub();
1614 }
1615
1616 sub post_as_new {
1617   $lxdebug->enter_sub();
1618
1619   _check_io_auth();
1620
1621   $form->{postasnew} = 1;
1622   map { delete $form->{$_} } qw(printed emailed queued);
1623
1624   &post;
1625
1626   $lxdebug->leave_sub();
1627 }
1628
1629 sub ship_to {
1630   $lxdebug->enter_sub();
1631
1632   _check_io_auth();
1633
1634   if ($form->{second_run}) {
1635     $form->{print_and_post} = 0;
1636   }
1637
1638   $title = $form->{title};
1639   $form->{title} = $locale->text('Ship to');
1640
1641   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1642     qw(exchangerate creditlimit creditremaining);
1643
1644   my @shipto_vars =
1645     qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
1646        shiptocontact shiptophone shiptofax shiptoemail
1647        shiptodepartment_1 shiptodepartment_2);
1648
1649   my @addr_vars =
1650     (qw(name department_1 department_2 street zipcode city country
1651         contact email phone fax));
1652
1653   # get details for name
1654   call_sub("$form->{vc}_details", @addr_vars);
1655
1656   $number =
1657     ($form->{vc} eq 'customer')
1658     ? $locale->text('Customer Number')
1659     : $locale->text('Vendor Number');
1660
1661   # get pricegroups for parts
1662   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1663
1664   # build up html code for prices_$i
1665   set_pricegroup($form->{rowcount});
1666
1667   $nextsub = ($form->{display_form}) ? $form->{display_form} : "display_form";
1668
1669   $form->{rowcount}--;
1670
1671   $form->header;
1672
1673   print qq|
1674 <body>
1675
1676 <form method="post" action="$form->{script}">
1677
1678 <table width="100%">
1679   <tr>
1680     <td>
1681       <table>
1682         <tr class="listheading">
1683           <th class="listheading" colspan="2" width="50%">|
1684     . $locale->text('Billing Address') . qq|</th>
1685           <th class="listheading" width="50%">|
1686     . $locale->text('Shipping Address') . qq|</th>
1687         </tr>
1688         <tr height="5"></tr>
1689         <tr>
1690           <th align="right" nowrap>$number</th>
1691           <td>$form->{"$form->{vc}number"}</td>
1692         </tr>
1693         <tr>
1694           <th align="right" nowrap>| . $locale->text('Company Name') . qq|</th>
1695           <td>$form->{name}</td>
1696           <td><input name="shiptoname" size="35" value="$form->{shiptoname}"></td>
1697         </tr>
1698         <tr>
1699           <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
1700           <td>$form->{department_1}</td>
1701           <td><input name="shiptodepartment_1" size="35" value="$form->{shiptodepartment_1}"></td>
1702         </tr>
1703         <tr>
1704           <th align="right" nowrap>&nbsp;</th>
1705           <td>$form->{department_2}</td>
1706           <td><input name="shiptodepartment_2" size="35" value="$form->{shiptodepartment_2}"></td>
1707         </tr>
1708         <tr>
1709           <th align="right" nowrap>| . $locale->text('Street') . qq|</th>
1710           <td>$form->{street}</td>
1711           <td><input name="shiptostreet" size="35" value="$form->{shiptostreet}"></td>
1712         </tr>
1713         <tr>
1714           <th align="right" nowrap>| . $locale->text('Zipcode') . qq|</th>
1715           <td>$form->{zipcode}</td>
1716           <td><input name="shiptozipcode" size="35" value="$form->{shiptozipcode}"></td>
1717         </tr>
1718         <tr>
1719           <th align="right" nowrap>| . $locale->text('City') . qq|</th>
1720           <td>$form->{city}</td>
1721           <td><input name="shiptocity" size="35" value="$form->{shiptocity}"></td>
1722         </tr>
1723         <tr>
1724           <th align="right" nowrap>| . $locale->text('Country') . qq|</th>
1725           <td>$form->{country}</td>
1726           <td><input name="shiptocountry" size="35" value="$form->{shiptocountry}"></td>
1727         </tr>
1728         <tr>
1729           <th align="right" nowrap>| . $locale->text('Contact') . qq|</th>
1730           <td>$form->{contact}</td>
1731           <td><input name="shiptocontact" size="35" value="$form->{shiptocontact}"></td>
1732         </tr>
1733         <tr>
1734           <th align="right" nowrap>| . $locale->text('Phone') . qq|</th>
1735           <td>$form->{phone}</td>
1736           <td><input name="shiptophone" size="20" value="$form->{shiptophone}"></td>
1737         </tr>
1738         <tr>
1739           <th align="right" nowrap>| . $locale->text('Fax') . qq|</th>
1740           <td>$form->{fax}</td>
1741           <td><input name="shiptofax" size="20" value="$form->{shiptofax}"></td>
1742         </tr>
1743         <tr>
1744           <th align="right" nowrap>| . $locale->text('E-mail') . qq|</th>
1745           <td>$form->{email}</td>
1746           <td><input name="shiptoemail" size="35" value="$form->{shiptoemail}"></td>
1747         </tr>
1748       </table>
1749     </td>
1750   </tr>
1751 </table>
1752 | . $cgi->hidden("-name" => "nextsub", "-value" => $nextsub);
1753 ;
1754
1755
1756
1757   # delete shipto
1758   map({ delete $form->{$_} } (@shipto_vars, qw(header)));
1759   $form->{title} = $title;
1760
1761   foreach $key (keys %$form) {
1762     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1763     $form->{$key} =~ s/\"/&quot;/g;
1764     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1765   }
1766
1767   print qq|
1768
1769 <hr size="3" noshade>
1770
1771 <br>
1772 <input class="submit" type="submit" name="action" value="|
1773     . $locale->text('Continue') . qq|">
1774 </form>
1775
1776 </body>
1777 </html>
1778 |;
1779
1780   $lxdebug->leave_sub();
1781 }
1782
1783 sub new_license {
1784   $lxdebug->enter_sub();
1785
1786   _check_io_auth();
1787
1788   my $row = shift;
1789
1790   # change callback
1791   $form->{old_callback} = $form->escape($form->{callback}, 1);
1792   $form->{callback} = $form->escape("$form->{script}?action=display_form", 1);
1793   $form->{old_callback} = $form->escape($form->{old_callback}, 1);
1794
1795   # delete action
1796   delete $form->{action};
1797   $customer = $form->{customer};
1798   map { $form->{"old_$_"} = $form->{"${_}_$row"} } qw(partnumber description);
1799
1800   # save all other form variables in a previousform variable
1801   $form->{row} = $row;
1802   foreach $key (keys %$form) {
1803     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1804
1805     # escape ampersands
1806     $form->{$key} =~ s/&/%26/g;
1807     $previousform .= qq|$key=$form->{$key}&|;
1808   }
1809   chop $previousform;
1810   $previousform = $form->escape($previousform, 1);
1811
1812   $form->{script} = "licenses.pl";
1813
1814   map { $form->{$_} = $form->{"old_$_"} } qw(partnumber description);
1815   map { $form->{$_} = $form->escape($form->{$_}, 1) }
1816     qw(partnumber description);
1817   $form->{callback} =
1818     qq|$form->{script}?action=add&vc=$form->{db}&$form->{db}_id=$form->{id}&$form->{db}=$name&type=$form->{type}&customer=$customer&partnumber=$form->{partnumber}&description=$form->{description}&previousform="$previousform"&initial=1|;
1819   $form->redirect;
1820
1821   $lxdebug->leave_sub();
1822 }
1823
1824 sub relink_accounts {
1825   $lxdebug->enter_sub();
1826
1827   _check_io_auth();
1828
1829   $form->{"taxaccounts"} =~ s/\s*$//;
1830   $form->{"taxaccounts"} =~ s/^\s*//;
1831   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1832     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1833   }
1834   $form->{"taxaccounts"} = "";
1835
1836   for (my $i = 1; $i <= $form->{"rowcount"}; $i++) {
1837     if ($form->{"id_$i"}) {
1838       IC->retrieve_accounts(\%myconfig, $form, $form->{"id_$i"}, $i, 1);
1839     }
1840   }
1841
1842   $lxdebug->leave_sub();
1843 }
1844
1845 sub set_duedate {
1846   $lxdebug->enter_sub();
1847
1848   _check_io_auth();
1849
1850   $form->get_duedate(\%myconfig);
1851
1852   print $cgi->header() . $form->{duedate};
1853
1854   $lxdebug->leave_sub();
1855 }
1856
1857 sub _update_part_information {
1858   $lxdebug->enter_sub();
1859
1860   my %part_information = IC->get_basic_part_info('id'        => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ],
1861                                                  'vendor_id' => $form->{vendor_id});
1862
1863   $form->{PART_INFORMATION} = \%part_information;
1864
1865   foreach my $i (1..$form->{rowcount}) {
1866     next unless ($form->{"id_${i}"});
1867
1868     my $info                 = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
1869     $form->{"partunit_${i}"} = $info->{unit};
1870   }
1871
1872   $lxdebug->leave_sub();
1873 }
1874
1875 sub _update_ship {
1876   $lxdebug->enter_sub();
1877
1878   if (!$form->{ordnumber}) {
1879     map { $form->{"ship_$_"} = 0 } (1..$form->{rowcount});
1880     $lxdebug->leave_sub();
1881     return;
1882   }
1883
1884   AM->retrieve_all_units();
1885
1886   my %ship = DO->get_shipped_qty('type'      => ($form->{type} eq 'purchase_order') ? 'purchase' : 'sales',
1887                                  'ordnumber' => $form->{ordnumber},);
1888
1889   foreach my $i (1..$form->{rowcount}) {
1890     next unless ($form->{"id_${i}"});
1891
1892     $form->{"ship_$i"} = 0;
1893
1894     my $ship_entry = $ship{$form->{"id_$i"}};
1895
1896     next if (!$ship_entry || ($ship_entry->{qty} <= 0));
1897
1898     my $rowqty =
1899       ($form->{simple_save} ? $form->{"qty_$i"} : $form->parse_amount(\%myconfig, $form->{"qty_$i"}))
1900       * $all_units->{$form->{"unit_$i"}}->{factor}
1901       / $all_units->{$form->{"partunit_$i"}}->{factor};
1902
1903     $form->{"ship_$i"}  = min($rowqty, $ship_entry->{qty});
1904     $ship_entry->{qty} -= $form->{"ship_$i"};
1905   }
1906
1907   foreach my $i (1..$form->{rowcount}) {
1908     next unless ($form->{"id_${i}"});
1909
1910     my $ship_entry = $ship{$form->{"id_$i"}};
1911
1912     next if (!$ship_entry || ($ship_entry->{qty} <= 0.01));
1913
1914     $form->{"ship_$i"} += $ship_entry->{qty};
1915     $ship_entry->{qty}  = 0;
1916   }
1917
1918   $lxdebug->leave_sub();
1919 }