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