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