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