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