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