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