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