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