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