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