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