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