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