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