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