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