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