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