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