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