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