Drucken: Variablen in Positionen interpolieren
[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     splice @row2_sort, 0, 1;
176     splice @header_sort, 4, 0, "serialnr";
177   }
178
179   my %column_def = (
180     runningnumber => { width => 5,     value => $locale->text('No.'),                  display => 1, },
181     partnumber    => { width => 8,     value => $locale->text('Number'),               display => 1, },
182     type_and_classific
183                   => { width => 2,     value => $locale->text('Type'),                 display => 1, },
184     description   => { width => 30,    value => $locale->text('Part Description'),     display => 1, },
185     ship          => { width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
186     ship_missing  => { width => 5,     value => $locale->text('Not delivered'),        display => $show_ship_missing, },
187     qty           => { width => 5,     value => $locale->text('Qty'),                  display => 1, },
188     price_factor  => { width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
189     unit          => { width => 5,     value => $locale->text('Unit'),                 display => 1, },
190     weight        => { width => 5,     value => $locale->text('Weight'),               display => $defaults->{show_weight}, },
191     serialnr      => { width => 10,    value => $locale->text('Serial No.'),           display => !$is_quotation },
192     projectnr     => { width => 10,    value => $locale->text('Project'),              display => 1, },
193     price_source  => { width => 5,     value => $locale->text('Price Source'),         display => !$is_delivery_order, },
194     sellprice     => { width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
195     discount      => { width => 5,     value => $locale->text('Discount'),             display => !$is_delivery_order, },
196     linetotal     => { width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
197     bin           => { width => 10,    value => $locale->text('Bin'),                  display => 0, },
198     stock_in_out  => { width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
199     reqdate       => {                 value => $locale->text('Reqdate'),              display => $is_s_p_order || $is_delivery_order || $is_invoice, },
200     subtotal      => {                 value => $locale->text('Subtotal'),             display => 1, },
201     marge         => {                 value => $locale->text('Ertrag'),               display => $show_marge, },
202     listprice     => {                 value => $locale->text('LP'),                   display => $show_marge, },
203     lastcost      => {                 value => $locale->text('EK'),                   display => $show_marge, },
204     onhand        => {                 value => $locale->text('On Hand'),              display => 1, },
205   );
206   my @HEADER = map { $column_def{$_} } @header_sort;
207
208   # cache units
209   my $all_units       = AM->retrieve_units(\%myconfig, $form);
210
211   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
212
213
214   $form->{invsubtotal} = 0;
215   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
216
217   # about details
218   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
219   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
220   # /about details
221
222   # translations, unused commented out
223   my $deliverydate  = $locale->text('Required by');
224
225   # special alignings
226   my %align  = map { $_ => 'right' } qw(qty ship right discount linetotal stock_in_out weight ship_missing);
227   my %nowrap = map { $_ => 1 }       qw(description unit  price_source);
228
229   $form->{marge_total}           = 0;
230   $form->{sellprice_total}       = 0;
231   $form->{lastcost_total}        = 0;
232   $form->{totalweight}           = 0;
233   my %projectnumber_labels = ();
234   my @projectnumber_values = ("");
235
236   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
237     push(@projectnumber_values, $item->{"id"});
238     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
239   }
240
241   _update_part_information();
242   _update_ship() if ($is_s_p_order);
243   _update_custom_variables();
244
245   my $totalweight = 0;
246
247   my $record = _make_record();
248   # rows
249
250   my @ROWS;
251   for my $i (1 .. $numrows) {
252     my %column_data = ();
253
254     my $record_item = $record->id && $record->items ? $record->items->[$i-1] : _make_record_item($i);
255
256     # undo formatting
257     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
258       qw(qty discount sellprice lastcost price_new price_old)
259         unless ($form->{simple_save});
260
261     if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
262       $form->{"sellprice_$i"} = $form->{"price_new_$i"};
263     }
264
265 # unit begin
266     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
267     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
268
269     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
270         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
271       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
272     }
273
274     $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
275     $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
276     $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
277
278     my $this_unit = $form->{"unit_$i"};
279     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
280
281     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
282       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
283       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
284
285       $column_data{price_factor} =
286         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
287                              '-default' => $form->{"price_factor_id_$i"},
288                              '-values'  => \@values,
289                              '-labels'  => \%labels,
290                              '-style'   => 'width:90px'));
291     } else {
292       $column_data{price_factor} = '&nbsp;';
293     }
294     $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
295
296     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
297 # / unit ending
298
299 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
300 #is shown for lastcost and sellprice.
301     my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
302     $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
303
304     my $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
305     my $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
306     my $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
307     my $rows            = $form->numtextrows($form->{"description_$i"}, 30, 6);
308
309     # quick delete single row
310     $column_data{runningnumber}  = q|<a onclick= "$('#partnumber_| . $i . q|').val(''); $('#update_button').click();">| .
311                                    q|<img height="10px" width="10px" src="image/cross.png" alt="| . $locale->text('Remove') . q|"></a> |;
312     $column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
313
314
315     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -id => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
316     $column_data{type_and_classific} = SL::Presenter::Part::type_abbreviation($form->{"part_type_$i"}).
317                                        SL::Presenter::Part::classification_abbreviation($form->{"classification_id_$i"}) if $form->{"id_$i"};
318     $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
319                                 ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
320                                 : $cgi->textfield(-name => "description_$i", -id => "description_$i",   -value => $form->{"description_$i"}, -size => 30))
321                                 . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
322
323     my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
324
325     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -class => "numeric", -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
326     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_dialog('qty_$i', '', 'formel_$i', '')", -value => $locale->text('*/'))
327                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"})
328       if $form->{"formel_$i"};
329
330     $column_data{ship} = '';
331     if ($form->{"id_$i"}) {
332       my $ship_qty        = $form->{"ship_$i"} * 1;
333       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
334       $ship_qty          /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
335
336       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"}
337       . $cgi->hidden(-name => "ship_$i", -value => $form->{"ship_$i"}, $qty_dec);
338
339       my $ship_missing_qty    = $form->{"qty_$i"} - $ship_qty;
340       my $ship_missing_amount = $form->round_amount($ship_missing_qty * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
341
342       $column_data{ship_missing} = $form->format_amount(\%myconfig, $ship_missing_qty) . ' ' . $form->{"unit_$i"} . '; ' . $form->format_amount(\%myconfig, $ship_missing_amount, $decimalplaces);
343     }
344
345     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
346     $column_data{bin}         = $form->{"bin_$i"};
347
348     $column_data{weight}      = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
349
350     my $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
351     my $discount_value  = $form->format_amount(\%myconfig, $form->{"discount_$i"});
352
353     my $price;
354     if ($form->{"id_${i}"} && !$is_delivery_order) {
355       my $price_source  = SL::PriceSource->new(record_item => $record_item, record => $record);
356          $price         = $price_source->price_from_source($::form->{"active_price_source_$i"});
357       my $discount      = $price_source->discount_from_source($::form->{"active_discount_source_$i"});
358       my $best_price    = $price_source->best_price;
359       my $best_discount = $price_source->best_discount;
360       $column_data{price_source} .= $cgi->button(-value => $price->source_description, -onClick => "kivi.io.price_chooser($i)");
361       if ($price->source) {
362         $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->invalid, title => $price->invalid }) if $price->invalid;
363         $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->missing, title => $price->missing }) if $price->missing;
364         if (!$price->missing && !$price->invalid) {
365           $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;
366           $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;
367           $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;
368         }
369       }
370       if ($discount->source) {
371         $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->invalid, title => $discount->invalid }) if $discount->invalid;
372         $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->missing, title => $discount->missing }) if $discount->missing;
373         if (!$discount->missing && !$discount->invalid) {
374           $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;
375           $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;
376           $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;
377         }
378       }
379     }
380
381     my $right_to_edit_prices  = (!$is_purchase && $main::auth->assert('sales_edit_prices', 1)) || ($is_purchase && $main::auth->assert('purchase_edit_prices', 1));
382     my $edit_prices           = $right_to_edit_prices && (!$::form->{"active_price_source_$i"} || !$price || $price->editable);
383     my $edit_discounts        = $right_to_edit_prices && !$::form->{"active_discount_source_$i"};
384     $column_data{sellprice}   = (!$edit_prices)
385                                 ? $cgi->hidden(   -name => "sellprice_$i", -id => "sellprice_$i", -value => $sellprice_value) . $sellprice_value
386                                 : $cgi->textfield(-name => "sellprice_$i", -id => "sellprice_$i", -size => 10, -class => "numeric", -value => $sellprice_value);
387     $column_data{discount}    = (!$edit_discounts)
388                                   ? $cgi->hidden(   -name => "discount_$i", -id => "discount_$i", -value => $discount_value) . $discount_value . ' %'
389                                   : $cgi->textfield(-name => "discount_$i", -id => "discount_$i", -size => 3, -"data-validate" => "number", -class => "numeric", -value => $discount_value);
390
391     if ($is_delivery_order) {
392       $column_data{stock_in_out} =  calculate_stock_in_out($i);
393     }
394
395     $column_data{serialnr}  = qq|<input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">|;
396     $column_data{projectnr} = NTI($cgi->popup_menu(
397       '-name' => "project_id_$i",
398       '-values' => \@projectnumber_values,
399       '-labels' => \%projectnumber_labels,
400       '-default' => $form->{"project_id_$i"}
401     ));
402     $column_data{reqdate}   = qq|<input name="reqdate_$i" size="11" data-validate="date" value="$form->{"reqdate_$i"}">|;
403     $column_data{subtotal}  = sprintf qq|<input type="checkbox" name="subtotal_$i" value="1" %s>|, $form->{"subtotal_$i"} ? 'checked' : '';
404
405 # begin marge calculations
406     $form->{"lastcost_$i"}     *= 1;
407     $form->{"marge_percent_$i"} = 0;
408
409     my $marge_color;
410     my $real_sellprice;
411     if ( $form->{taxincluded} and $form->{"qty_$i"} * 1  and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
412       # if we use taxincluded we need to calculate the marge from the net_value
413       # all the marge calculations are based on linetotal which we need to
414       # convert to net first
415
416       # there is no direct form value for the tax_rate of the item, but
417       # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
418       # gives the tax percentage (e.g. 0.19)
419       $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
420     } else {
421       $real_sellprice            = $linetotal;
422     };
423     my $real_lastcost            = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
424     my $marge_percent_warn       = $myconfig{marge_percent_warn} * 1 || 15;
425     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
426
427     if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
428       $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
429       $marge_color                = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
430     }
431
432     $form->{"marge_absolut_$i"}  = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
433     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
434     $form->{"lastcost_total"}   += $real_lastcost;
435     $form->{"sellprice_total"}  += $real_sellprice;
436
437     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
438
439     $column_data{marge} = sprintf qq|<font %s>%s &nbsp;%s%%</font>|,
440       $marge_color, $form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"};
441     $column_data{listprice} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2);
442     $column_data{lastcost}  = sprintf qq|<input size="5" name="lastcost_$i" value="%s">|, $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
443 # / marge calculations ending
444
445 # Calculate total weight
446     $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
447
448 # calculate onhand
449     if ($form->{"id_$i"}) {
450       my $part         = IC->get_basic_part_info(id => $form->{"id_$i"});
451       my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
452       $column_data{onhand} = sprintf "<font %s>%s %s</font>",
453                       $onhand_color,
454                       $form->format_amount(\%myconfig, $part->{onhand}, 2),
455                       $part->{unit};
456     }
457 # / calculate onhand
458
459     my @ROW1 = map { { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} } } grep { $column_def{$_}{display} } @header_sort;
460     my @ROW2 = map { { value => sprintf "<b>%s</b> %s", $column_def{$_}{value}, $column_data{$_} } } grep { $column_def{$_}{display} } @row2_sort;
461
462     my @hidden_vars;
463     # add hidden ids for persistent (item|invoice)_ids and previous (converted_from*) ids
464     if ($is_quotation) {
465       push @hidden_vars, qw(orderitems_id converted_from_orderitems_id);
466     }
467     if ($is_s_p_order) {
468       push @hidden_vars, qw(orderitems_id converted_from_orderitems_id converted_from_invoice_id);
469     }
470     if ($is_invoice) {
471       push @hidden_vars, qw(invoice_id converted_from_orderitems_id converted_from_delivery_order_items_id converted_from_invoice_id);
472     }
473     if ($::form->{type} =~ /credit_note/) {
474       push @hidden_vars, qw(invoice_id converted_from_invoice_id);
475     }
476    if ($is_delivery_order) {
477       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
478       push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost);
479       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
480       push @hidden_vars, qw(delivery_order_items_id converted_from_orderitems_id converted_from_delivery_order_items_id has_sernumber);
481     }
482
483     my @HIDDENS = map { value => $_}, (
484           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
485           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
486           map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
487             (qw(bo price_old id inventory_accno bin partsgroup partnotes active_price_source active_discount_source
488                 income_accno expense_accno listprice part_type taxaccounts ordnumber donumber transdate cusordnumber
489                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
490     );
491
492     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
493
494     $form->{invsubtotal} += $linetotal;
495
496     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
497     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
498
499     my $colspan = scalar @ROW1;
500     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, obj => $record_item };
501   }
502
503   $form->{totalweight} = $totalweight;
504
505   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
506                                                        HEADER => \@HEADER,
507                                                      });
508
509   if (abs($form->{sellprice_total} * 1) >= 0.01) {
510     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
511   }
512
513   $main::lxdebug->leave_sub();
514 }
515
516 sub setup_io_select_item_action_bar {
517   my %params = @_;
518
519   for my $bar ($::request->layout->get('actionbar')) {
520     $bar->add(
521       action => [
522         t8('Continue'),
523         submit    => [ '#form' ],
524         accesskey => 'enter',
525       ],
526     );
527   }
528 }
529
530 sub select_item {
531   $main::lxdebug->enter_sub();
532
533   my %params = @_;
534   my $mode            = $params{mode}            || croak "Missing parameter 'mode'";
535   my $pre_entered_qty = $params{pre_entered_qty} || 1;
536   _check_io_auth();
537
538   setup_io_select_item_action_bar();
539
540   my $previous_form = $::auth->save_form_in_session(form => $::form);
541   $::form->{title}  = $::myconfig{item_multiselect} ?
542       $::locale->text('Set count for one or more of the items to select them'):
543       $::locale->text('Select from one of the items below');
544   $::form->header;
545
546   my @item_list = map {
547     # maybe there is a better backend function or way to calc
548     $_->{display_sellprice} = ($_->{price_factor}) ? $_->{sellprice} / $_->{price_factor} : $_->{sellprice};
549     $_;
550   } @{ $::form->{item_list} };
551
552   # delete action variable
553   delete @{$::form}{qw(action item_list)};
554
555   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM   => $previous_form,
556                                                          MODE            => $mode,
557                                                          ITEM_LIST       => \@item_list,
558                                                          IS_ASSEMBLY     => $mode eq 'IC',
559                                                          IS_PURCHASE     => $mode eq 'IS',
560                                                          PRE_ENTERED_QTY => $pre_entered_qty, });
561
562   $main::lxdebug->leave_sub();
563 }
564
565 sub item_selected {
566
567   # this function is used for adding parts to records (mode = IR/IS)
568   # and to assemblies (mode = IC)
569
570   $main::lxdebug->enter_sub();
571
572   my $form     = $main::form;
573   my %myconfig = %main::myconfig;
574
575   _check_io_auth();
576
577   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
578
579   my $mode     = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
580   my $row_key  = $mode eq 'IC' ? 'assembly_rows' : 'rowcount';
581   my $curr_row = $form->{ $row_key };
582
583   my $row = $curr_row;
584
585   if ($myconfig{item_multiselect}) {
586     my %multi_items;
587     for (keys %$form) {
588       next unless $form->{$_};
589       next unless /^select_qty_(\d+)/;
590       $multi_items{"id_${row}"}  = $1;
591       $multi_items{"qty_${row}"} = $form->{$_};
592       $row++;
593     }
594     $form->{$_} = $multi_items{$_} for keys %multi_items;
595   } else {
596     $form->{"id_${row}"} = delete($form->{select_item_id}) || croak 'Missing item selection ID';
597     $row++;
598   }
599
600   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
601     qw(sellprice weight);
602
603   if ( $mode eq 'IC' ) {
604     # assembly mode:
605     # the qty variables of the existing assembly items are all still formatted, so we parse them here
606     # including the qty of the just added part
607     $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for (1 .. $row - 1);
608   } else {
609     if ($myconfig{item_multiselect}) {
610       # other modes and multiselection:
611       # parse all newly entered qtys
612       $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for ($curr_row .. $row - 1);
613     }
614   }
615
616   for my $i ($curr_row .. $row - 1) {
617     $form->{ $row_key } = $i;
618
619     my $id = $form->{"id_${i}"};
620
621     delete $form->{item_list};
622
623     if ($mode eq 'IS') {
624       IS->retrieve_item(\%myconfig, \%$form);
625     } elsif ($mode eq 'IR') {
626       IR->retrieve_item(\%myconfig, \%$form);
627     } elsif ($mode eq 'IC') {
628       IC->assembly_item(\%myconfig, \%$form);
629     } else {
630       croak "Invalid item selection mode '${mode}'";
631     }
632
633     my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
634
635     # if there was a price entered, override it
636     my $sellprice;
637     unless ( $mode eq 'IC' ) {
638       $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
639     };
640
641     my @new_fields =
642         qw(id partnumber description sellprice listprice inventory_accno
643            income_accno expense_accno bin unit weight part_type taxaccounts
644            partsgroup formel longdescription not_discountable partnotes lastcost
645            price_factor_id price_factor);
646
647     my $ic_cvar_configs = CVar->get_configs(module => 'IC');
648     push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
649
650     map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
651
652     if (my $record = _make_record()) {
653       my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
654       my $best_price   = $price_source->best_price;
655
656       if ($best_price) {
657         $::form->{"sellprice_$i"}           = $best_price->price;
658         $::form->{"active_price_source_$i"} = $best_price->source;
659       }
660
661       my $best_discount = $price_source->best_discount;
662
663       if ($best_discount) {
664         $::form->{"discount_$i"}               = $best_discount->discount;
665         $::form->{"active_discount_source_$i"} = $best_discount->source;
666       }
667     }
668
669     $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
670
671     if ($form->{"part_payment_id_$i"} ne "") {
672       $form->{payment_id} = $form->{"part_payment_id_$i"};
673     }
674
675     my ($dec)         = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
676     $dec              = length $dec;
677     my $decimalplaces = ($dec > 2) ? $dec : 2;
678
679     if ($sellprice) {
680       $form->{"sellprice_$i"} = $sellprice;
681     } else {
682
683       # if there is an exchange rate adjust sellprice
684       if (($form->{exchangerate} * 1) != 0) {
685         $form->{"sellprice_$i"} /= $form->{exchangerate};
686         $form->{"sellprice_$i"} =
687             $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
688       }
689     }
690
691     # at this stage qty of newly added part needs to be have been parsed
692     $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
693
694     if ($form->{"not_discountable_$i"}) {
695       $form->{"discount_$i"} = 0;
696     }
697
698     my $amount =
699         $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"}) * $form->{"qty_$i"};
700     map { $form->{"${_}_base"} += $amount }                         (split / /, $form->{"taxaccounts_$i"});
701     map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
702
703     $form->{creditremaining} -= $amount;
704     $form->{"runningnumber_$i"} = $i;
705
706     # format amounts
707     map {
708       $form->{"${_}_$i"} =
709           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
710     } qw(sellprice lastcost qty) if $form->{part_type} ne 'assembly';
711     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0) if $form->{part_type} ne 'assembly';
712
713     delete $form->{nextsub};
714
715   }
716
717   &display_form;
718
719   $main::lxdebug->leave_sub();
720 }
721
722 sub new_item {
723   _check_io_auth();
724
725   my $price = $::form->{vc} eq 'customer' ? 'sellprice_as_number' : 'lastcost_as_number';
726   my $previousform = $::auth->save_form_in_session;
727   my $callback     = build_std_url("action=return_from_new_item", "previousform=$previousform");
728   my $i            = $::form->{rowcount};
729
730   my $parts_classification_type = $::form->{vc} eq 'customer' ? 'sales' : 'purchases';
731
732   my @HIDDENS;
733   push @HIDDENS,      { 'name' => 'callback',     'value' => $callback };
734   push @HIDDENS, map +{ 'name' => $_,             'value' => $::form->{$_} },        qw(rowcount vc);
735   push @HIDDENS, map +{ 'name' => "part.$_",      'value' => $::form->{"${_}_$i"} }, qw(partnumber description unit price_factor_id);
736   push @HIDDENS,      { 'name' => "part.$price",  'value' => $::form->{"sellprice_$i"} };
737   push @HIDDENS,      { 'name' => "part.notes",   'value' => $::form->{"longdescription_$i"} };
738
739   push @HIDDENS,      { 'name' => "parts_classification_type", 'value' => $parts_classification_type };
740
741   $::form->header;
742   print $::form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
743 }
744
745 sub return_from_new_item {
746   _check_io_auth();
747
748   my $part = SL::DB::Manager::Part->find_by(id => delete $::form->{new_parts_id}) or die 'can not find part that was just saved!';
749
750   $::auth->restore_form_from_session(delete $::form->{previousform}, form => $::form);
751
752   $::form->{"id_$::form->{rowcount}"} = $part->id;
753
754   my $url = build_std_url("script=$::form->{script}", "RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session);
755   print $::request->{cgi}->redirect($url);
756 }
757
758 sub check_form {
759   $main::lxdebug->enter_sub();
760
761   my $form     = $main::form;
762   my %myconfig = %main::myconfig;
763
764   _check_io_auth();
765
766   my @a     = ();
767   my $count = 0;
768
769   # remove any makes or model rows
770   if ($form->{part_type} eq 'assembly') {
771
772     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
773     #$form->{sellprice} = 0;
774     $form->{weight}    = 0;
775     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
776       qw(sellprice rop stock);
777
778     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
779
780     for my $i (1 .. ($form->{assembly_rows} - 1)) {
781       if ($form->{"qty_$i"}) {
782         push @a, {};
783         my $j = $#a;
784
785         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
786
787         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
788
789         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
790
791         # fuer assemblies auskommentiert. siehe oben
792         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
793         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
794         $count++;
795       }
796     }
797     # kann das hier auch weg? s.o. jb
798     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
799
800     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
801     $form->{assembly_rows} = $count;
802
803   } elsif ($form->{part_type} !~ m{^(?:part|service)$}) {
804     remove_emptied_rows(1);
805
806     $form->{creditremaining} -= &invoicetotal;
807   }
808
809   &display_form;
810
811   $main::lxdebug->leave_sub();
812 }
813
814 sub remove_emptied_rows {
815   my $dont_add_empty = shift;
816   my $form           = $::form;
817
818   return unless $form->{rowcount};
819
820   my @flds = qw(id partnumber description qty ship sellprice unit
821                 discount inventory_accno income_accno expense_accno listprice
822                 taxaccounts bin assembly weight projectnumber project_id
823                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
824                 not_discountable shop ve gv buchungsgruppen_id language_values
825                 price_old price_new unit_old ordnumber donumber
826                 transdate longdescription basefactor marge_total marge_percent
827                 marge_price_factor lastcost price_factor_id partnotes
828                 stock_out stock_in has_sernumber reqdate orderitems_id
829                 active_price_source active_discount_source delivery_order_items_id
830                 invoice_id converted_from_orderitems_id
831                 converted_from_delivery_order_items_id converted_from_invoice_id);
832
833   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
834   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
835
836   my @new_rows;
837   for my $i (1 .. $form->{rowcount} - 1) {
838     next unless $form->{"partnumber_$i"};
839
840     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
841   }
842
843   my $new_rowcount = scalar @new_rows;
844   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
845   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
846 }
847
848 sub invoicetotal {
849   $main::lxdebug->enter_sub();
850
851   my $form     = $main::form;
852   my %myconfig = %main::myconfig;
853
854   _check_io_auth();
855
856   $form->{oldinvtotal} = 0;
857
858   # add all parts and deduct paid
859   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
860
861   my ($amount, $sellprice, $discount, $qty);
862
863   for my $i (1 .. $form->{rowcount}) {
864     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
865     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
866     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
867
868     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
869
870     $amount = $sellprice * (1 - $discount / 100) * $qty;
871     map { $form->{"${_}_base"} += $amount }
872       (split (/ /, $form->{"taxaccounts_$i"}));
873     $form->{oldinvtotal} += $amount;
874   }
875
876   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
877     split(/ /, $form->{taxaccounts})
878     if !$form->{taxincluded};
879
880   $form->{oldtotalpaid} = 0;
881   for my $i (1 .. $form->{paidaccounts}) {
882     $form->{oldtotalpaid} += $form->{"paid_$i"};
883   }
884
885   $main::lxdebug->leave_sub();
886
887   # return total
888   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
889 }
890
891 sub validate_items {
892   $main::lxdebug->enter_sub();
893
894   my $form     = $main::form;
895   my $locale   = $main::locale;
896
897   _check_io_auth();
898
899   # check if items are valid
900   if ($form->{rowcount} == 1) {
901     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
902     &update;
903     $::dispatcher->end_request;
904   }
905
906   for my $i (1 .. $form->{rowcount} - 1) {
907     $form->isblank("partnumber_$i",
908                    $locale->text('Number missing in Row') . " $i");
909   }
910
911   $main::lxdebug->leave_sub();
912 }
913
914 sub order {
915   $main::lxdebug->enter_sub();
916
917   _order();
918
919   if ($::instance_conf->get_feature_experimental_order) {
920
921     # At this point, the record is saved and the exchangerate contains
922     # an unformatted value. _make_record uses RDBO attributes (i.e. _as_number)
923     # to assign values and thus expects an formatted value.
924     $::form->{exchangerate} = $::form->format_amount(\%::myconfig, $::form->{exchangerate});
925
926     my $order = _make_record();
927
928     $order->currency(SL::DB::Currency->new(name => $::form->{currency})->load) if $::form->{currency};
929     $order->globalproject_id(undef)                                            if !$order->globalproject_id;
930     $order->payment_id(undef)                                                  if !$order->payment_id;
931
932     my $row = 1;
933     foreach my $item (@{$order->items_sorted}) {
934       $item->custom_variables([]);
935
936       $item->price_factor_id(undef) if !$item->price_factor_id;
937       $item->project_id(undef)      if !$item->project_id;
938
939       # autovivify all cvars that are not in the form (cvars_by_config can do it).
940       # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
941        foreach my $var (@{ $item->cvars_by_config }) {
942         my $key = 'ic_cvar_' . $var->config->name . '_' . $row;
943         $var->unparsed_value($::form->{$key});
944         $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
945       }
946       $item->parse_custom_variable_values;
947
948       $row++;
949     }
950
951     require SL::Controller::Order;
952     my $c = SL::Controller::Order->new(order => $order);
953     $c->setup_custom_shipto_from_form($order, $::form);
954     $c->action_edit();
955
956     $main::lxdebug->leave_sub();
957     $::dispatcher->end_request;
958   }
959
960   &display_form;
961
962   $main::lxdebug->leave_sub();
963 }
964
965 sub _order {
966   my $form     = $main::form;
967   my %myconfig = %main::myconfig;
968   my $locale   = $main::locale;
969
970   _check_io_auth();
971
972   if ($form->{second_run}) {
973     $form->{print_and_post} = 0;
974   }
975   $form->{ordnumber} = $form->{invnumber};
976
977   $form->{old_employee_id} = $form->{employee_id};
978   $form->{old_salesman_id} = $form->{salesman_id};
979
980   delete $form->{$_} foreach (qw(id printed emailed queued));
981
982   # When creating a new sales order from a saved sales invoice, reset id,
983   # ordnumber, transdate and deliverydate as we are creating a new order. This
984   # workflow is probably mainly used as a template mechanism for creating new
985   # orders from existing invoices, so we probably don't want to link the items.
986   # Is this order function called anywhere else?
987   # The worksflows in oe already call sales_order and purchase_order in oe, not
988   # this general function which now only seems to be called from saved sales
989   # invoices
990   # Why is ordnumber set to invnumber above, does this ever make sense?
991
992   if ( $form->{script} eq 'is.pl' && $form->{type} eq 'invoice' ) {
993     delete $form->{$_} foreach (qw(ordnumber id transdate deliverydate));
994   };
995
996   my $buysell;
997   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
998     $form->{title} = $locale->text('Add Purchase Order');
999     $form->{vc}    = 'vendor';
1000     $form->{type}  = 'purchase_order';
1001     $buysell       = 'sell';
1002   }
1003   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
1004     $form->{title} = $locale->text('Add Sales Order');
1005     $form->{vc}    = 'customer';
1006     $form->{type}  = 'sales_order';
1007     $buysell       = 'buy';
1008   }
1009   $form->{script} = 'oe.pl';
1010
1011   $form->{rowcount}--;
1012
1013   $form->{cp_id} *= 1;
1014
1015   require "bin/mozilla/$form->{script}";
1016   my $script = $form->{"script"};
1017   $script =~ s|.*/||;
1018   $script =~ s|.pl$||;
1019   $locale = Locale->new($::lx_office_conf{system}->{language}, $script);
1020
1021   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1022
1023   my $currency = $form->{currency};
1024
1025   &order_links;
1026
1027   $form->{currency}     = $currency;
1028   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
1029   $form->{exchangerate} = $form->{forex} || '';
1030
1031   for my $i (1 .. $form->{rowcount}) {
1032     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
1033             if ($form->{"${_}_${i}"}) }
1034         qw(ship qty sellprice basefactor discount));
1035     $form->{"converted_from_invoice_id_$i"} = delete $form->{"invoice_id_$i"};
1036   }
1037
1038   &prepare_order;
1039 }
1040
1041 sub quotation {
1042   $main::lxdebug->enter_sub();
1043
1044   my $form     = $main::form;
1045   my %myconfig = %main::myconfig;
1046   my $locale   = $main::locale;
1047
1048   _check_io_auth();
1049
1050   # we are coming from *_order and convert to quotation
1051   # it seems that quotation is only called if we have a existing order
1052   if ($form->{type} =~  /(sales|purchase)_order/) {
1053     $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1054   }
1055   if ($form->{second_run}) {
1056     $form->{print_and_post} = 0;
1057   }
1058   delete $form->{$_} foreach (qw(id printed emailed queued quonumber transaction_description));
1059
1060   my $buysell;
1061   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
1062     $form->{title} = $locale->text('Add Request for Quotation');
1063     $form->{vc}    = 'vendor';
1064     $form->{type}  = 'request_quotation';
1065     $buysell       = 'sell';
1066   }
1067   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
1068     $form->{title} = $locale->text('Add Quotation');
1069     $form->{vc}    = 'customer';
1070     $form->{type}  = 'sales_quotation';
1071     $buysell       = 'buy';
1072   }
1073
1074   $form->{cp_id} *= 1;
1075
1076   $form->{script} = 'oe.pl';
1077
1078   $form->{rowcount}--;
1079
1080   require "bin/mozilla/$form->{script}";
1081
1082   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1083
1084   my $currency = $form->{currency};
1085
1086   &order_links;
1087
1088   $form->{currency}     = $currency;
1089   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
1090   $form->{exchangerate} = $form->{forex} || '';
1091
1092   for my $i (1 .. $form->{rowcount}) {
1093     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
1094                                                      $form->{"${_}_${i}"})
1095             if ($form->{"${_}_${i}"}) }
1096         qw(ship qty sellprice basefactor discount lastcost));
1097   }
1098
1099   &prepare_order;
1100   &display_form;
1101
1102   $main::lxdebug->leave_sub();
1103 }
1104
1105 sub request_for_quotation {
1106   quotation();
1107 }
1108
1109 sub print_options {
1110   $::lxdebug->enter_sub();
1111
1112   my (%options) = @_;
1113
1114   _check_io_auth();
1115
1116   my $inline = delete $options{inline};
1117
1118   require SL::Helper::PrintOptions;
1119   my $print_options = SL::Helper::PrintOptions->get_print_options(
1120     form     => $::form,
1121     myconfig => \%::myconfig,
1122     locale   => $::locale,
1123     options  => \%options);
1124
1125   if ($inline) {
1126     $::lxdebug->leave_sub();
1127     return $print_options;
1128   }
1129
1130   print $print_options;
1131   $::lxdebug->leave_sub();
1132 }
1133
1134
1135 sub print {
1136   $main::lxdebug->enter_sub();
1137
1138   my $form     = $main::form;
1139   my $locale   = $main::locale;
1140
1141   _check_io_auth();
1142
1143   if ($form->{print_nextsub}) {
1144     call_sub($form->{print_nextsub});
1145     $main::lxdebug->leave_sub();
1146     return;
1147   }
1148
1149   # if this goes to the printer pass through
1150   my $old_form;
1151   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1152     $form->error($locale->text('Select postscript or PDF!'))
1153       if ($form->{format} !~ /(postscript|pdf)/);
1154
1155     $old_form = Form->new;
1156     map { $old_form->{$_} = $form->{$_} } keys %$form;
1157   }
1158
1159   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1160     if ($form->{formname} eq "proforma") {
1161       $form->{proforma} = 1;
1162     }
1163     $form->{print_and_save} = 1;
1164     my $formname = $form->{formname};
1165     &save();
1166     $form->{formname} = $formname;
1167     &edit();
1168     $::lxdebug->leave_sub();
1169     $::dispatcher->end_request;
1170   }
1171
1172   &print_form($old_form);
1173
1174   $main::lxdebug->leave_sub();
1175 }
1176
1177 sub print_form {
1178   $main::lxdebug->enter_sub();
1179
1180   my $form     = $main::form;
1181   my %myconfig = %main::myconfig;
1182   my $locale   = $main::locale;
1183
1184   _check_io_auth();
1185
1186   my $defaults = SL::DB::Default->get;
1187   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
1188   $form->{templates} = $defaults->templates;
1189
1190   my ($old_form, %params) = @_;
1191
1192   my $inv       = "inv";
1193   my $due       = "due";
1194   my $numberfld = "invnumber";
1195   my $order;
1196
1197   my $display_form =
1198     ($form->{display_form}) ? $form->{display_form} : "display_form";
1199
1200   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1201   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1202
1203   if ($form->{formname} eq "invoice") {
1204     $form->{label} = $locale->text('Invoice');
1205   }
1206   if ($form->{formname} eq 'sales_order') {
1207     $inv                  = "ord";
1208     $due                  = "req";
1209     $form->{"${inv}date"} = $form->{transdate};
1210     $form->{label}        = $locale->text('Confirmation');
1211     $numberfld            = "sonumber";
1212     $order                = 1;
1213   }
1214
1215   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1216     $inv                  = "inv";
1217     $due                  = "due";
1218     $form->{"${inv}date"} = $form->{invdate};
1219     $form->{label}        = $locale->text('Proforma Invoice');
1220     $numberfld            = "sonumber";
1221     $order                = 0;
1222   }
1223
1224   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1225     $inv                  = "inv";
1226     $due                  = "due";
1227     $form->{"${inv}date"} = $form->{transdate};
1228     $form->{"invdate"}    = $form->{transdate};
1229     $form->{invnumber}    = $form->{ordnumber};
1230     $form->{label}        = $locale->text('Proforma Invoice');
1231     $numberfld            = "sonumber";
1232     $order                = 1;
1233   }
1234
1235   if ($form->{formname} eq 'purchase_order') {
1236     $inv                  = "ord";
1237     $due                  = "req";
1238     $form->{"${inv}date"} = $form->{transdate};
1239     $form->{label}        = $locale->text('Purchase Order');
1240     $numberfld            = "ponumber";
1241     $order                = 1;
1242   }
1243   if ($form->{formname} eq 'bin_list') {
1244     $inv                  = "ord";
1245     $due                  = "req";
1246     $form->{"${inv}date"} = $form->{transdate};
1247     $form->{label}        = $locale->text('Bin List');
1248     $order                = 1;
1249   }
1250   if ($form->{formname} eq 'sales_quotation') {
1251     $inv                  = "quo";
1252     $due                  = "req";
1253     $form->{"${inv}date"} = $form->{transdate};
1254     $form->{label}        = $locale->text('Quotation');
1255     $numberfld            = "sqnumber";
1256     $order                = 1;
1257   }
1258
1259   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1260     $inv                  = "quo";
1261     $due                  = "req";
1262     $form->{"${inv}date"} = $form->{transdate};
1263     $form->{"invdate"}    = $form->{transdate};
1264     $form->{label}        = $locale->text('Proforma Invoice');
1265     $numberfld            = "sqnumber";
1266     $order                = 1;
1267   }
1268
1269   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'ic_supply') ) {
1270     $inv                  = "inv";
1271     $due                  = "due";
1272     $form->{"${inv}date"} = $form->{transdate};
1273     $form->{"invdate"}    = $form->{transdate};
1274     $form->{invnumber}    = $form->{ordnumber};
1275     $form->{label}        = $locale->text('Intra-Community supply');
1276     $numberfld            = "sonumber";
1277     $order                = 1;
1278   }
1279
1280   if ($form->{formname} eq 'request_quotation') {
1281     $inv                  = "quo";
1282     $due                  = "req";
1283     $form->{"${inv}date"} = $form->{transdate};
1284     $form->{label}        = $locale->text('RFQ');
1285     $numberfld            = "rfqnumber";
1286     $order                = 1;
1287   }
1288
1289   if ($form->{type} =~ /_delivery_order$/) {
1290     undef $due;
1291     $inv                  = "do";
1292     $form->{"${inv}date"} = $form->{transdate};
1293     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1294     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1295   }
1296   if ($form->{type} =~ /letter/) {
1297     undef $due;
1298     undef $inv;
1299     $form->{label}        = $locale->text('Letter');
1300   }
1301
1302   $form->{TEMPLATE_DRIVER_OPTIONS} = { };
1303   if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice request_quotation purchase_order purchase_delivery_order credit_note)) {
1304     $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = $form->get_variable_content_types();
1305   }
1306
1307   if ($form->{format} =~ m{pdf}) {
1308     _maybe_attach_zugferd_data($form);
1309   }
1310
1311   $form->isblank("email", $locale->text('E-mail address missing!'))
1312     if ($form->{media} eq 'email');
1313   $form->isblank("${inv}date",
1314            $locale->text($form->{label})
1315            . ": "
1316            . $locale->text(' Date missing!'));
1317
1318   # $locale->text('Invoice Number missing!')
1319   # $locale->text('Invoice Date missing!')
1320   # $locale->text('Order Number missing!')
1321   # $locale->text('Order Date missing!')
1322   # $locale->text('Quotation Number missing!')
1323   # $locale->text('Quotation Date missing!')
1324
1325   $form->{what_done} = $form->{formname};
1326
1327   &validate_items;
1328
1329   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1330   my ($saved_email, $saved_cc, $saved_bcc) =
1331     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1332
1333   my $language_saved = $form->{language_id};
1334   my $payment_id_saved = $form->{payment_id};
1335   my $delivery_term_id_saved = $form->{delivery_term_id};
1336   my $salesman_id_saved = $form->{salesman_id};
1337   my $cp_id_saved = $form->{cp_id};
1338   my $taxzone_id_saved = $form->{taxzone_id};
1339   my $currency_saved = $form->{currency};
1340
1341   call_sub("$form->{vc}_details") if ($form->{vc});
1342
1343   $form->{language_id} = $language_saved;
1344   $form->{payment_id} = $payment_id_saved;
1345   $form->{delivery_term_id} = $delivery_term_id_saved;
1346   $form->{taxzone_id} = $taxzone_id_saved;
1347   $form->{currency} = $currency_saved;
1348
1349   $form->{"email"} = $saved_email if ($saved_email);
1350   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1351   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1352
1353   if (!$cp_id_saved) {
1354     # No contact was selected. Delete all contact variables because
1355     # IS->customer_details() and IR->vendor_details() get the default
1356     # contact anyway.
1357     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1358   }
1359
1360   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1361   if ($form->{"language_id"}) {
1362     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1363       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1364   } else {
1365     $output_dateformat = $myconfig{"dateformat"};
1366     $output_numberformat = $myconfig{"numberformat"};
1367     $output_longdates = 1;
1368   }
1369
1370   # Store the output number format so that the template modules know
1371   # how to parse the amounts back if requested.
1372   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
1373
1374   ($form->{employee}) = split /--/, $form->{employee};
1375
1376   # create the form variables
1377   if ($form->{type} =~ /_delivery_order$/) {
1378     DO->order_details(\%myconfig, \%$form);
1379   } elsif ($order) {
1380     OE->order_details(\%myconfig, \%$form);
1381   } elsif ($form->{type} eq 'letter') {
1382     # right now, no details are needed
1383     # but i do not want to break the bad default (invoice)
1384   } else {
1385     IS->invoice_details(\%myconfig, \%$form, $locale);
1386   }
1387
1388   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
1389   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
1390
1391   if ($form->{shipto_id}) {
1392     $form->get_shipto(\%myconfig);
1393   }
1394
1395   $form->{notes} =~ s/^\s+//g;
1396
1397   delete $form->{printer_command};
1398
1399   $form->{language} = $form->get_template_language(\%myconfig);
1400
1401   my $printer_code;
1402   if ($form->{media} ne 'email') {
1403     $printer_code = $form->get_printer_code(\%myconfig);
1404     if ($printer_code ne "") {
1405       $printer_code = "_" . $printer_code;
1406     }
1407   }
1408
1409   if ($form->{language} ne "") {
1410     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
1411     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
1412
1413     $form->{language} = "_" . $form->{language};
1414   }
1415
1416   # Format dates.
1417   format_dates($output_dateformat, $output_longdates,
1418                qw(invdate orddate quodate pldate duedate reqdate transdate tax_point
1419                   shippingdate deliverydate validitydate paymentdate
1420                   datepaid transdate_oe transdate_do transdate_quo deliverydate_oe dodate
1421                   employee_startdate employee_enddate
1422                   ),
1423                grep({ /^datepaid_\d+$/ ||
1424                         /^transdate_oe_\d+$/ ||
1425                         /^transdate_do_\d+$/ ||
1426                         /^transdate_quo_\d+$/ ||
1427                         /^deliverydate_oe_\d+$/ ||
1428                         /^reqdate_\d+$/ ||
1429                         /^deliverydate_\d+$/ ||
1430                         /^transdate_\d+$/
1431                     } keys(%{$form})));
1432
1433   reformat_numbers($output_numberformat, 2,
1434                    qw(invtotal ordtotal quototal subtotal linetotal
1435                       listprice sellprice netprice discount
1436                       tax taxbase total paid payment),
1437                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
1438
1439   reformat_numbers($output_numberformat, undef,
1440                    qw(qty price_factor),
1441                    grep({ /^qty_\d+$/
1442                         } keys(%{$form})));
1443
1444   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1445
1446   if (scalar @{ $cvar_date_fields }) {
1447     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1448   }
1449
1450   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1451     reformat_numbers($output_numberformat, $precision, @{ $field_list });
1452   }
1453
1454   my $extension = 'html';
1455   if ($form->{format} eq 'postscript') {
1456     $form->{postscript}   = 1;
1457     $extension            = 'tex';
1458
1459   } elsif ($form->{"format"} =~ /pdf/) {
1460     $form->{pdf}          = 1;
1461     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
1462
1463   } elsif ($form->{"format"} =~ /opendocument/) {
1464     $form->{opendocument} = 1;
1465     $extension            = 'odt';
1466   } elsif ($form->{"format"} =~ /excel/) {
1467     $form->{excel} = 1;
1468     $extension            = 'xls';
1469   }
1470
1471   # search for the template
1472   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1473     name        => $form->{formname},
1474     email       => $form->{media} eq 'email',
1475     language_id => $form->{language_id},
1476     printer_id  => $form->{printer_id},
1477     extension   => $extension,
1478   );
1479
1480   if (!defined $template_file) {
1481     $::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));
1482   }
1483
1484   $form->{IN} = $template_file;
1485
1486   delete $form->{OUT};
1487
1488   if ($form->{media} eq 'printer') {
1489     $form->{OUT}      = $form->{printer_command};
1490     $form->{OUT_MODE} = '|-';
1491     $form->{printed} .= " $form->{formname}";
1492     $form->{printed}  =~ s/^ //;
1493   }
1494   my $printed = $form->{printed};
1495
1496   if ($form->{media} eq 'email') {
1497     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1498       unless $form->{subject};
1499
1500     $form->{emailed} .= " $form->{formname}";
1501     $form->{emailed} =~ s/^ //;
1502     $form->{addition} = "MAILED";
1503   }
1504   my $emailed = $form->{emailed};
1505
1506   if ($form->{media} eq 'queue') {
1507     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
1508
1509     my $filename;
1510     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
1511     if ($filename = $queued{ $form->{formname} }) {
1512       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
1513       delete $queued{ $form->{formname} };
1514
1515       $form->{queued}    =  join ' ', %queued;
1516       $filename          =~ s/\..*$//g;
1517       $filename         .=  $suffix;
1518       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
1519       $form->{OUT_MODE}  =  '>';
1520
1521     } else {
1522       my $temp_fh;
1523       ($temp_fh, $filename) = File::Temp::tempfile(
1524         'kivitendo-spoolXXXXXX',
1525         SUFFIX => "$suffix",
1526         DIR    => $::lx_office_conf{paths}->{spool},
1527         UNLINK => 0,
1528       );
1529       close $temp_fh;
1530       $form->{OUT} = "$filename";
1531       # use >> for OUT_MODE because file is already created by File::Temp
1532       $form->{OUT_MODE} = '>>';
1533       # strip directory so that only filename is stored in table status
1534       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
1535     }
1536
1537     # add type
1538     $form->{queued} .= " $form->{formname} $filename";
1539     $form->{queued} =~ s/^ //;
1540   }
1541   my $queued = $form->{queued};
1542
1543 # saving the history
1544   if(!exists $form->{addition}) {
1545     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1546     if($form->{media} =~ /printer/) {
1547       $form->{addition} = "PRINTED";
1548     }
1549     elsif($form->{media} =~ /email/) {
1550       $form->{addition} = "MAILED";
1551     }
1552     elsif($form->{media} =~ /queue/) {
1553       $form->{addition} = "QUEUED";
1554     }
1555     elsif($form->{media} =~ /screen/) {
1556       $form->{addition} = "SCREENED";
1557     }
1558     $form->save_history;
1559   }
1560   # /saving the history
1561
1562   # prepare meta information for template introspection
1563   $form->{template_meta} = {
1564     formname  => $form->{formname},
1565     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
1566     format    => $form->{format},
1567     media     => $form->{media},
1568     extension => $extension,
1569     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
1570     today     => DateTime->today,
1571   };
1572
1573   if ($defaults->print_interpolate_variables_in_positions) {
1574     $form->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
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 }