e597aa036b56ff52a38a5cdfe1ab13df2b6f518a
[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 SL::CT;
37 use SL::IC;
38 use CGI::Ajax;
39 use CGI;
40
41 require "$form->{path}/common.pl";
42
43 # any custom scripts for this one
44 if (-f "$form->{path}/custom_io.pl") {
45   eval { require "$form->{path}/custom_io.pl"; };
46 }
47 if (-f "$form->{path}/$form->{login}_io.pl") {
48   eval { require "$form->{path}/$form->{login}_io.pl"; };
49 }
50
51 1;
52
53 # end of main
54
55 # this is for our long dates
56 # $locale->text('January')
57 # $locale->text('February')
58 # $locale->text('March')
59 # $locale->text('April')
60 # $locale->text('May ')
61 # $locale->text('June')
62 # $locale->text('July')
63 # $locale->text('August')
64 # $locale->text('September')
65 # $locale->text('October')
66 # $locale->text('November')
67 # $locale->text('December')
68
69 # this is for our short month
70 # $locale->text('Jan')
71 # $locale->text('Feb')
72 # $locale->text('Mar')
73 # $locale->text('Apr')
74 # $locale->text('May')
75 # $locale->text('Jun')
76 # $locale->text('Jul')
77 # $locale->text('Aug')
78 # $locale->text('Sep')
79 # $locale->text('Oct')
80 # $locale->text('Nov')
81 # $locale->text('Dec')
82 use SL::IS;
83 use SL::PE;
84 use SL::AM;
85 use Data::Dumper;
86 ########################################
87 # Eintrag fuer Version 2.2.0 geaendert #
88 # neue Optik im Rechnungsformular      #
89 ########################################
90 sub display_row {
91   $lxdebug->enter_sub();
92   my $numrows = shift;
93
94   if ($lizenzen && $form->{vc} eq "customer") {
95     if ($form->{type} =~ /sales_order/) {
96       @column_index = (runningnumber, partnumber, description, ship, qty);
97     } elsif ($form->{type} =~ /sales_quotation/) {
98       @column_index = (runningnumber, partnumber, description, qty);
99     } else {
100       @column_index = (runningnumber, partnumber, description, qty);
101     }
102   } else {
103     if (   ($form->{type} =~ /purchase_order/)
104         || ($form->{type} =~ /sales_order/)) {
105       @column_index = (runningnumber, partnumber, description, ship, qty);
106         } else {
107       @column_index = (runningnumber, partnumber, description, qty);
108     }
109   }
110 ############## ENDE Neueintrag ##################
111
112   my $dimension_units = AM->retrieve_units(\%myconfig, $form, "dimension");
113   my $service_units = AM->retrieve_units(\%myconfig, $form, "service");
114   my $all_units = AM->retrieve_units(\%myconfig, $form);
115
116   push @column_index, qw(unit);
117
118   #for pricegroups column
119   if (   $form->{type} =~ (/sales_quotation/)
120       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
121       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
122       or ($form->{type} =~ /sales_order/)) {
123     push @column_index, qw(sellprice_pg);
124   }
125
126   push @column_index, qw(sellprice);
127
128   if ($form->{vc} eq 'customer') {
129     push @column_index, qw(discount);
130   }
131
132   push @column_index, "linetotal";
133
134   my $colspan = $#column_index + 1;
135
136   $form->{invsubtotal} = 0;
137   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
138
139 ########################################
140   # Eintrag fuer Version 2.2.0 geaendert #
141   # neue Optik im Rechnungsformular      #
142 ########################################
143   $column_data{runningnumber} =
144       qq|<th align="left" nowrap width="5" class="listheading">|
145     . $locale->text('No.')
146     . qq|</th>|;
147   $column_data{partnumber} =
148       qq|<th align="left" nowrap width="12" class="listheading">|
149     . $locale->text('Number')
150     . qq|</th>|;
151   $column_data{description} =
152       qq|<th align="left" nowrap width="30" class="listheading">|
153     . $locale->text('Part Description')
154     . qq|</th>|;
155   if ($form->{"type"} eq "purchase_order") {
156     $column_data{ship} =
157       qq|<th align="left" nowrap width="5" class="listheading">|
158       . $locale->text('Ship rcvd')
159       . qq|</th>|;
160   } else {
161     $column_data{ship} =
162       qq|<th align="left" nowrap width="5" class="listheading">|
163       . $locale->text('Ship')
164       . qq|</th>|;
165   }
166   $column_data{qty} =
167       qq|<th align="left" nowrap width="5" class="listheading">|
168     . $locale->text('Qty')
169     . qq|</th>|;
170   $column_data{unit} =
171       qq|<th align="left" nowrap width="5" class="listheading">|
172     . $locale->text('Unit')
173     . qq|</th>|;
174   $column_data{license} =
175       qq|<th align="left" nowrap width="10" class="listheading">|
176     . $locale->text('License')
177     . qq|</th>|;
178   $column_data{serialnr} =
179       qq|<th align="left" nowrap width="10" class="listheading">|
180     . $locale->text('Serial No.')
181     . qq|</th>|;
182   $column_data{projectnr} =
183       qq|<th align="left" nowrap width="10" class="listheading">|
184     . $locale->text('Project')
185     . qq|</th>|;
186   $column_data{sellprice} =
187       qq|<th align="left" nowrap width="15" class="listheading">|
188     . $locale->text('Price')
189     . qq|</th>|;
190   $column_data{sellprice_pg} =
191       qq|<th align="left" nowrap width="15" class="listheading">|
192     . $locale->text('Pricegroup')
193     . qq|</th>|;
194   $column_data{discount} =
195       qq|<th align="left" class="listheading">|
196     . $locale->text('Discount')
197     . qq|</th>|;
198   $column_data{linetotal} =
199       qq|<th align="left" nowrap width="10" class="listheading">|
200     . $locale->text('Extended')
201     . qq|</th>|;
202   $column_data{bin} =
203       qq|<th align="left" nowrap width="10" class="listheading">|
204     . $locale->text('Bin')
205     . qq|</th>|;
206 ############## ENDE Neueintrag ##################
207
208   $myconfig{"show_form_details"} = 1
209     unless (defined($myconfig{"show_form_details"}));
210   $form->{"show_details"} = $myconfig{"show_form_details"}
211     unless (defined($form->{"show_details"}));
212   $form->{"show_details"} = $form->{"show_details"} ? 1 : 0;
213   my $show_details_new = 1 - $form->{"show_details"};
214   my $show_details_checked = $form->{"show_details"} ? "checked" : "";
215
216   print qq|
217   <tr>
218     <td>| . $cgi->hidden("-name" => "show_details", "-value" => $form->{show_details}) . qq|
219       <input type="checkbox" id="cb_show_details" onclick="show_form_details($show_details_new);" $show_details_checked>
220       <label for="cb_show_details">| . $locale->text("Show details") . qq|</label><br>
221       <table width="100%">
222         <tr class="listheading">|;
223
224   map { print "\n$column_data{$_}" } @column_index;
225
226   print qq|
227         </tr>
228 |;
229
230   $runningnumber = $locale->text('No.');
231   $deliverydate  = $locale->text('Delivery Date');
232   $serialnumber  = $locale->text('Serial No.');
233   $projectnumber = $locale->text('Project');
234   $partsgroup    = $locale->text('Group');
235   $reqdate       = $locale->text('Reqdate');
236
237   $delvar = 'deliverydate';
238
239   if ($form->{type} =~ /_order$/ || $form->{type} =~ /_quotation$/) {
240     $deliverydate = $locale->text('Required by');
241     $delvar       = 'reqdate';
242   }
243
244   my %projectnumber_labels = ();
245   my @projectnumber_values = ("");
246   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
247     push(@projectnumber_values, $item->{"id"});
248     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
249   }
250
251   for $i (1 .. $numrows) {
252
253     # undo formatting
254     map {
255       $form->{"${_}_$i"} =
256         $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
257     } qw(qty ship discount sellprice price_new price_old) unless ($form->{simple_save});
258
259     if (!$form->{"unit_old_$i"}) {
260       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
261       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
262       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
263       $form->{"unit_old_$i"} = $form->{"unit_$i"};
264     }
265
266     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
267     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
268     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
269
270     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
271     if (!$check_units->{$form->{"selected_unit_$i"}} ||
272         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
273          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
274       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
275       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
276       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
277       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
278     }
279     if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) {
280       if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
281         my $basefactor = 1;
282         if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
283             $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
284           $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
285             $all_units->{$form->{"unit_old_$i"}}->{"factor"};
286         }
287         $form->{"sellprice_$i"} *= $basefactor;
288         $form->{"unit_old_$i"} = $form->{"selected_unit_$i"};
289       }
290     }
291     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
292     $dec           = length $dec;
293     $decimalplaces = ($dec > 2) ? $dec : 2;
294
295     $discount =
296       $form->round_amount(
297                         $form->{"sellprice_$i"} * $form->{"discount_$i"} / 100,
298                         $decimalplaces);
299
300     $linetotal =
301       $form->round_amount($form->{"sellprice_$i"} - $discount, $decimalplaces);
302     $linetotal = $form->round_amount($linetotal * $form->{"qty_$i"}, 2);
303
304     # convert " to &quot;
305     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g }
306       qw(partnumber description unit unit_old);
307
308 ########################################
309     # Eintrag fuer Version 2.2.0 geaendert #
310     # neue Optik im Rechnungsformular      #
311 ########################################
312     $column_data{runningnumber} =
313       qq|<td><input name="runningnumber_$i" size="5" value="$i"></td>|;    # HuT
314 ############## ENDE Neueintrag ##################
315
316     $column_data{partnumber} =
317       qq|<td><input name="partnumber_$i" size=12 value="$form->{"partnumber_$i"}"></td>|;
318
319     if (($rows = $form->numtextrows($form->{"description_$i"}, 30, 6)) > 1) {
320       $column_data{description} =
321         qq|<td><textarea name="description_$i" rows="$rows" cols="30" wrap="soft">| . H($form->{"description_$i"}) . qq|</textarea><button type="button" onclick="set_longdescription_window('longdescription_$i')">| . $locale->text('L') . qq|</button></td>|;
322     } else {
323       $column_data{description} =
324         qq|<td><input name="description_$i" size="30" value="| . $form->quote($form->{"description_$i"}) . qq|"><button type="button" onclick="set_longdescription_window('longdescription_$i')">| . $locale->text('L') . qq|</button></td>|;
325     }
326
327     (my $qty_dec) = ($form->{"qty_$i"} =~ /\.(\d+)/);
328     $qty_dec = length $qty_dec;
329
330     $column_data{qty} =
331         qq|<td align="right"><input name="qty_$i" size="5" value="|
332       . $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec) .qq|">|;
333     if ($form->{"formel_$i"}) {
334     $column_data{qty} .= qq|<button type="button" onclick="calculate_qty_selection_window('qty_$i','alu_$i', 'formel_$i', $i)">| . $locale->text('*/') . qq|</button>| .
335           $cgi->hidden("-name" => "formel_$i", "-value" => $form->{"formel_$i"}) . $cgi->hidden("-name" => "alu_$i", "-value" => $form->{"alu_$i"}). qq|</td>|;
336     }
337     $column_data{ship} =
338         qq|<td align="right"><input name="ship_$i" size=5 value="|
339       . $form->format_amount(\%myconfig, $form->{"ship_$i"})
340       . qq|"></td>|;
341
342     my $is_part     = $form->{"inventory_accno_$i"};
343     my $is_assembly = $form->{"assembly_$i"};
344     my $is_assigned = $form->{"id_$i"};
345     my $this_unit = $form->{"unit_$i"};
346     if ($form->{"selected_unit_$i"} && $this_unit &&
347         $all_units->{$form->{"selected_unit_$i"}} && $all_units->{$this_unit} &&
348         ($all_units->{$form->{"selected_unit_$i"}}->{"base_unit"} eq $all_units->{$this_unit}->{"base_unit"})) {
349       $this_unit = $form->{"selected_unit_$i"};
350     } elsif (!$is_assigned ||
351              ($is_part && !$this_unit && ($all_units->{$this_unit} && ($all_units->{$this_unit}->{"base_unit"} eq $all_units->{"kg"}->{"base_unit"})))) {
352       $this_unit = "kg";
353     }
354
355     $column_data{"unit"} = "<td>" .
356        AM->unit_select_html($is_part || $is_assembly ? $dimension_units :
357                             $is_assigned ? $service_units : $all_units,
358                             "unit_$i", $this_unit,
359                             $is_assigned ? $form->{"unit_$i"} : undef)
360       . "</td>";
361
362     # build in drop down list for pricesgroups
363     if ($form->{"prices_$i"}) {
364       if  ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"}) {
365         $price_tmp = $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces);
366       } else {
367         $price_tmp = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
368       }
369
370       $column_data{sellprice_pg} =
371       qq|<td align="right"><select name="sellprice_pg_$i">$form->{"prices_$i"}</select></td>|;
372       $column_data{sellprice} =
373       qq|<td><input name="sellprice_$i" size="10" value="$price_tmp" onBlur=\"check_right_number_format(this)\"></td>|;
374     } else {
375
376       # for last row and report
377       # set pricegroup drop down list from report menu
378       if ($form->{"sellprice_$i"} != 0) {
379         $prices =
380           qq|<option value="$form->{"sellprice_$i"}--$form->{"pricegroup_id_$i"}" selected>$form->{"pricegroup_$i"}</option>\n|;
381
382         $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"};
383
384         $column_data{sellprice_pg} =
385           qq|<td align="right"><select name="sellprice_pg_$i">$prices</select></td>|;
386
387       } else {
388
389         # for last row
390         $column_data{sellprice_pg} = qq|<td align="right">&nbsp;</td>|;
391         }
392         
393       $column_data{sellprice} =
394       qq|<td><input name="sellprice_$i" size="10" onBlur=\"check_right_number_format(this)\" value="|
395         . $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
396                                $decimalplaces)
397         . qq|"></td>|;
398     }
399     $column_data{discount} =
400         qq|<td align="right"><input name="discount_$i" size=3 value="|
401       . $form->format_amount(\%myconfig, $form->{"discount_$i"})
402       . qq|"></td>|;
403     $column_data{linetotal} =
404         qq|<td align="right">|
405       . $form->format_amount(\%myconfig, $linetotal, 2)
406       . qq|</td>|;
407     $column_data{bin} = qq|<td>$form->{"bin_$i"}</td>|;
408
409 ########################################
410     # Eintrag fuer Version 2.2.0 geaendert #
411     # neue Optik im Rechnungsformular      #
412 ########################################
413     #     if ($lizenzen &&  $form->{type} eq "invoice" &&  $form->{vc} eq "customer") {
414     #     $column_data{license} = qq|<td><select name="licensenumber_$i">$form->{"lizenzen_$i"}></select></td>|;
415     #     }
416     #
417     #     if ($form->{type} !~ /_quotation/) {
418     #     $column_data{serialnr} = qq|<td><input name="serialnumber_$i" size=10 value="$form->{"serialnumber_$i"}"></td>|;
419     #     }
420     #
421     #     $column_data{projectnr} = qq|<td><input name="projectnumber_$i" size=10 value="$form->{"projectnumber_$i"}"></td>|;
422 ############## ENDE Neueintrag ##################
423     my $j = $i % 2;
424     print qq|
425
426         <tr valign="top" class="listrow$j">|;
427
428     map { print "\n$column_data{$_}" } @column_index;
429
430     print("</tr>\n" .
431           $cgi->hidden("-name" => "unit_old_$i",
432                        "-value" => $form->{"selected_unit_$i"})
433           . "\n" .
434           $cgi->hidden("-name" => "price_new_$i",
435                        "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"}))
436           . "\n");
437     map({ print($cgi->hidden("-name" => $_, "-value" => $form->{$_}) . "\n"); }
438         ("orderitems_id_$i", "bo_$i", "pricegroup_old_$i", "price_old_$i",
439          "id_$i", "inventory_accno_$i", "bin_$i", "partsgroup_$i", "partnotes_$i",
440          "income_accno_$i", "expense_accno_$i", "listprice_$i", "assembly_$i",
441          "taxaccounts_$i", "ordnumber_$i", "transdate_$i", "cusordnumber_$i",
442          "longdescription_$i", "basefactor_$i"));
443
444 ########################################
445     # Eintrag fuer Version 2.2.0 geaendert #
446     # neue Optik im Rechnungsformular      #
447 ########################################
448
449     my $row_style_attr =
450       'style="display:none;"' if (!$form->{"show_details"});
451
452     # print second row
453     print qq|
454         <tr  class="listrow$j" $row_style_attr>
455           <td colspan="$colspan">
456 |;
457     if ($lizenzen && $form->{type} eq "invoice" && $form->{vc} eq "customer") {
458       my $selected = $form->{"licensenumber_$i"};
459       my $lizenzen_quoted;
460       $form->{"lizenzen_$i"} =~ s/ selected//g;
461       $form->{"lizenzen_$i"} =~
462         s/value="${selected}"\>/value="${selected}" selected\>/;
463       $lizenzen_quoted = $form->{"lizenzen_$i"};
464       $lizenzen_quoted =~ s/\"/&quot;/g;
465       print qq|
466         <b>Lizenz\#</b>&nbsp;<select name="licensenumber_$i" size="1">
467         $form->{"lizenzen_$i"}
468         </select>
469         <input type="hidden" name="lizenzen_$i" value="${lizenzen_quoted}">
470 |;
471     }
472     if ($form->{type} !~ /_quotation/) {
473       print qq|
474           <b>$serialnumber</b>&nbsp;<input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">|;
475     }
476
477     print qq|<b>$projectnumber</b>&nbsp;| .
478       NTI($cgi->popup_menu('-name' => "project_id_$i",
479                            '-values' => \@projectnumber_values,
480                            '-labels' => \%projectnumber_labels,
481                            '-default' => $form->{"project_id_$i"}));
482
483     if ($form->{type} eq 'invoice' or $form->{type} =~ /order/) {
484       my $reqdate_term =
485         ($form->{type} eq 'invoice')
486         ? 'deliverydate'
487         : 'reqdate';    # invoice uses a different term for the same thing.
488       print qq|
489         <b>${$reqdate_term}</b>&nbsp;<input name="${reqdate_term}_$i" size="11" onBlur="check_right_date_format(this)" value="$form->{"${reqdate_term}_$i"}">
490 |;
491     }
492     my $subtotalchecked = ($form->{"subtotal_$i"}) ? "checked" : "";
493     print qq|
494           <b>|.$locale->text('Subtotal').qq|</b>&nbsp;<input type="checkbox" name="subtotal_$i" value="1" "$subtotalchecked">
495           </td>
496         </tr>
497
498 |;
499
500 ############## ENDE Neueintrag ##################
501
502     map { $form->{"${_}_base"} += $linetotal }
503       (split(/ /, $form->{"taxaccounts_$i"}));
504
505     $form->{invsubtotal} += $linetotal;
506   }
507
508   print qq|
509       </table>
510     </td>
511   </tr>
512 |;
513
514   $lxdebug->leave_sub();
515 }
516
517 ##################################################
518 # build html-code for pricegroups in variable $form->{prices_$j}
519
520 sub set_pricegroup {
521   $lxdebug->enter_sub();
522   my $rowcount = shift;
523   for $j (1 .. $rowcount) {
524     my $pricegroup_old = $form->{"pricegroup_old_$i"};
525     if ($form->{PRICES}{$j}) {
526       $len    = 0;
527       $prices = '<option value="--">' . $locale->text("none (pricegroup)") . '</option>';
528       $price  = 0;
529       foreach $item (@{ $form->{PRICES}{$j} }) {
530
531         #$price = $form->round_amount($myconfig,  $item->{price}, 5);
532         #$price = $form->format_amount($myconfig, $item->{price}, 2);
533         $price         = $item->{price};
534         $pricegroup_id = $item->{pricegroup_id};
535         $pricegroup    = $item->{pricegroup};
536
537         # build drop down list for pricegroups
538         $prices .=
539           qq|<option value="$price--$pricegroup_id"$item->{selected}>$pricegroup</option>\n|;
540
541         $len += 1;
542
543         #        map {
544         #               $form->{"${_}_$j"} =
545         #               $form->format_amount(\%myconfig, $form->{"${_}_$j"})
546         #              } qw(sellprice price_new price_old);
547
548         # set new selectedpricegroup_id and prices for "Preis"
549         if ($item->{selected} && ($pricegroup_id != 0)) {
550           $form->{"pricegroup_old_$j"} = $pricegroup_id;
551           $form->{"price_new_$j"}      = $price;
552           $form->{"sellprice_$j"}      = $price;
553         }
554         if ($pricegroup_id == 0) {
555           $form->{"price_new_$j"} = $form->{"sellprice_$j"};
556         }
557       }
558       $form->{"prices_$j"} = $prices;
559     }
560   }
561   $lxdebug->leave_sub();
562 }
563
564 sub select_item {
565   $lxdebug->enter_sub();
566   @column_index = qw(ndx partnumber description onhand unit sellprice);
567
568   $column_data{ndx}        = qq|<th>&nbsp;</th>|;
569   $column_data{partnumber} =
570     qq|<th class="listheading">| . $locale->text('Number') . qq|</th>|;
571   $column_data{description} =
572     qq|<th class="listheading">| . $locale->text('Part Description') . qq|</th>|;
573   $column_data{sellprice} =
574     qq|<th class="listheading">| . $locale->text('Price') . qq|</th>|;
575   $column_data{onhand} =
576     qq|<th class="listheading">| . $locale->text('Qty') . qq|</th>|;
577   $column_data{unit} =
578     qq|<th class="listheading">| . $locale->text('Unit') . qq|</th>|;
579   # list items with radio button on a form
580   $form->header;
581
582   $title   = $locale->text('Select from one of the items below');
583   $colspan = $#column_index + 1;
584
585   print qq|
586   <body>
587
588 <form method="post" action="$form->{script}">
589
590 <table width="100%">
591   <tr>
592     <th class="listtop" colspan="$colspan">$title</th>
593   </tr>
594   <tr height="5"></tr>
595   <tr class="listheading">|;
596
597   map { print "\n$column_data{$_}" } @column_index;
598
599   print qq|</tr>|;
600
601   my $i = 0;
602   foreach $ref (@{ $form->{item_list} }) {
603     $checked = ($i++) ? "" : "checked";
604
605     if ($lizenzen) {
606       if ($ref->{inventory_accno} > 0) {
607         $ref->{"lizenzen"} = qq|<option></option>|;
608         foreach $item (@{ $form->{LIZENZEN}{ $ref->{"id"} } }) {
609           $ref->{"lizenzen"} .=
610             qq|<option value=\"$item->{"id"}\">$item->{"licensenumber"}</option>|;
611         }
612         $ref->{"lizenzen"} .= qq|<option value="-1">Neue Lizenz</option>|;
613         $ref->{"lizenzen"} =~ s/\"/&quot;/g;
614       }
615     }
616
617     map { $ref->{$_} =~ s/\"/&quot;/g } qw(partnumber description unit);
618
619     #sk tradediscount
620     $ref->{sellprice} =
621       $form->round_amount($ref->{sellprice} * (1 - $form->{tradediscount}), 2);
622     $column_data{ndx} =
623       qq|<td><input name="ndx" class="radio" type="radio" value="$i" $checked></td>|;
624     $column_data{partnumber} =
625       qq|<td><input name="new_partnumber_$i" type="hidden" value="$ref->{partnumber}">$ref->{partnumber}</td>|;
626     $column_data{description} =
627       qq|<td><input name="new_description_$i" type="hidden" value="$ref->{description}">$ref->{description}</td>|;
628     $column_data{sellprice} =
629       qq|<td align="right"><input name="new_sellprice_$i" type="hidden" value="$ref->{sellprice}">|
630       . $form->format_amount(\%myconfig, $ref->{sellprice}, 2, "&nbsp;")
631       . qq|</td>|;
632     $column_data{onhand} =
633       qq|<td align="right"><input name="new_onhand_$i" type="hidden" value="$ref->{onhand}">|
634       . $form->format_amount(\%myconfig, $ref->{onhand}, '', "&nbsp;")
635       . qq|</td>|;
636     $column_data{unit} =
637       qq|<td>$ref->{unit}</td>|;
638     $j++;
639     $j %= 2;
640     print qq|
641 <tr class=listrow$j>|;
642
643     map { print "\n$column_data{$_}" } @column_index;
644
645     print("</tr>\n");
646
647     my @new_fields =
648       qw(bin listprice inventory_accno income_accno expense_accno unit weight
649          assembly taxaccounts partsgroup formel logdescription not_discountable
650          part_payment_id partnodes id);
651     push(@new_fields, "lizenzen") if ($lizenzen);
652
653     map({ print($cgi->hidden("-name" => "new_${_}_$i",
654                              "-value" => $ref->{$_})); } @new_fields);
655   }
656
657   print qq|
658 <tr><td colspan="8"><hr size="3" noshade></td></tr>
659 </table>
660
661 <input name="lastndx" type="hidden" value="$i">
662
663 |;
664
665   # delete action variable
666   map { delete $form->{$_} } qw(action item_list header);
667
668   # save all other form variables
669   foreach $key (keys %${form}) {
670     $form->{$key} =~ s/\"/&quot;/g;
671     print qq|<input name="$key" type="hidden" value="$form->{$key}">\n|;
672   }
673
674   print qq|
675 <input type="hidden" name="nextsub" value="item_selected">
676
677 <br>
678 <input class="submit" type="submit" name="action" value="|
679     . $locale->text('Continue') . qq|">
680 </form>
681
682 </body>
683 </html>
684 |;
685
686   $lxdebug->leave_sub();
687 }
688
689 sub item_selected {
690   $lxdebug->enter_sub();
691
692   # replace the last row with the checked row
693   $i = $form->{rowcount};
694   $i = $form->{assembly_rows} if ($form->{item} eq 'assembly');
695
696   # index for new item
697   $j = $form->{ndx};
698
699   #sk
700   #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
701   #$form->{"sellprice_$i"} = $form->{"sellprice_$i"};
702
703   # if there was a price entered, override it
704   $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
705
706   map { $form->{"${_}_$i"} = $form->{"new_${_}_$j"} }
707     qw(id partnumber description sellprice listprice inventory_accno
708        income_accno expense_accno bin unit weight assembly taxaccounts
709        partsgroup formel longdescription not_discountable partnotes);
710   if ($form->{"part_payment_id_$i"} ne "") {
711     $form->{payment_id} = $form->{"part_payment_id_$i"};
712   }
713
714   if ($lizenzen) {
715     map { $form->{"${_}_$i"} = $form->{"new_${_}_$j"} } qw(lizenzen);
716   }
717
718   ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
719   $dec           = length $dec;
720   $decimalplaces = ($dec > 2) ? $dec : 2;
721
722   if ($sellprice) {
723     $form->{"sellprice_$i"} = $sellprice;
724   } else {
725
726     # if there is an exchange rate adjust sellprice
727     if (($form->{exchangerate} * 1) != 0) {
728       $form->{"sellprice_$i"} /= $form->{exchangerate};
729       $form->{"sellprice_$i"} =
730         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
731     }
732   }
733
734   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
735     qw(sellprice listprice weight);
736
737   $form->{sellprice} += ($form->{"sellprice_$i"} * $form->{"qty_$i"});
738   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
739   
740   if ($form->{"not_discountable_$i"}) {
741     $form->{"discount_$i"} = 0;
742   }
743
744   $amount =
745     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
746     $form->{"qty_$i"};
747   map { $form->{"${_}_base"} += $amount }
748     (split / /, $form->{"taxaccounts_$i"});
749   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
750     $form->{"taxaccounts_$i"}
751     if !$form->{taxincluded};
752
753   $form->{creditremaining} -= $amount;
754
755   $form->{"runningnumber_$i"} = $i;
756
757   # delete all the new_ variables
758   for $i (1 .. $form->{lastndx}) {
759     map { delete $form->{"new_${_}_$i"} }
760       qw(partnumber description sellprice bin listprice inventory_accno income_accno expense_accno unit assembly taxaccounts id);
761   }
762
763   map { delete $form->{$_} } qw(ndx lastndx nextsub);
764
765   # format amounts
766   map {
767     $form->{"${_}_$i"} =
768       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
769   } qw(sellprice listprice) if $form->{item} ne 'assembly';
770
771   # get pricegroups for parts
772   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
773
774   # build up html code for prices_$i
775   set_pricegroup($form->{rowcount});
776
777   &display_form;
778
779   $lxdebug->leave_sub();
780 }
781
782 sub new_item {
783   $lxdebug->enter_sub();
784
785   # change callback
786   $form->{old_callback} = $form->escape($form->{callback}, 1);
787   $form->{callback} = $form->escape("$form->{script}?action=display_form", 1);
788
789   # delete action
790   delete $form->{action};
791
792   # save all other form variables in a previousform variable
793   foreach $key (keys %$form) {
794
795     # escape ampersands
796     $form->{$key} =~ s/&/%26/g;
797     $previousform .= qq|$key=$form->{$key}&|;
798   }
799   chop $previousform;
800   $previousform = $form->escape($previousform, 1);
801
802   $i = $form->{rowcount};
803   map { $form->{"${_}_$i"} =~ s/\"/&quot;/g } qw(partnumber description);
804
805   $form->header;
806
807   print qq|
808 <body>
809
810 <h4 class="error">| . $locale->text('Item not on file!') . qq|
811
812 <p>
813 | . $locale->text('What type of item is this?') . qq|</h4>
814
815 <form method="post" action="ic.pl">
816
817 <p>
818
819   <input class="radio" type="radio" name="item" value="part" checked>&nbsp;|
820     . $locale->text('Part') . qq|<br>
821   <input class="radio" type="radio" name="item" value="service">&nbsp;|
822     . $locale->text('Service');
823 print $cgi->hidden("-name" => "previousform", "-value" => $previousform);
824 map({ print($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } 
825      ("rowcount", "vc", "path", "login", "password"));
826      map({ print($cgi->hidden("-name" => $_, "-value" => $form->{"$__$i"})); }
827      ("partnumber", "description"));
828 print $cgi->hidden("-name" => "taxaccount2", "-value" => $form->{taxaccounts});
829
830 print qq|
831 <input type="hidden" name="nextsub" value="add">
832
833 <p>
834 <input class="submit" type="submit" name="action" value="|
835     . $locale->text('Continue') . qq|">
836 </form>
837
838 </body>
839 </html>
840 |;
841
842   $lxdebug->leave_sub();
843 }
844
845 sub display_form {
846   $lxdebug->enter_sub();
847
848   relink_accounts();
849
850   my $new_rowcount = $form->{"rowcount"} * 1 + 1;
851   $form->{"project_id_${new_rowcount}"} = $form->{"globalproject_id"};
852
853   $form->language_payment(\%myconfig);
854
855   # if we have a display_form
856   if ($form->{display_form}) {
857     &{"$form->{display_form}"};
858     exit;
859   }
860
861   Common::webdav_folder($form) if ($webdav);
862
863   #   if (   $form->{print_and_post}
864   #       && $form->{second_run}
865   #       && ($form->{action} eq "display_form")) {
866   #     for (keys %$form) { $old_form->{$_} = $form->{$_} }
867   #     $old_form->{rowcount}++;
868   #
869   #     #$form->{rowcount}--;
870   #     #$form->{rowcount}--;
871   #
872   #     $form->{print_and_post} = 0;
873   #
874   #     &print_form($old_form);
875   #     exit;
876   #   }
877   #
878   #   $form->{action}   = "";
879   #   $form->{resubmit} = 0;
880   #
881   #   if ($form->{print_and_post} && !$form->{second_run}) {
882   #     $form->{second_run} = 1;
883   #     $form->{action}     = "display_form";
884   #     $form->{rowcount}--;
885   #     my $rowcount = $form->{rowcount};
886   #
887   #     # get pricegroups for parts
888   #     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
889   #
890   #     # build up html code for prices_$i
891   #     set_pricegroup($rowcount);
892   #
893   #     $form->{resubmit} = 1;
894   #
895   #   }
896   &form_header;
897
898   $numrows    = ++$form->{rowcount};
899   $subroutine = "display_row";
900
901   if ($form->{item} eq 'part') {
902
903     #set preisgruppenanzahl
904     $numrows    = $form->{price_rows};
905     $subroutine = "price_row";
906
907     &{$subroutine}($numrows);
908
909     $numrows    = ++$form->{makemodel_rows};
910     $subroutine = "makemodel_row";
911   }
912   if ($form->{item} eq 'assembly') {
913     $numrows    = $form->{price_rows};
914     $subroutine = "price_row";
915
916     &{$subroutine}($numrows);
917
918     $numrows    = ++$form->{makemodel_rows};
919     $subroutine = "makemodel_row";
920
921     # create makemodel rows
922     &{$subroutine}($numrows);
923
924     $numrows    = ++$form->{assembly_rows};
925     $subroutine = "assembly_row";
926   }
927   if ($form->{item} eq 'service') {
928     $numrows    = $form->{price_rows};
929     $subroutine = "price_row";
930
931     &{$subroutine}($numrows);
932
933     $numrows = 0;
934   }
935
936   # create rows
937   &{$subroutine}($numrows) if $numrows;
938
939   &form_footer;
940
941   $lxdebug->leave_sub();
942 }
943
944 sub check_form {
945   $lxdebug->enter_sub();
946   my @a     = ();
947   my $count = 0;
948   my @flds  = (
949     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)
950   );
951
952
953   # remove any makes or model rows
954   if ($form->{item} eq 'part') {
955     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
956       qw(listprice sellprice lastcost weight rop);
957
958     @flds = (make, model);
959     for my $i (1 .. ($form->{makemodel_rows})) {
960       if (($form->{"make_$i"} ne "") || ($form->{"model_$i"} ne "")) {
961         push @a, {};
962         my $j = $#a;
963
964         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
965         $count++;
966       }
967     }
968
969     $form->redo_rows(\@flds, \@a, $count, $form->{makemodel_rows});
970     $form->{makemodel_rows} = $count;
971
972   } elsif ($form->{item} eq 'assembly') {
973
974     $form->{sellprice} = 0;
975     $form->{weight}    = 0;
976     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
977       qw(listprice rop stock);
978
979     @flds =
980       qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup);
981
982     for my $i (1 .. ($form->{assembly_rows} - 1)) {
983       if ($form->{"qty_$i"}) {
984         push @a, {};
985         my $j = $#a;
986
987         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
988
989         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
990
991         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
992
993         $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"});
994         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"});
995         $count++;
996       }
997     }
998
999     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
1000
1001     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
1002     $form->{assembly_rows} = $count;
1003
1004     $count = 0;
1005     @flds  = qw(make model);
1006     @a     = ();
1007
1008     for my $i (1 .. ($form->{makemodel_rows})) {
1009       if (($form->{"make_$i"} ne "") || ($form->{"model_$i"} ne "")) {
1010         push @a, {};
1011         my $j = $#a;
1012
1013         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
1014         $count++;
1015       }
1016     }
1017
1018     $form->redo_rows(\@flds, \@a, $count, $form->{makemodel_rows});
1019     $form->{makemodel_rows} = $count;
1020
1021   } else {
1022
1023     # this section applies to invoices and orders
1024     # remove any empty numbers
1025     if ($form->{rowcount}) {
1026       for my $i (1 .. $form->{rowcount} - 1) {
1027         if ($form->{"partnumber_$i"}) {
1028           push @a, {};
1029           my $j = $#a;
1030
1031           map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
1032           $count++;
1033           if ($lizenzen) {
1034             if ($form->{"licensenumber_$i"} == -1) {
1035               &new_license($i);
1036               exit;
1037             }
1038           }
1039         }
1040       }
1041
1042       $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
1043       $form->{rowcount} = $count;
1044
1045       $form->{creditremaining} -= &invoicetotal;
1046
1047     }
1048   }
1049
1050   #sk
1051   # if pricegroups
1052   if (   $form->{type} =~ (/sales_quotation/)
1053       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
1054       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
1055       or ($form->{type} =~ /sales_order/)) {
1056
1057     # get pricegroups for parts
1058     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1059
1060     # build up html code for prices_$i
1061     set_pricegroup($form->{rowcount});
1062
1063   }
1064
1065   &display_form;
1066
1067   $lxdebug->leave_sub();
1068 }
1069
1070 sub invoicetotal {
1071   $lxdebug->enter_sub();
1072
1073   $form->{oldinvtotal} = 0;
1074
1075   # add all parts and deduct paid
1076   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
1077
1078   my ($amount, $sellprice, $discount, $qty);
1079
1080   for my $i (1 .. $form->{rowcount}) {
1081     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
1082     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
1083     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1084
1085     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
1086
1087     $amount = $sellprice * (1 - $discount / 100) * $qty;
1088     map { $form->{"${_}_base"} += $amount }
1089       (split (/ /, $form->{"taxaccounts_$i"}));
1090     $form->{oldinvtotal} += $amount;
1091   }
1092
1093   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
1094     split(/ /, $form->{taxaccounts})
1095     if !$form->{taxincluded};
1096
1097   $form->{oldtotalpaid} = 0;
1098   for $i (1 .. $form->{paidaccounts}) {
1099     $form->{oldtotalpaid} += $form->{"paid_$i"};
1100   }
1101
1102   $lxdebug->leave_sub();
1103
1104   # return total
1105   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
1106 }
1107
1108 sub validate_items {
1109   $lxdebug->enter_sub();
1110
1111   # check if items are valid
1112   if ($form->{rowcount} == 1) {
1113     &update;
1114     exit;
1115   }
1116
1117   for $i (1 .. $form->{rowcount} - 1) {
1118     $form->isblank("partnumber_$i",
1119                    $locale->text('Number missing in Row') . " $i");
1120   }
1121
1122   $lxdebug->leave_sub();
1123 }
1124
1125 sub order {
1126   $lxdebug->enter_sub();
1127   if ($form->{second_run}) {
1128     $form->{print_and_post} = 0;
1129   }
1130   $form->{ordnumber} = $form->{invnumber};
1131
1132   map { delete $form->{$_} } qw(id printed emailed queued);
1133   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
1134     $form->{title} = $locale->text('Add Purchase Order');
1135     $form->{vc}    = 'vendor';
1136     $form->{type}  = 'purchase_order';
1137     $buysell       = 'sell';
1138   }
1139   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
1140     $form->{title} = $locale->text('Add Sales Order');
1141     $form->{vc}    = 'customer';
1142     $form->{type}  = 'sales_order';
1143     $buysell       = 'buy';
1144   }
1145   $form->{script} = 'oe.pl';
1146
1147   $form->{shipto} = 1;
1148
1149   $form->{rowcount}--;
1150
1151   $form->{cp_id} *= 1;
1152
1153   require "$form->{path}/$form->{script}";
1154   my $script = $form->{"script"};
1155   $script =~ s|.*/||;
1156   $script =~ s|.pl$||;
1157   $locale = new Locale($language, $script);
1158
1159   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
1160
1161   $currency = $form->{currency};
1162
1163   &order_links;
1164
1165   $form->{currency}     = $currency;
1166   $form->{exchangerate} = "";
1167   $form->{forex}        = "";
1168   $form->{exchangerate} = $exchangerate
1169     if (
1170         $form->{forex} = (
1171                   $exchangerate =
1172                     $form->check_exchangerate(
1173                     \%myconfig, $form->{currency}, $form->{transdate}, $buysell
1174                     )));
1175
1176   for $i (1 .. $form->{rowcount}) {
1177     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
1178                                                      $form->{"${_}_${i}"})
1179             if ($form->{"${_}_${i}"}) }
1180         qw(ship qty sellprice listprice basefactor));
1181   }
1182
1183   &prepare_order;
1184   &display_form;
1185
1186   $lxdebug->leave_sub();
1187 }
1188
1189 sub quotation {
1190   $lxdebug->enter_sub();
1191   if ($form->{second_run}) {
1192     $form->{print_and_post} = 0;
1193   }
1194   map { delete $form->{$_} } qw(id printed emailed queued);
1195
1196   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
1197     $form->{title} = $locale->text('Add Request for Quotation');
1198     $form->{vc}    = 'vendor';
1199     $form->{type}  = 'request_quotation';
1200     $buysell       = 'sell';
1201   }
1202   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
1203     $form->{title} = $locale->text('Add Quotation');
1204     $form->{vc}    = 'customer';
1205     $form->{type}  = 'sales_quotation';
1206     $buysell       = 'buy';
1207   }
1208
1209   $form->{cp_id} *= 1;
1210
1211   $form->{script} = 'oe.pl';
1212
1213   $form->{shipto} = 1;
1214
1215   $form->{rowcount}--;
1216
1217   require "$form->{path}/$form->{script}";
1218
1219   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
1220
1221   $currency = $form->{currency};
1222
1223   &order_links;
1224
1225   $form->{currency}     = $currency;
1226   $form->{exchangerate} = "";
1227   $form->{forex}        = "";
1228   $form->{exchangerate} = $exchangerate
1229     if (
1230         $form->{forex} = (
1231                   $exchangerate =
1232                     $form->check_exchangerate(
1233                     \%myconfig, $form->{currency}, $form->{transdate}, $buysell
1234                     )));
1235
1236   for $i (1 .. $form->{rowcount}) {
1237     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
1238                                                      $form->{"${_}_${i}"})
1239             if ($form->{"${_}_${i}"}) }
1240         qw(ship qty sellprice listprice basefactor));
1241   }
1242
1243   &prepare_order;
1244   &display_form;
1245
1246   $lxdebug->leave_sub();
1247 }
1248
1249 sub request_for_quotation {
1250   quotation();
1251 }
1252
1253 sub edit_e_mail {
1254   $lxdebug->enter_sub();
1255   if ($form->{second_run}) {
1256     $form->{print_and_post} = 0;
1257     $form->{resubmit}       = 0;
1258   }
1259   if ($myconfig{role} eq 'admin') {
1260     $bcc = qq|
1261     <tr>
1262       <th align="right" nowrap="true">| . $locale->text('Bcc') . qq|</th>
1263       <td><input name="bcc" size="30" value="| . Q($form->{bcc}) . qq|"></td>
1264     </tr>
1265 |;
1266   }
1267
1268   if ($form->{formname} =~ /(pick|packing|bin)_list/) {
1269     $form->{email} = $form->{shiptoemail} if $form->{shiptoemail};
1270   }
1271
1272   if ($form->{"cp_id"} && !$form->{"email"}) {
1273     CT->get_contact(\%myconfig, $form);
1274     $form->{"email"} = $form->{"cp_email"};
1275   }
1276
1277   $name = $form->{ $form->{vc} };
1278   $name =~ s/--.*//g;
1279   $title = $locale->text('E-mail') . " $name";
1280
1281   $form->{oldmedia} = $form->{media};
1282   $form->{media}    = "email";
1283
1284   my %formname_translations =
1285     (
1286      "bin_list" => $locale->text('Bin List'),
1287      "credit_note" => $locale->text('Credit Note'),
1288      "invoice" => $locale->text('Invoice'),
1289      "packing_list" => $locale->text('Packing List'),
1290      "pick_list" => $locale->text('Pick List'),
1291      "proforma" => $locale->text('Proforma Invoice'),
1292      "purchase_order" => $locale->text('Purchase Order'),
1293      "request_quotation" => $locale->text('RFQ'),
1294      "sales_order" => $locale->text('Confirmation'),
1295      "sales_quotation" => $locale->text('Quotation'),
1296      "storno_invoice" => $locale->text('Storno Invoice'),
1297      "storno_packing_list" => $locale->text('Storno Packing List'),
1298     );
1299
1300   my $attachment_filename = $formname_translations{$form->{"formname"}};
1301   my $prefix;
1302
1303   if (grep({ $form->{"type"} eq $_ } qw(invoice credit_note))) {
1304     $prefix = "inv";
1305   } elsif ($form->{"type"} =~ /_quotation$/) {
1306     $prefix = "quo";
1307   } else {
1308     $prefix = "ord";
1309   }
1310
1311   if ($attachment_filename && $form->{"${prefix}number"}) {
1312     $attachment_filename .= "_" . $form->{"${prefix}number"} .
1313       ($form->{"format"} =~ /pdf/i ? ".pdf" :
1314        $form->{"format"} =~ /postscript/i ? ".ps" :
1315        $form->{"format"} =~ /opendocument/i ? ".odt" :
1316        $form->{"format"} =~ /html/i ? ".html" : "");
1317     $attachment_filename =~ s/ /_/g;
1318     my %umlaute =
1319       (
1320        "ä" => "ae", "ö" => "oe", "ü" => "ue",
1321        "Ä" => "Ae", "Ö" => "Oe", "Ãœ" => "Ue",
1322        "ß" => "ss"
1323       );
1324     map({ $attachment_filename =~ s/$_/$umlaute{$_}/g; } keys(%umlaute));
1325   } else {
1326     $attachment_filename = "";
1327   }
1328
1329   if ($form->{"email"}) {
1330     $form->{"fokus"} = "Form.subject";
1331   } else {
1332     $form->{"fokus"} = "Form.email";
1333   }
1334   $form->header;
1335
1336   print qq|
1337 <body onload="fokus()">
1338
1339 <form name="Form" method="post" action="$form->{script}">
1340
1341 <table width="100%">
1342   <tr class="listtop">
1343     <th class="listtop">$title</th>
1344   </tr>
1345   <tr height="5"></tr>
1346   <tr>
1347     <td>
1348       <table>
1349         <tr>
1350           <th align="right" nowrap>| . $locale->text('To') . qq|</th>
1351           <td><input name="email" size="30" value="| .
1352           Q($form->{"email"}) . qq|"></td>
1353         </tr>
1354         <tr>
1355           <th align="right" nowrap>| . $locale->text('Cc') . qq|</th>
1356           <td><input name="cc" size="30" value="| .
1357           Q($form->{"cc"}) . qq|"></td>
1358         </tr>
1359         $bcc
1360         <tr>
1361           <th align="right" nowrap>| . $locale->text('Subject') . qq|</th>
1362           <td><input name="subject" size="30" value="| .
1363           Q($form->{"subject"}) . qq|"></td>
1364         </tr>
1365         <tr>
1366           <th align="right" nowrap>| . $locale->text('Attachment name') .
1367           qq|</th>
1368           <td><input name="attachment_filename" size="30" value="| .
1369           Q($attachment_filename) . qq|"></td>
1370       </table>
1371     </td>
1372   </tr>
1373   <tr>
1374     <td>
1375       <table>
1376         <tr>
1377           <th align="left" nowrap>| . $locale->text('Message') . qq|</th>
1378         </tr>
1379         <tr>
1380           <td><textarea name="message" rows="15" cols="60" wrap="soft">| .
1381           H($form->{"message"}) . qq|</textarea></td>
1382         </tr>
1383       </table>
1384     </td>
1385   </tr>
1386   <tr>
1387     <td>
1388 |;
1389
1390   print_options();
1391
1392   map { delete $form->{$_} }
1393     qw(action email cc bcc subject message formname sendmode format header override);
1394
1395   # save all other variables
1396   foreach $key (keys %$form) {
1397     $form->{$key} =~ s/\"/&quot;/g;
1398     print qq|<input type="hidden" name="$key" value="| . Q($form->{$key}) . qq|">\n|;
1399   }
1400
1401   print qq|
1402     </td>
1403   </tr>
1404   <tr>
1405     <td><hr size="3" noshade></td>
1406   </tr>
1407 </table>
1408
1409 <input type="hidden" name="nextsub" value="send_email">
1410
1411 <br>
1412 <input name="action" class="submit" type="submit" value="|
1413     . $locale->text('Continue') . qq|">
1414 </form>
1415
1416 </body>
1417 </html>
1418 |;
1419
1420   $lxdebug->leave_sub();
1421 }
1422
1423 sub send_email {
1424   $lxdebug->enter_sub();
1425
1426   my $callback = $form->{script} . "?action=edit";
1427   map({ $callback .= "\&${_}=" . E($form->{$_}); }
1428       qw(login password path type id));
1429
1430   print_form("return");
1431
1432   $form->{callback} = $callback;
1433   $form->redirect();
1434
1435   $lxdebug->leave_sub();
1436 }
1437
1438 # generate the printing options displayed at the bottom of oe and is forms.
1439 # this function will attempt to guess what type of form is displayed, and will generate according options
1440 #
1441 # about the coding: 
1442 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
1443 # the opthash function builds hashrefs which are then pieced together for the template arrays.
1444 # unneeded options are "undef"ed out, and then grepped out. 
1445 #
1446 # the inline options is untested, but intended to be used later in metatemplating
1447 sub print_options {
1448   $lxdebug->enter_sub() and my ($inline) = @_;
1449
1450   # names 3 parameters and returns a hashref, for use in templates
1451   sub opthash { +{ value => shift, selected => shift, oname => shift } }
1452   (@FORMNAME, @FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
1453
1454   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
1455   $form->{sendmode}   = "attachment";
1456   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
1457   $form->{copies}     = $form->{copies} || $myconfig{copies} || 3;
1458   $form->{media}      = $form->{media} || $myconfig{default_media} || "screen";
1459   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
1460                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
1461
1462   $form->{PD}{ $form->{formname} } = "selected";
1463   $form->{DF}{ $form->{format} }   = "selected";
1464   $form->{OP}{ $form->{media} }    = "selected";
1465   $form->{SM}{ $form->{formname} } = "selected";
1466
1467   push @FORMNAME, grep $_,
1468     ($form->{type} eq 'purchase_order') ? (
1469       opthash("purchase_order", $form->{PD}{purchase_order}, $locale->text('Purchase Order')),
1470       opthash("bin_list", $form->{PD}{bin_list}, $locale->text('Bin List')) 
1471     ) : undef,
1472     ($form->{type} eq 'credit_note') ?
1473       opthash("credit_note", $form->{PD}{credit_note}, $locale->text('Credit Note')) : undef,
1474     ($form->{type} eq 'sales_order') ? (
1475       opthash("sales_order", $form->{PD}{sales_order}, $locale->text('Confirmation')),
1476       opthash("proforma", $form->{PD}{proforma}, $locale->text('Proforma Invoice')),
1477       opthash("pick_list", $form->{PD}{pick_list}, $locale->text('Pick List')),
1478       opthash("packing_list", $form->{PD}{packing_list}, $locale->text('Packing List')) 
1479     ) : undef,
1480     ($form->{type} =~ /_quotation$/) ?
1481       opthash("$`_quotation", $form->{PD}{"$`_quotation"}, $locale->text('Quotation')) : undef,
1482     ($form->{type} eq 'invoice') ? (
1483       opthash("invoice", $form->{PD}{invoice}, $locale->text('Invoice')),
1484       opthash("proforma", $form->{PD}{proforma}, $locale->text('Proforma Invoice')),
1485       opthash("packing_list", $form->{PD}{packing_list}, $locale->text('Packing List'))
1486     ) : undef,
1487     ($form->{type} eq 'invoice' && $form->{storno}) ? (
1488       opthash("storno_invoice", $form->{PD}{storno_invoice}, $locale->text('Storno Invoice')),
1489       opthash("storno_packing_list", $form->{PD}{storno_packing_list}, $locale->text('Storno Packing List')) 
1490     ) : undef,
1491     ($form->{type} eq 'credit_note') ?
1492       opthash("credit_note", $form->{PD}{credit_note}, $locale->text('Credit Note')) : undef;
1493
1494   push @SENDMODE, 
1495     opthash("attachment", $form->{SM}{attachment}, $locale->text('Attachment')),
1496     opthash("inline", $form->{SM}{inline}, $locale->text('In-line'))
1497       if ($form->{media} eq 'email');
1498
1499   push @MEDIA, grep $_,
1500       opthash("screen", $form->{OP}{screen}, $locale->text('Screen')),
1501     (scalar @{ $form->{printers} } && $latex_templates) ?
1502       opthash("printer", $form->{OP}{printer}, $locale->text('Printer')) : undef,
1503     ($latex_templates) ? 
1504       opthash("queue", $form->{OP}{queue}, $locale->text('Queue')) : undef
1505         if ($form->{media} ne 'email');
1506
1507   push @FORMAT, grep $_,
1508     ($opendocument_templates && $openofficeorg_writer_bin && $xvfb_bin && (-x $openofficeorg_writer_bin) && (-x $xvfb_bin)) ?
1509       opthash("opendocument_pdf", $form->{DF}{"opendocument_pdf"}, $locale->text("PDF (OpenDocument/OASIS)")) : undef,
1510     ($latex_templates) ? (
1511       opthash("pdf", $form->{DF}{pdf}, $locale->text('PDF')),
1512       opthash("postscript", $form->{DF}{postscript}, $locale->text('Postscript'))
1513     ) : undef,
1514       opthash("html", $form->{DF}{html}, "HTML"),
1515     ($opendocument_templates) ?
1516       opthash("opendocument", $form->{DF}{opendocument}, $locale->text("OpenDocument/OASIS")) : undef;
1517
1518   push @LANGUAGE_ID, 
1519     map { opthash($_->{id}, ($_->{id} eq $form->{language} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
1520       if (ref $form->{languages} eq 'ARRAY');
1521
1522   push @PRINTER_ID, 
1523     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
1524       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
1525
1526   @SELECTS = map { sname => lc $_, DATA => \@$_, show => scalar @$_ }, qw(FORMNAME LANGUAGE_ID FORMAT SENDMODE MEDIA PRINTER_ID);
1527
1528   %template_vars = (
1529     display_copies       => scalar @{ $form->{printers} } && $latex_templates && $form->{media} ne 'email',
1530     display_remove_draft => (!$form->{id} && $form->{draft_id}),
1531     groupitems_checked   => $form->{groupitems} ? "checked" : '',
1532     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
1533   );
1534
1535   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
1536
1537   if ($inline) {
1538     $lxdebug->leave_sub() and return $print_options;
1539   } else {
1540     print $print_options; $lxdebug->leave_sub();
1541   }
1542 }
1543
1544 sub print {
1545   $lxdebug->enter_sub();
1546
1547   # if this goes to the printer pass through
1548   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1549     $form->error($locale->text('Select postscript or PDF!'))
1550       if ($form->{format} !~ /(postscript|pdf)/);
1551
1552     $old_form = new Form;
1553     map { $old_form->{$_} = $form->{$_} } keys %$form;
1554   }
1555
1556   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1557     if ($form->{formname} eq "proforma") {
1558       $form->{proforma} = 1;
1559     }
1560     $form->{print_and_save} = 1;
1561     my $formname = $form->{formname};
1562     &save();
1563     $form->{formname} = $formname;
1564     &edit();
1565     exit;
1566   }
1567
1568   &print_form($old_form);
1569
1570   $lxdebug->leave_sub();
1571 }
1572
1573 sub print_form {
1574   $lxdebug->enter_sub();
1575   my ($old_form) = @_;
1576
1577   $inv       = "inv";
1578   $due       = "due";
1579   $numberfld = "invnumber";
1580
1581   $display_form =
1582     ($form->{display_form}) ? $form->{display_form} : "display_form";
1583
1584   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1585   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1586
1587   if ($form->{formname} eq "invoice") {
1588     $form->{label} = $locale->text('Invoice');
1589   }
1590   if ($form->{formname} eq "packing_list") {
1591
1592     # this is from an invoice
1593     $form->{label} = $locale->text('Packing List');
1594   }
1595   if ($form->{formname} eq 'sales_order') {
1596     $inv                  = "ord";
1597     $due                  = "req";
1598     $form->{"${inv}date"} = $form->{transdate};
1599     $form->{label}        = $locale->text('Sales Order');
1600     $numberfld            = "sonumber";
1601     $order                = 1;
1602   }
1603
1604   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1605     $inv                  = "inv";
1606     $due                  = "due";
1607     $form->{"${inv}date"} = $form->{invdate};
1608     $form->{label}        = $locale->text('Proforma Invoice');
1609     $numberfld            = "sonumber";
1610     $order                = 0;
1611   }
1612
1613   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1614     $inv                  = "inv";
1615     $due                  = "due";
1616     $form->{"${inv}date"} = $form->{transdate};
1617     $form->{"invdate"}    = $form->{transdate};
1618     $form->{invnumber}    = $form->{ordnumber};
1619     $form->{label}        = $locale->text('Proforma Invoice');
1620     $numberfld            = "sonumber";
1621     $order                = 1;
1622   }
1623
1624   if ($form->{formname} eq 'packing_list' && $form->{type} ne 'invoice') {
1625
1626     # we use the same packing list as from an invoice
1627     $inv = "ord";
1628     $due = "req";
1629     $form->{invdate} = $form->{"${inv}date"} = $form->{transdate};
1630     $form->{label} = $locale->text('Packing List');
1631     $order = 1;
1632     # set invnumber for template packing_list 
1633     $form->{invnumber}   = $form->{ordnumber};
1634   }
1635   if ($form->{formname} eq 'pick_list') {
1636     $inv                  = "ord";
1637     $due                  = "req";
1638     $form->{"${inv}date"} =
1639       ($form->{transdate}) ? $form->{transdate} : $form->{invdate};
1640     $form->{label} = $locale->text('Pick List');
1641     $order = 1 unless $form->{type} eq 'invoice';
1642   }
1643   if ($form->{formname} eq 'purchase_order') {
1644     $inv                  = "ord";
1645     $due                  = "req";
1646     $form->{"${inv}date"} = $form->{transdate};
1647     $form->{label}        = $locale->text('Purchase Order');
1648     $numberfld            = "ponumber";
1649     $order                = 1;
1650   }
1651   if ($form->{formname} eq 'bin_list') {
1652     $inv                  = "ord";
1653     $due                  = "req";
1654     $form->{"${inv}date"} = $form->{transdate};
1655     $form->{label}        = $locale->text('Bin List');
1656     $order                = 1;
1657   }
1658   if ($form->{formname} eq 'sales_quotation') {
1659     $inv                  = "quo";
1660     $due                  = "req";
1661     $form->{"${inv}date"} = $form->{transdate};
1662     $form->{label}        = $locale->text('Quotation');
1663     $numberfld            = "sqnumber";
1664     $order                = 1;
1665   }
1666
1667   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1668     $inv                  = "quo";
1669     $due                  = "req";
1670     $form->{"${inv}date"} = $form->{transdate};
1671     $form->{"invdate"}    = $form->{transdate};
1672     $form->{label}        = $locale->text('Proforma Invoice');
1673     $numberfld            = "sqnumber";
1674     $order                = 1;
1675   }
1676
1677   if ($form->{formname} eq 'request_quotation') {
1678     $inv                  = "quo";
1679     $due                  = "req";
1680     $form->{"${inv}date"} = $form->{transdate};
1681     $form->{label}        = $locale->text('Quotation');
1682     $numberfld            = "rfqnumber";
1683     $order                = 1;
1684   }
1685
1686   $form->isblank("email", $locale->text('E-mail address missing!'))
1687     if ($form->{media} eq 'email');
1688   $form->isblank("${inv}date",
1689            $locale->text($form->{label}) 
1690            . ": "
1691            . $locale->text(' Date missing!'));
1692
1693   # $locale->text('Invoice Number missing!')
1694   # $locale->text('Invoice Date missing!')
1695   # $locale->text('Packing List Number missing!')
1696   # $locale->text('Packing List Date missing!')
1697   # $locale->text('Order Number missing!')
1698   # $locale->text('Order Date missing!')
1699   # $locale->text('Quotation Number missing!')
1700   # $locale->text('Quotation Date missing!')
1701
1702   # assign number
1703   $form->{what_done} = $form->{formname};
1704   if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) {
1705     $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld);
1706     if ($form->{media} ne 'email') {
1707
1708       # get pricegroups for parts
1709       IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1710
1711       # build up html code for prices_$i
1712       set_pricegroup($form->{rowcount});
1713
1714       $form->{rowcount}--;
1715
1716       &{"$display_form"};
1717       # saving the history
1718           if(!exists $form->{addition}) {
1719             $form->{addition} = "PRINTED";
1720             $form->save_history($form->dbconnect(\%myconfig));
1721       }
1722       # /saving the history
1723       exit;
1724     }
1725   }
1726
1727   &validate_items;
1728
1729   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1730   my ($saved_email, $saved_cc, $saved_bcc) =
1731     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1732
1733   $language_saved = $form->{language_id};
1734   $payment_id_saved = $form->{payment_id};
1735   $salesman_id_saved = $form->{salesman_id};
1736   $cp_id_saved = $form->{cp_id};
1737
1738   &{"$form->{vc}_details"}();
1739
1740   $form->{language_id} = $language_saved;
1741   $form->{payment_id} = $payment_id_saved;
1742
1743   $form->{"email"} = $saved_email if ($saved_email);
1744   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1745   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1746
1747   if (!$cp_id_saved) {
1748     # No contact was selected. Delete all contact variables because
1749     # IS->customer_details() and IR->vendor_details() get the default
1750     # contact anyway.
1751     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1752   }
1753
1754   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1755   if ($form->{"language_id"}) {
1756     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1757       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1758   } else {
1759     $output_dateformat = $myconfig{"dateformat"};
1760     $output_numberformat = $myconfig{"numberformat"};
1761     $output_longdates = 1;
1762   }
1763
1764   ($form->{employee}) = split /--/, $form->{employee};
1765
1766   # create the form variables
1767   if ($order) {
1768     OE->order_details(\%myconfig, \%$form);
1769   } else {
1770     IS->invoice_details(\%myconfig, \%$form, $locale);
1771   }
1772
1773   $form->get_salesman(\%myconfig, $salesman_id_saved);
1774
1775   if ($form->{shipto_id}) {
1776     $form->get_shipto(\%myconfig);
1777   }
1778
1779   @a = qw(name street zipcode city country);
1780
1781   $shipto = 1;
1782
1783   # if there is no shipto fill it in from billto
1784   foreach $item (@a) {
1785     if ($form->{"shipto$item"}) {
1786       $shipto = 0;
1787       last;
1788     }
1789   }
1790
1791   if ($shipto) {
1792     if (   $form->{formname} eq 'purchase_order'
1793         || $form->{formname} eq 'request_quotation') {
1794       $form->{shiptoname}   = $myconfig{company};
1795       $form->{shiptostreet} = $myconfig{address};
1796     } else {
1797       map { $form->{"shipto$_"} = $form->{$_} } @a;
1798     }
1799   }
1800
1801   $form->{notes} =~ s/^\s+//g;
1802
1803   $form->{templates} = "$myconfig{templates}";
1804
1805   $form->{language} = $form->get_template_language(\%myconfig);
1806   $form->{printer_code} = $form->get_printer_code(\%myconfig);
1807
1808   if ($form->{language} ne "") {
1809     map({ $form->{"unit"}->[$_] =
1810             AM->translate_units($form, $form->{"language"},
1811                                 $form->{"unit"}->[$_], $form->{"qty"}->[$_]); }
1812         (0..scalar(@{$form->{"unit"}}) - 1));
1813     $form->{language} = "_" . $form->{language};
1814   }
1815
1816   # Format dates.
1817   format_dates($output_dateformat, $output_longdates,
1818                qw(invdate orddate quodate pldate duedate reqdate transdate
1819                   shippingdate deliverydate validitydate paymentdate
1820                   datepaid transdate_oe deliverydate_oe
1821                   employee_startdate employee_enddate
1822                   ),
1823                grep({ /^datepaid_\d+$/ ||
1824                         /^transdate_oe_\d+$/ ||
1825                         /^deliverydate_oe_\d+$/ ||
1826                         /^reqdate_\d+$/ ||
1827                         /^deliverydate_\d+$/ ||
1828                         /^transdate_\d+$/
1829                     } keys(%{$form})));
1830
1831   reformat_numbers($output_numberformat, 2,
1832                    qw(invtotal ordtotal quototal subtotal linetotal
1833                       listprice sellprice netprice discount
1834                       tax taxbase),
1835                    grep({ /^linetotal_\d+$/ ||
1836                             /^listprice_\d+$/ ||
1837                             /^sellprice_\d+$/ ||
1838                             /^netprice_\d+$/ ||
1839                             /^taxbase_\d+$/ ||
1840                             /^discount_\d+$/ ||
1841                             /^tax_\d+$/
1842                         } keys(%{$form})));
1843
1844   reformat_numbers($output_numberformat, undef,
1845                    qw(qty),
1846                    grep({ /^qty_\d+$/
1847                         } keys(%{$form})));
1848
1849   if ($form->{printer_code} ne "") {
1850     $form->{printer_code} = "_" . $form->{printer_code};
1851   }
1852
1853   $form->{IN} = "$form->{formname}$form->{language}$form->{printer_code}.html";
1854   if ($form->{format} eq 'postscript') {
1855     $form->{postscript} = 1;
1856     $form->{IN} =~ s/html$/tex/;
1857   } elsif ($form->{"format"} =~ /pdf/) {
1858     $form->{pdf} = 1;
1859     if ($form->{"format"} =~ /opendocument/) {
1860       $form->{IN} =~ s/html$/odt/;
1861     } else {
1862       $form->{IN} =~ s/html$/tex/;
1863     }
1864   } elsif ($form->{"format"} =~ /opendocument/) {
1865     $form->{"opendocument"} = 1;
1866     $form->{"IN"} =~ s/html$/odt/;
1867   }
1868
1869   if ($form->{media} eq 'printer') {
1870     $form->{OUT} = "| $form->{printer_command} &>/dev/null";
1871     $form->{printed} .= " $form->{formname}";
1872     $form->{printed} =~ s/^ //;
1873   }
1874   $printed = $form->{printed};
1875
1876   if ($form->{media} eq 'email') {
1877     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1878       unless $form->{subject};
1879
1880     $form->{OUT} = "$sendmail";
1881
1882     $form->{emailed} .= " $form->{formname}";
1883     $form->{emailed} =~ s/^ //;
1884   }
1885   $emailed = $form->{emailed};
1886
1887   if ($form->{media} eq 'queue') {
1888     %queued = split / /, $form->{queued};
1889
1890     if ($filename = $queued{ $form->{formname} }) {
1891       $form->{queued} =~ s/$form->{formname} $filename//;
1892       unlink "$spool/$filename";
1893       $filename =~ s/\..*$//g;
1894     } else {
1895       $filename = time;
1896       $filename .= $$;
1897     }
1898
1899     $filename .= ($form->{postscript}) ? '.ps' : '.pdf';
1900     $form->{OUT} = ">$spool/$filename";
1901
1902     # add type
1903     $form->{queued} .= " $form->{formname} $filename";
1904
1905     $form->{queued} =~ s/^ //;
1906   }
1907   $queued = $form->{queued};
1908
1909 # saving the history
1910   if(!exists $form->{addition}) {
1911     if($form->{media} =~ /printer/) {
1912         $form->{addition} = "PRINTED";
1913     }
1914     elsif($form->{media} =~ /email/) {
1915         $form->{addition} = "MAILED";
1916     }
1917     elsif($form->{media} =~ /queue/) {
1918         $form->{addition} = "QUEUED";
1919     }
1920     elsif($form->{media} =~ /screen/) {
1921         $form->{addition} = "SCREENED";
1922     }
1923     $form->save_history($form->dbconnect(\%myconfig));
1924   }
1925   # /saving the history
1926
1927   $form->parse_template(\%myconfig, $userspath);
1928
1929   $form->{callback} = "";
1930
1931   if ($form->{media} eq 'email') {
1932     $form->{message} = $locale->text('sent') unless $form->{message};
1933   }
1934   $message = $form->{message};
1935
1936   # if we got back here restore the previous form
1937   if ($form->{media} =~ /(printer|email|queue)/) {
1938
1939     $form->update_status(\%myconfig)
1940       if ($form->{media} eq 'queue' && $form->{id});
1941
1942     return $lxdebug->leave_sub() if ($old_form eq "return");
1943
1944     if ($old_form) {
1945
1946       $old_form->{"${inv}number"} = $form->{"${inv}number"};
1947
1948       # restore and display form
1949       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1950
1951       $form->{queued}  = $queued;
1952       $form->{printed} = $printed;
1953       $form->{emailed} = $emailed;
1954       $form->{message} = $message;
1955
1956       $form->{rowcount}--;
1957       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1958         qw(exchangerate creditlimit creditremaining);
1959
1960       for $i (1 .. $form->{paidaccounts}) {
1961         map {
1962           $form->{"${_}_$i"} =
1963             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1964         } qw(paid exchangerate);
1965       }
1966
1967       &{"$display_form"};
1968       exit;
1969     }
1970
1971     $msg =
1972       ($form->{media} eq 'printer')
1973       ? $locale->text('sent to printer')
1974       : $locale->text('emailed to') . " $form->{email}";
1975     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1976   }
1977   if ($form->{printing}) {
1978    &{"$display_form"};
1979    exit; 
1980   }
1981
1982   $lxdebug->leave_sub();
1983 }
1984
1985 sub customer_details {
1986   $lxdebug->enter_sub();
1987   IS->customer_details(\%myconfig, \%$form, @_);
1988   $lxdebug->leave_sub();
1989 }
1990
1991 sub vendor_details {
1992   $lxdebug->enter_sub();
1993
1994   IR->vendor_details(\%myconfig, \%$form, @_);
1995
1996   $lxdebug->leave_sub();
1997 }
1998
1999 sub post_as_new {
2000   $lxdebug->enter_sub();
2001
2002   $form->{postasnew} = 1;
2003   map { delete $form->{$_} } qw(printed emailed queued);
2004
2005   &post;
2006
2007   $lxdebug->leave_sub();
2008 }
2009
2010 sub ship_to {
2011   $lxdebug->enter_sub();
2012   if ($form->{second_run}) {
2013     $form->{print_and_post} = 0;
2014   }
2015
2016   $title = $form->{title};
2017   $form->{title} = $locale->text('Ship to');
2018
2019   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
2020     qw(exchangerate creditlimit creditremaining);
2021
2022   my @shipto_vars =
2023     qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
2024        shiptocontact shiptophone shiptofax shiptoemail
2025        shiptodepartment_1 shiptodepartment_2);
2026
2027   my @addr_vars =
2028     (qw(name department_1 department_2 street zipcode city country
2029         contact email phone fax));
2030
2031   # get details for name
2032   &{"$form->{vc}_details"}(@addr_vars);
2033
2034   $number =
2035     ($form->{vc} eq 'customer')
2036     ? $locale->text('Customer Number')
2037     : $locale->text('Vendor Number');
2038
2039   # get pricegroups for parts
2040   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
2041
2042   # build up html code for prices_$i
2043   set_pricegroup($form->{rowcount});
2044
2045   $nextsub = ($form->{display_form}) ? $form->{display_form} : "display_form";
2046
2047   $form->{rowcount}--;
2048
2049   $form->header;
2050
2051   print qq|
2052 <body>
2053
2054 <form method="post" action="$form->{script}">
2055
2056 <table width="100%">
2057   <tr>
2058     <td>
2059       <table>
2060         <tr class="listheading">
2061           <th class="listheading" colspan="2" width="50%">|
2062     . $locale->text('Billing Address') . qq|</th>
2063           <th class="listheading" width="50%">|
2064     . $locale->text('Shipping Address') . qq|</th>
2065         </tr>
2066         <tr height="5"></tr>
2067         <tr>
2068           <th align="right" nowrap>$number</th>
2069           <td>$form->{"$form->{vc}number"}</td>
2070         </tr>
2071         <tr>
2072           <th align="right" nowrap>| . $locale->text('Company Name') . qq|</th>
2073           <td>$form->{name}</td>
2074           <td><input name="shiptoname" size="35" value="$form->{shiptoname}"></td>
2075         </tr>
2076         <tr>
2077           <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
2078           <td>$form->{department_1}</td>
2079           <td><input name="shiptodepartment_1" size="35" value="$form->{shiptodepartment_1}"></td>
2080         </tr>
2081         <tr>
2082           <th align="right" nowrap>&nbsp;</th>
2083           <td>$form->{department_2}</td>
2084           <td><input name="shiptodepartment_2" size="35" value="$form->{shiptodepartment_2}"></td>
2085         </tr>
2086         <tr>
2087           <th align="right" nowrap>| . $locale->text('Street') . qq|</th>
2088           <td>$form->{street}</td>
2089           <td><input name="shiptostreet" size="35" value="$form->{shiptostreet}"></td>
2090         </tr>
2091         <tr>
2092           <th align="right" nowrap>| . $locale->text('Zipcode') . qq|</th>
2093           <td>$form->{zipcode}</td>
2094           <td><input name="shiptozipcode" size="35" value="$form->{shiptozipcode}"></td>
2095         </tr>
2096         <tr>
2097           <th align="right" nowrap>| . $locale->text('City') . qq|</th>
2098           <td>$form->{city}</td>
2099           <td><input name="shiptocity" size="35" value="$form->{shiptocity}"></td>
2100         </tr>
2101         <tr>
2102           <th align="right" nowrap>| . $locale->text('Country') . qq|</th>
2103           <td>$form->{country}</td>
2104           <td><input name="shiptocountry" size="35" value="$form->{shiptocountry}"></td>
2105         </tr>
2106         <tr>
2107           <th align="right" nowrap>| . $locale->text('Contact') . qq|</th>
2108           <td>$form->{contact}</td>
2109           <td><input name="shiptocontact" size="35" value="$form->{shiptocontact}"></td>
2110         </tr>
2111         <tr>
2112           <th align="right" nowrap>| . $locale->text('Phone') . qq|</th>
2113           <td>$form->{phone}</td>
2114           <td><input name="shiptophone" size="20" value="$form->{shiptophone}"></td>
2115         </tr>
2116         <tr>
2117           <th align="right" nowrap>| . $locale->text('Fax') . qq|</th>
2118           <td>$form->{fax}</td>
2119           <td><input name="shiptofax" size="20" value="$form->{shiptofax}"></td>
2120         </tr>
2121         <tr>
2122           <th align="right" nowrap>| . $locale->text('E-mail') . qq|</th>
2123           <td>$form->{email}</td>
2124           <td><input name="shiptoemail" size="35" value="$form->{shiptoemail}"></td>
2125         </tr>
2126       </table>
2127     </td>
2128   </tr>
2129 </table>
2130 | . $cgi->hidden("-name" => "nextsub", "-value" => $nextsub);
2131 ;
2132
2133
2134
2135   # delete shipto
2136   map({ delete $form->{$_} } (@shipto_vars, qw(header)));
2137   $form->{title} = $title;
2138
2139   foreach $key (keys %$form) {
2140     $form->{$key} =~ s/\"/&quot;/g;
2141     print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
2142   }
2143
2144   print qq|
2145
2146 <hr size="3" noshade>
2147
2148 <br>
2149 <input class="submit" type="submit" name="action" value="|
2150     . $locale->text('Continue') . qq|">
2151 </form>
2152
2153 </body>
2154 </html>
2155 |;
2156
2157   $lxdebug->leave_sub();
2158 }
2159
2160 sub new_license {
2161   $lxdebug->enter_sub();
2162
2163   my $row = shift;
2164
2165   # change callback
2166   $form->{old_callback} = $form->escape($form->{callback}, 1);
2167   $form->{callback} = $form->escape("$form->{script}?action=display_form", 1);
2168   $form->{old_callback} = $form->escape($form->{old_callback}, 1);
2169
2170   # delete action
2171   delete $form->{action};
2172   $customer = $form->{customer};
2173   map { $form->{"old_$_"} = $form->{"${_}_$row"} } qw(partnumber description);
2174
2175   # save all other form variables in a previousform variable
2176   $form->{row} = $row;
2177   foreach $key (keys %$form) {
2178
2179     # escape ampersands
2180     $form->{$key} =~ s/&/%26/g;
2181     $previousform .= qq|$key=$form->{$key}&|;
2182   }
2183   chop $previousform;
2184   $previousform = $form->escape($previousform, 1);
2185
2186   $form->{script} = "licenses.pl";
2187
2188   map { $form->{$_} = $form->{"old_$_"} } qw(partnumber description);
2189   map { $form->{$_} = $form->escape($form->{$_}, 1) }
2190     qw(partnumber description);
2191   $form->{callback} =
2192     qq|$form->{script}?login=$form->{login}&path=$form->{path}&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|;
2193   $form->redirect;
2194
2195   $lxdebug->leave_sub();
2196 }
2197
2198 sub relink_accounts {
2199   $lxdebug->enter_sub();
2200
2201   $form->{"taxaccounts"} =~ s/\s*$//;
2202   $form->{"taxaccounts"} =~ s/^\s*//;
2203   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
2204     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
2205   }
2206   $form->{"taxaccounts"} = "";
2207
2208   for (my $i = 1; $i <= $form->{"rowcount"}; $i++) {
2209     if ($form->{"id_$i"}) {
2210       IC->retrieve_accounts(\%myconfig, $form, $form->{"id_$i"}, $i, 1);
2211     }
2212   }
2213
2214   $lxdebug->leave_sub();
2215 }
2216
2217 sub set_duedate {
2218   $lxdebug->enter_sub();
2219
2220   $form->get_duedate(\%myconfig);
2221
2222   my $q = new CGI;
2223   $result = "$form->{duedate}";
2224   print $q->header();
2225   print $result;
2226   $lxdebug->leave_sub();
2227
2228 }
2229