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