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