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