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