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