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