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