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