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