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