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