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