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