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