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