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