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