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