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