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