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