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