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