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