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