ca43b4939135e5afd5f3b4d04bb2e3f985a5b88d
[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
1209   if ($form->{formname} eq "invoice_for_advance_payment") {
1210     $form->{label} = $locale->text('Invoice for Advance Payment');
1211   }
1212
1213   if ($form->{formname} eq 'sales_order') {
1214     $inv                  = "ord";
1215     $due                  = "req";
1216     $form->{"${inv}date"} = $form->{transdate};
1217     $form->{label}        = $locale->text('Confirmation');
1218     $numberfld            = "sonumber";
1219     $order                = 1;
1220   }
1221
1222   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1223     $inv                  = "inv";
1224     $due                  = "due";
1225     $form->{"${inv}date"} = $form->{invdate};
1226     $form->{label}        = $locale->text('Proforma Invoice');
1227     $numberfld            = "sonumber";
1228     $order                = 0;
1229   }
1230
1231   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1232     $inv                  = "inv";
1233     $due                  = "due";
1234     $form->{"${inv}date"} = $form->{transdate};
1235     $form->{"invdate"}    = $form->{transdate};
1236     $form->{invnumber}    = $form->{ordnumber};
1237     $form->{label}        = $locale->text('Proforma Invoice');
1238     $numberfld            = "sonumber";
1239     $order                = 1;
1240   }
1241
1242   if ($form->{formname} eq 'purchase_order') {
1243     $inv                  = "ord";
1244     $due                  = "req";
1245     $form->{"${inv}date"} = $form->{transdate};
1246     $form->{label}        = $locale->text('Purchase Order');
1247     $numberfld            = "ponumber";
1248     $order                = 1;
1249   }
1250   if ($form->{formname} eq 'bin_list') {
1251     $inv                  = "ord";
1252     $due                  = "req";
1253     $form->{"${inv}date"} = $form->{transdate};
1254     $form->{label}        = $locale->text('Bin List');
1255     $order                = 1;
1256   }
1257   if ($form->{formname} eq 'sales_quotation') {
1258     $inv                  = "quo";
1259     $due                  = "req";
1260     $form->{"${inv}date"} = $form->{transdate};
1261     $form->{label}        = $locale->text('Quotation');
1262     $numberfld            = "sqnumber";
1263     $order                = 1;
1264   }
1265
1266   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1267     $inv                  = "quo";
1268     $due                  = "req";
1269     $form->{"${inv}date"} = $form->{transdate};
1270     $form->{"invdate"}    = $form->{transdate};
1271     $form->{label}        = $locale->text('Proforma Invoice');
1272     $numberfld            = "sqnumber";
1273     $order                = 1;
1274   }
1275
1276   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'ic_supply') ) {
1277     $inv                  = "inv";
1278     $due                  = "due";
1279     $form->{"${inv}date"} = $form->{transdate};
1280     $form->{"invdate"}    = $form->{transdate};
1281     $form->{invnumber}    = $form->{ordnumber};
1282     $form->{label}        = $locale->text('Intra-Community supply');
1283     $numberfld            = "sonumber";
1284     $order                = 1;
1285   }
1286
1287   if ($form->{formname} eq 'request_quotation') {
1288     $inv                  = "quo";
1289     $due                  = "req";
1290     $form->{"${inv}date"} = $form->{transdate};
1291     $form->{label}        = $locale->text('RFQ');
1292     $numberfld            = "rfqnumber";
1293     $order                = 1;
1294   }
1295
1296   if ($form->{type} =~ /_delivery_order$/) {
1297     undef $due;
1298     $inv                  = "do";
1299     $form->{"${inv}date"} = $form->{transdate};
1300     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1301     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1302   }
1303   if ($form->{type} =~ /letter/) {
1304     undef $due;
1305     undef $inv;
1306     $form->{label}        = $locale->text('Letter');
1307   }
1308
1309   $form->{TEMPLATE_DRIVER_OPTIONS} = { };
1310   if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice invoice_for_advance_payment request_quotation purchase_order purchase_delivery_order credit_note)) {
1311     $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = $form->get_variable_content_types();
1312   }
1313
1314   if ($form->{format} =~ m{pdf}) {
1315     _maybe_attach_zugferd_data($form);
1316   }
1317
1318   $form->isblank("email", $locale->text('E-mail address missing!'))
1319     if ($form->{media} eq 'email');
1320   $form->isblank("${inv}date",
1321            $locale->text($form->{label})
1322            . ": "
1323            . $locale->text(' Date missing!'));
1324
1325   # $locale->text('Invoice Number missing!')
1326   # $locale->text('Invoice Date missing!')
1327   # $locale->text('Order Number missing!')
1328   # $locale->text('Order Date missing!')
1329   # $locale->text('Quotation Number missing!')
1330   # $locale->text('Quotation Date missing!')
1331
1332   $form->{what_done} = $form->{formname};
1333
1334   &validate_items;
1335
1336   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1337   my ($saved_email, $saved_cc, $saved_bcc) =
1338     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1339
1340   my $language_saved = $form->{language_id};
1341   my $payment_id_saved = $form->{payment_id};
1342   my $delivery_term_id_saved = $form->{delivery_term_id};
1343   my $salesman_id_saved = $form->{salesman_id};
1344   my $cp_id_saved = $form->{cp_id};
1345   my $taxzone_id_saved = $form->{taxzone_id};
1346   my $currency_saved = $form->{currency};
1347
1348   call_sub("$form->{vc}_details") if ($form->{vc});
1349
1350   $form->{language_id} = $language_saved;
1351   $form->{payment_id} = $payment_id_saved;
1352   $form->{delivery_term_id} = $delivery_term_id_saved;
1353   $form->{taxzone_id} = $taxzone_id_saved;
1354   $form->{currency} = $currency_saved;
1355
1356   $form->{"email"} = $saved_email if ($saved_email);
1357   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1358   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1359
1360   if (!$cp_id_saved) {
1361     # No contact was selected. Delete all contact variables because
1362     # IS->customer_details() and IR->vendor_details() get the default
1363     # contact anyway.
1364     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1365   }
1366
1367   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1368   if ($form->{"language_id"}) {
1369     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1370       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1371   } else {
1372     $output_dateformat = $myconfig{"dateformat"};
1373     $output_numberformat = $myconfig{"numberformat"};
1374     $output_longdates = 1;
1375   }
1376
1377   # Store the output number format so that the template modules know
1378   # how to parse the amounts back if requested.
1379   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
1380
1381   ($form->{employee}) = split /--/, $form->{employee};
1382
1383   # create the form variables
1384   if ($form->{type} =~ /_delivery_order$/) {
1385     DO->order_details(\%myconfig, \%$form);
1386   } elsif ($order) {
1387     OE->order_details(\%myconfig, \%$form);
1388   } elsif ($form->{type} eq 'letter') {
1389     # right now, no details are needed
1390     # but i do not want to break the bad default (invoice)
1391   } else {
1392     IS->invoice_details(\%myconfig, \%$form, $locale);
1393   }
1394
1395   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
1396   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
1397
1398   if ($form->{shipto_id}) {
1399     $form->get_shipto(\%myconfig);
1400   }
1401
1402   $form->set_addition_billing_address_print_variables;
1403
1404   $form->{notes} =~ s/^\s+//g;
1405
1406   delete $form->{printer_command};
1407
1408   $form->{language} = $form->get_template_language(\%myconfig);
1409
1410   my $printer_code;
1411   if ($form->{media} ne 'email') {
1412     $printer_code = $form->get_printer_code(\%myconfig);
1413     if ($printer_code ne "") {
1414       $printer_code = "_" . $printer_code;
1415     }
1416   }
1417
1418   if ($form->{language} ne "") {
1419     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
1420     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
1421
1422     $form->{language} = "_" . $form->{language};
1423   }
1424
1425   # Format dates.
1426   format_dates($output_dateformat, $output_longdates,
1427                qw(invdate orddate quodate pldate duedate reqdate transdate tax_point
1428                   shippingdate deliverydate validitydate paymentdate
1429                   datepaid transdate_oe transdate_do transdate_quo deliverydate_oe dodate
1430                   employee_startdate employee_enddate
1431                   ),
1432                grep({ /^datepaid_\d+$/ ||
1433                         /^transdate_oe_\d+$/ ||
1434                         /^transdate_do_\d+$/ ||
1435                         /^transdate_quo_\d+$/ ||
1436                         /^deliverydate_oe_\d+$/ ||
1437                         /^reqdate_\d+$/ ||
1438                         /^deliverydate_\d+$/ ||
1439                         /^transdate_\d+$/
1440                     } keys(%{$form})));
1441
1442   reformat_numbers($output_numberformat, 2,
1443                    qw(invtotal ordtotal quototal subtotal linetotal
1444                       listprice sellprice netprice discount
1445                       tax taxbase total paid payment),
1446                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
1447
1448   reformat_numbers($output_numberformat, undef,
1449                    qw(qty price_factor),
1450                    grep({ /^qty_\d+$/
1451                         } keys(%{$form})));
1452
1453   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1454
1455   if (scalar @{ $cvar_date_fields }) {
1456     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1457   }
1458
1459   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1460     reformat_numbers($output_numberformat, $precision, @{ $field_list });
1461   }
1462
1463   my $extension = 'html';
1464   if ($form->{format} eq 'postscript') {
1465     $form->{postscript}   = 1;
1466     $extension            = 'tex';
1467
1468   } elsif ($form->{"format"} =~ /pdf/) {
1469     $form->{pdf}          = 1;
1470     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
1471
1472   } elsif ($form->{"format"} =~ /opendocument/) {
1473     $form->{opendocument} = 1;
1474     $extension            = 'odt';
1475   } elsif ($form->{"format"} =~ /excel/) {
1476     $form->{excel} = 1;
1477     $extension            = 'xls';
1478   }
1479
1480   # search for the template
1481   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1482     name        => $form->{formname},
1483     email       => $form->{media} eq 'email',
1484     language_id => $form->{language_id},
1485     printer_id  => $form->{printer_id},
1486     extension   => $extension,
1487   );
1488
1489   if (!defined $template_file) {
1490     $::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));
1491   }
1492
1493   $form->{IN} = $template_file;
1494
1495   delete $form->{OUT};
1496
1497   if ($form->{media} eq 'printer') {
1498     $form->{OUT}      = $form->{printer_command};
1499     $form->{OUT_MODE} = '|-';
1500     $form->{printed} .= " $form->{formname}";
1501     $form->{printed}  =~ s/^ //;
1502   }
1503   my $printed = $form->{printed};
1504
1505   if ($form->{media} eq 'email') {
1506     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1507       unless $form->{subject};
1508
1509     $form->{emailed} .= " $form->{formname}";
1510     $form->{emailed} =~ s/^ //;
1511     $form->{addition} = "MAILED";
1512   }
1513   my $emailed = $form->{emailed};
1514
1515   if ($form->{media} eq 'queue') {
1516     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
1517
1518     my $filename;
1519     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
1520     if ($filename = $queued{ $form->{formname} }) {
1521       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
1522       delete $queued{ $form->{formname} };
1523
1524       $form->{queued}    =  join ' ', %queued;
1525       $filename          =~ s/\..*$//g;
1526       $filename         .=  $suffix;
1527       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
1528       $form->{OUT_MODE}  =  '>';
1529
1530     } else {
1531       my $temp_fh;
1532       ($temp_fh, $filename) = File::Temp::tempfile(
1533         'kivitendo-spoolXXXXXX',
1534         SUFFIX => "$suffix",
1535         DIR    => $::lx_office_conf{paths}->{spool},
1536         UNLINK => 0,
1537       );
1538       close $temp_fh;
1539       $form->{OUT} = "$filename";
1540       # use >> for OUT_MODE because file is already created by File::Temp
1541       $form->{OUT_MODE} = '>>';
1542       # strip directory so that only filename is stored in table status
1543       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
1544     }
1545
1546     # add type
1547     $form->{queued} .= " $form->{formname} $filename";
1548     $form->{queued} =~ s/^ //;
1549   }
1550   my $queued = $form->{queued};
1551
1552 # saving the history
1553   if(!exists $form->{addition}) {
1554     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1555     if($form->{media} =~ /printer/) {
1556       $form->{addition} = "PRINTED";
1557     }
1558     elsif($form->{media} =~ /email/) {
1559       $form->{addition} = "MAILED";
1560     }
1561     elsif($form->{media} =~ /queue/) {
1562       $form->{addition} = "QUEUED";
1563     }
1564     elsif($form->{media} =~ /screen/) {
1565       $form->{addition} = "SCREENED";
1566     }
1567     $form->save_history;
1568   }
1569   # /saving the history
1570
1571   # prepare meta information for template introspection
1572   $form->{template_meta} = {
1573     formname  => $form->{formname},
1574     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
1575     format    => $form->{format},
1576     media     => $form->{media},
1577     extension => $extension,
1578     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
1579     today     => DateTime->today,
1580   };
1581
1582   if ($defaults->print_interpolate_variables_in_positions) {
1583     $form->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
1584   }
1585
1586   $form->parse_template(\%myconfig);
1587
1588   $form->{callback} = "";
1589
1590   if ($form->{media} eq 'email') {
1591     $form->{message} = $locale->text('sent') unless $form->{message};
1592   }
1593   my $message = $form->{message};
1594
1595   # if we got back here restore the previous form
1596   if ($form->{media} =~ /(printer|email|queue)/) {
1597
1598     $form->update_status(\%myconfig)
1599       if ($form->{media} eq 'queue' && $form->{id});
1600
1601     return $main::lxdebug->leave_sub() if ($old_form eq "return");
1602
1603     if ($old_form) {
1604
1605       $old_form->{"${inv}number"} = $form->{"${inv}number"};
1606
1607       # restore and display form
1608       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1609
1610       $form->{queued}  = $queued;
1611       $form->{printed} = $printed;
1612       $form->{emailed} = $emailed;
1613       $form->{message} = $message;
1614
1615       $form->{rowcount}--;
1616       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1617         qw(exchangerate creditlimit creditremaining);
1618
1619       for my $i (1 .. $form->{paidaccounts}) {
1620         map {
1621           $form->{"${_}_$i"} =
1622             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1623         } qw(paid exchangerate);
1624       }
1625
1626       call_sub($display_form);
1627       $::dispatcher->end_request;
1628     }
1629
1630     my $msg =
1631       ($form->{media} eq 'printer')
1632       ? $locale->text('sent to printer')
1633       : $locale->text('emailed to') . " $form->{email}";
1634
1635     if (!$params{no_redirect}) {
1636       $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1637     }
1638   }
1639   if ($form->{printing}) {
1640    call_sub($display_form);
1641    $::dispatcher->end_request;
1642   }
1643
1644   $main::lxdebug->leave_sub();
1645 }
1646
1647 sub customer_details {
1648   $main::lxdebug->enter_sub();
1649
1650   my $form     = $main::form;
1651   my %myconfig = %main::myconfig;
1652
1653   IS->customer_details(\%myconfig, \%$form, @_);
1654
1655   $main::lxdebug->leave_sub();
1656 }
1657
1658 sub vendor_details {
1659   $main::lxdebug->enter_sub();
1660
1661   my $form     = $main::form;
1662   my %myconfig = %main::myconfig;
1663
1664   IR->vendor_details(\%myconfig, \%$form, @_);
1665
1666   $main::lxdebug->leave_sub();
1667 }
1668
1669 sub post_as_new {
1670   $main::lxdebug->enter_sub();
1671
1672   my $form     = $main::form;
1673
1674   _check_io_auth();
1675
1676   $form->{postasnew} = 1;
1677   map { delete $form->{$_} } qw(printed emailed queued);
1678
1679   &post;
1680
1681   $main::lxdebug->leave_sub();
1682 }
1683
1684 sub relink_accounts {
1685   $main::lxdebug->enter_sub();
1686
1687   my $form     = $main::form;
1688   my %myconfig = %main::myconfig;
1689
1690   $form->{"taxaccounts"} =~ s/\s*$//;
1691   $form->{"taxaccounts"} =~ s/^\s*//;
1692   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1693     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber tax_id)); # add tax_id ?
1694   }
1695   $form->{"taxaccounts"} = "";
1696
1697   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1698
1699   $main::lxdebug->leave_sub();
1700 }
1701
1702 sub get_payment_terms_for_invoice {
1703   my $terms = $::form->{payment_id}  ? SL::DB::PaymentTerm->new(id => $::form->{payment_id}) ->load
1704             : $::form->{customer_id} ? SL::DB::Customer   ->new(id => $::form->{customer_id})->load->payment
1705             : $::form->{vendor_id}   ? SL::DB::Vendor     ->new(id => $::form->{vendor_id})  ->load->payment
1706             :                          undef;
1707
1708   return $terms;
1709 }
1710
1711 sub set_duedate {
1712   _check_io_auth();
1713
1714   my $js      = SL::ClientJS->new(controller => SL::Controller::Base->new);
1715   my $terms   = get_payment_terms_for_invoice();
1716   my $invdate = $::form->{invdate} eq 'undefined' ? DateTime->today_local : DateTime->from_kivitendo($::form->{invdate});
1717   my $duedate = $terms ? $terms->calc_date(reference_date => $invdate, due_date => $::form->{duedate})->to_kivitendo : ($::form->{duedate} || $invdate->to_kivitendo);
1718
1719   if ($terms && $terms->auto_calculation) {
1720     $js->hide('#duedate_container')
1721        ->show('#duedate_fixed')
1722        ->html('#duedate_fixed', $duedate);
1723
1724   } else {
1725     $js->show('#duedate_container')
1726        ->hide('#duedate_fixed');
1727   }
1728
1729   $js->val('#duedate', $duedate)
1730      ->render;
1731 }
1732
1733 sub _update_part_information {
1734   $main::lxdebug->enter_sub();
1735
1736   my $form     = $main::form;
1737
1738   my %part_information = IC->get_basic_part_info('id' => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ]);
1739
1740   $form->{PART_INFORMATION} = \%part_information;
1741
1742   foreach my $i (1..$form->{rowcount}) {
1743     next unless ($form->{"id_${i}"});
1744
1745     my $info                        = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
1746     $form->{"partunit_${i}"}        = $info->{unit};
1747     $form->{"weight_$i"}            = $info->{weight};
1748     $form->{"part_type_$i"}         = $info->{part_type};
1749     $form->{"classification_id_$i"} = $info->{classification_id};
1750     $form->{"has_sernumber_$i"}     = $info->{has_sernumber};
1751   }
1752
1753   $main::lxdebug->leave_sub();
1754 }
1755
1756 sub _update_ship {
1757   return unless $::form->{id};
1758   my $helper = SL::Helper::ShippedQty->new->calculate($::form->{id});
1759
1760   for my $i (1..$::form->{rowcount}) {
1761     if (my $oid = $::form->{"orderitems_id_$i"}) {
1762       $::form->{"ship_$i"} = $helper->shipped_qty->{$oid};
1763     }
1764   }
1765 }
1766
1767 sub _update_custom_variables {
1768   $main::lxdebug->enter_sub();
1769
1770   my $form     = $main::form;
1771
1772   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
1773   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
1774
1775   $main::lxdebug->leave_sub();
1776 }
1777
1778 sub _render_custom_variables_inputs {
1779   $main::lxdebug->enter_sub(2);
1780
1781   my $form     = $main::form;
1782
1783   my %params = @_;
1784
1785   if (!$form->{CVAR_CONFIGS}->{IC}) {
1786     $main::lxdebug->leave_sub();
1787     return;
1788   }
1789
1790   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
1791
1792   # get partsgroup_id from part
1793   my $partsgroup_id;
1794   if ($params{part_id}) {
1795     $partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id;
1796   }
1797
1798   my $num_visible_cvars = 0;
1799   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
1800     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
1801
1802     # set partsgroup filter
1803     my $partsgroup_filtered = 0;
1804     if ($cvar->{flag_partsgroup_filter}) {
1805       if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) {
1806         $partsgroup_filtered = 1;
1807       }
1808     }
1809
1810     my $hide_non_editable = 1;
1811
1812     my $show = 0;
1813     my $description = '';
1814     if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) {
1815       $num_visible_cvars++;
1816       $description = $cvar->{description} . ' ';
1817       $show = 1;
1818     }
1819
1820     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
1821
1822     push @{ $params{ROW2} }, {
1823       line_break     => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)),
1824       description    => $description,
1825       cvar           => 1,
1826       render_options => {
1827          hide_non_editable => $hide_non_editable,
1828          var               => $cvar,
1829          name_prefix       => 'ic_',
1830          name_postfix      => "_$params{row}",
1831          valid             => $cvar->{valid},
1832          value             => CVar->parse($::form->{$form_key}, $cvar),
1833          partsgroup_filtered => $partsgroup_filtered,
1834       }
1835     };
1836   }
1837
1838   $main::lxdebug->leave_sub(2);
1839 }
1840
1841 sub _remove_billed_or_delivered_rows {
1842   my (%params) = @_;
1843
1844   croak "Missing parameter 'quantities'" if !$params{quantities};
1845
1846   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
1847   my @new_rows;
1848
1849   my $make_key = sub {
1850     my ($row) = @_;
1851     return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
1852     my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
1853     return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
1854   };
1855
1856   my $removed_rows = 0;
1857   my $row          = 0;
1858   while ($row < $::form->{rowcount}) {
1859     $row++;
1860     next unless $::form->{"id_$row"};
1861
1862     my $parts_id                      = $::form->{"id_$row"};
1863     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
1864
1865     my $key                           = $make_key->($row);
1866     my $sub_qty                       = min($base_qty, $params{quantities}->{$key});
1867     $params{quantities}->{$key}      -= $sub_qty;
1868
1869     if (!$sub_qty || ($sub_qty != $base_qty)) {
1870       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
1871       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
1872
1873     } else {
1874       $removed_rows++;
1875     }
1876   }
1877
1878   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
1879   $::form->{rowcount} -= $removed_rows;
1880 }
1881
1882 # TODO: both of these are makeshift so that price sources can operate on rdbo objects. if
1883 # this ever gets rewritten in controller style, throw this out
1884 sub _make_record_item {
1885   my ($row, %params) = @_;
1886
1887   my $class = {
1888     sales_order             => 'OrderItem',
1889     purchase_order          => 'OrderItem',
1890     sales_quotation         => 'OrderItem',
1891     request_quotation       => 'OrderItem',
1892     invoice                 => 'InvoiceItem',
1893     invoice_for_advance_payment => 'InvoiceItem',
1894     credit_note             => 'InvoiceItem',
1895     purchase_invoice        => 'InvoiceItem',
1896     purchase_delivery_order => 'DeliveryOrderItem',
1897     sales_delivery_order    => 'DeliveryOrderItem',
1898   }->{$::form->{type}};
1899
1900   return unless $class;
1901
1902   $class = 'SL::DB::' . $class;
1903
1904   my %translated_methods = (
1905     'SL::DB::OrderItem' => {
1906       id                      => 'parts_id',
1907       orderitems_id           => 'id',
1908     },
1909     'SL::DB::DeliveryOrderItem' => {
1910       id                      => 'parts_id',
1911       delivery_order_items_id => 'id',
1912     },
1913     'SL::DB::InvoiceItem' => {
1914       id                      => 'parts_id',
1915       invoice_id => 'id',
1916     },
1917   );
1918
1919   eval "require $class";
1920
1921   my $obj = $::form->{"orderitems_id_$row"}
1922           ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{"orderitems_id_$row"})
1923           : $class->new;
1924
1925   for my $key (grep { /_$row$/ } keys %$::form) {
1926     my $method = $key;
1927     $method =~ s/_$row$//;
1928     $method = $translated_methods{$class}{$method} // $method;
1929     my $value = $::form->{$key};
1930     if ($obj->meta->column($method)) {
1931       if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
1932         $obj->${\"$method\_as_date"}($value);
1933       } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
1934         $obj->${\"$method\_as_number"}(($value // '') eq '' ? undef : $value);
1935       } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
1936         $obj->$method(!!$value);
1937       } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
1938         $obj->$method(($value // '') eq '' ? undef : $value * 1);
1939       } else {
1940         $obj->$method($value);
1941       }
1942
1943       if ($method eq 'discount') {
1944         $obj->discount($obj->discount / 100.0);
1945       }
1946
1947     } else {
1948       $obj->{__additional_form_attributes}{$method} = $value;
1949     }
1950   }
1951
1952   if ($::form->{"id_$row"}) {
1953     $obj->part(SL::DB::Part->load_cached($::form->{"id_$row"}));
1954   }
1955
1956   if ($obj->can('qty')) {
1957     $obj->qty(     $obj->qty      * $params{factor});
1958     $obj->base_qty($obj->base_qty * $params{factor});
1959   }
1960
1961   return $obj;
1962 }
1963
1964 sub _make_record {
1965   my $class = {
1966     sales_order             => 'Order',
1967     purchase_order          => 'Order',
1968     sales_quotation         => 'Order',
1969     request_quotation       => 'Order',
1970     purchase_delivery_order => 'DeliveryOrder',
1971     sales_delivery_order    => 'DeliveryOrder',
1972   }->{$::form->{type}};
1973
1974   if ($::form->{type} =~ /invoice|credit_note/) {
1975     $class = $::form->{vc} eq 'customer' ? 'Invoice'
1976            : $::form->{vc} eq 'vendor'   ? 'PurchaseInvoice'
1977            : do { die 'unknown invoice type' };
1978   }
1979
1980   my $factor = $::form->{type} =~ m{credit_note} ? -1 : 1;
1981
1982   return unless $class;
1983
1984   $class = 'SL::DB::' . $class;
1985
1986   eval "require $class";
1987
1988   my $obj = $::form->{id}
1989           ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{id})
1990           : $class->new;
1991
1992   for my $method (keys %$::form) {
1993     next unless $obj->can($method);
1994     next unless $obj->meta->column($method);
1995
1996     if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
1997       $obj->${\"$method\_as_date"}($::form->{$method});
1998     } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
1999       $obj->${\"$method\_as_number"}(($::form->{$method} // '') eq '' ? undef : $::form->{$method});
2000     } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
2001       $obj->$method(!!$::form->{$method});
2002     } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
2003       $obj->$method(($::form->{$method} // '') eq '' ? undef : $::form->{$method} * 1);
2004     } else {
2005       $obj->$method($::form->{$method});
2006     }
2007   }
2008
2009   my @items;
2010   for my $i (1 .. $::form->{rowcount}) {
2011     next unless $::form->{"id_$i"};
2012     push @items, _make_record_item($i, factor => $factor);
2013   }
2014
2015   $obj->items(@items) if @items;
2016   $obj->is_sales(!!$obj->customer_id) if $class eq 'SL::DB::DeliveryOrder';
2017
2018   if ($class eq 'SL::DB::Invoice') {
2019     my $paid = $factor *
2020       sum
2021       map  { $::form->parse_amount(\%::myconfig, $::form->{$_}) }
2022       grep { m{^paid_\d+$} }
2023       keys %{ $::form };
2024     $obj->paid($paid);
2025   }
2026
2027   return $obj;
2028 }
2029
2030 sub setup_sales_purchase_print_options {
2031   my $print_form = Form->new('');
2032   $print_form->{printers}  = SL::DB::Manager::Printer->get_all_sorted;
2033
2034   $print_form->{$_} = $::form->{$_} for qw(type media printer_id storno formname groupitems);
2035
2036   return SL::Helper::PrintOptions->get_print_options(
2037     form    => $print_form,
2038     options => {
2039       show_headers => 1,
2040     },
2041   );
2042 }
2043
2044 sub _get_files_for_email_dialog {
2045   my %files = map { ($_ => []) } qw(versions files vc_files part_files project_files);
2046
2047   return %files if !$::instance_conf->get_doc_storage;
2048
2049   if ($::form->{id}) {
2050     $files{versions} = [ SL::File->get_all_versions(object_id => $::form->{id},    object_type => $::form->{type}, file_type => 'document') ];
2051     $files{files}    = [ SL::File->get_all(         object_id => $::form->{id},    object_type => $::form->{type}, file_type => 'attachment') ];
2052     $files{vc_files} = [ SL::File->get_all(         object_id => $::form->{vc_id}, object_type => $::form->{vc},   file_type => 'attachment') ]
2053       if $::form->{vc} && $::form->{"vc_id"};
2054     $files{project_files} = [ SL::File->get_all(object_id => $::form->{project_id}, object_type => 'project',file_type => 'attachment') ]
2055       if $::form->{project_id};
2056   }
2057
2058   my @parts =
2059     uniq_by { $_->{id} }
2060     grep    { $_->{id} }
2061     map     {
2062       +{ id         => $::form->{"id_$_"},
2063          partnumber => $::form->{"partnumber_$_"},
2064        }
2065     } (1 .. $::form->{rowcount});
2066
2067   foreach my $part (@parts) {
2068     my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
2069     push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
2070   }
2071
2072   foreach my $key (keys %files) {
2073     $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
2074   }
2075
2076   return %files;
2077 }
2078
2079 sub show_sales_purchase_email_dialog {
2080   my $email = '';
2081   my $email_cc = '';
2082   my $record_email;
2083   if ($::form->{cp_id}) {
2084     $email = SL::DB::Contact->load_cached($::form->{cp_id})->cp_email;
2085   }
2086   # write a dispatch table if a third type enters
2087   # check record mail for sales_invoice
2088   if ($::form->{type} eq 'invoice' && (!$email || $::instance_conf->get_invoice_mail_settings ne 'cp')) {
2089     # check for invoice_mail if defined (vc.invoice_email)
2090     $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->invoice_mail;
2091     if ($record_email) {
2092       # check if cc for contact is also wanted
2093       $email_cc = $email if ($::instance_conf->get_invoice_mail_settings eq 'invoice_mail_cc_cp');
2094       $email    = $record_email;
2095     }
2096   }
2097   # check record mail for sales_delivery_order
2098   if ($::form->{type} eq 'sales_delivery_order') {
2099     # check for deliver_order_mail if defined (vc.delivery_order_mail)
2100     $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->delivery_order_mail;
2101     if ($record_email) {
2102       # check if cc for contact is also wanted
2103       $email_cc = $email; # always cc to cp
2104       $email    = $record_email;
2105     }
2106   }
2107   # still no email? use general mail (vc.email)
2108   if (!$email && $::form->{vc} && $::form->{vc_id}) {
2109     $email = SL::DB::Customer->load_cached($::form->{vc_id})->email if 'customer' eq $::form->{vc};
2110     $email = SL::DB::Vendor  ->load_cached($::form->{vc_id})->email if 'vendor'   eq $::form->{vc};
2111   }
2112
2113   $email = '' if $::form->{type} eq 'purchase_delivery_order';
2114
2115   $::form->{language} = $::form->get_template_language(\%::myconfig);
2116   $::form->{language} = "_" . $::form->{language};
2117
2118   my %body_params = (record_email => $record_email);
2119   if (($::form->{type} eq 'invoice') && $::form->{direct_debit}) {
2120     $body_params{translation_type}          = "preset_text_invoice_direct_debit";
2121     $body_params{fallback_translation_type} = "preset_text_invoice";
2122   }
2123
2124   my @employees_with_email = grep {
2125     my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
2126     $user && !!trim($user->get_config_value('email'));
2127   } @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
2128
2129   my $email_form = {
2130     to                  => $email,
2131     cc                  => $email_cc,
2132     subject             => $::form->generate_email_subject,
2133     message             => $::form->generate_email_body(%body_params),
2134     attachment_filename => $::form->generate_attachment_filename,
2135     js_send_function    => 'kivi.SalesPurchase.send_email()',
2136   };
2137
2138   my %files = _get_files_for_email_dialog();
2139   my $html  = $::form->parse_html_template("common/_send_email_dialog", {
2140     email_form      => $email_form,
2141     show_bcc        => $::auth->assert('email_bcc', 'may fail'),
2142     FILES           => \%files,
2143     is_customer     => $::form->{vc} eq 'customer',
2144     is_invoice_mail => ($record_email && $::form->{type} eq 'invoice'),
2145     ALL_EMPLOYEES   => \@employees_with_email,
2146   });
2147
2148   print $::form->ajax_response_header, $html;
2149 }
2150
2151 sub send_sales_purchase_email {
2152   my $type        = $::form->{type};
2153   my $id          = $::form->{id};
2154   my $script      = $type =~ m{sales_order|purchase_order|quotation} ? 'oe.pl'
2155                   : $type =~ m{delivery_}                            ? 'do.pl'
2156                   :                                                    'is.pl';
2157
2158   my $email_form  = delete $::form->{email_form};
2159   my %field_names = (to => 'email');
2160
2161   $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
2162
2163   $::form->{media} = 'email';
2164
2165   $::form->{attachment_policy} //= '';
2166
2167   # Is an old file version available?
2168   my $attfile;
2169   if ($::form->{attachment_policy} eq 'old_file') {
2170     $attfile = SL::File->get_all(object_id     => $id,
2171                                  object_type   => $type,
2172                                  file_type     => 'document',
2173                                  print_variant => $::form->{formname},);
2174   }
2175
2176   if ($::form->{attachment_policy} eq 'no_file' || ($::form->{attachment_policy} eq 'old_file' && $attfile)) {
2177     $::form->send_email(\%::myconfig, 'pdf');
2178
2179   } else {
2180     print_form("return");
2181     Common->save_email_status(\%::myconfig, $::form);
2182   }
2183
2184   flash_later('info', $::locale->text('The email has been sent.'));
2185
2186   print $::form->redirect_header($script . '?action=edit&id=' . $::form->escape($id) . '&type=' . $::form->escape($type));
2187 }
2188
2189 sub _maybe_attach_zugferd_data {
2190   my ($form) = @_;
2191
2192   my $record = _make_record();
2193
2194   return if !$record
2195     || !$record->can('customer')
2196     || !$record->customer
2197     || !$record->can('create_pdf_a_print_options')
2198     || !$record->can('create_zugferd_data')
2199     || !$record->customer->create_zugferd_invoices_for_this_customer;
2200
2201   eval {
2202     my $xmlfile = File::Temp->new;
2203     $xmlfile->print($record->create_zugferd_data);
2204     $xmlfile->close;
2205
2206     $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_a}           = $record->create_pdf_a_print_options(zugferd_xmp_data => $record->create_zugferd_xmp_data);
2207     $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_attachments} = [
2208       { source       => $xmlfile,
2209         name         => 'factur-x.xml',
2210         description  => $::locale->text('Factur-X/ZUGFeRD invoice'),
2211         relationship => '/Alternative',
2212         mime_type    => 'text/xml',
2213       }
2214     ];
2215   };
2216
2217   if (my $e = SL::X::ZUGFeRDValidation->caught) {
2218     $::form->error($e->message);
2219   }
2220 }
2221
2222 sub download_factur_x_xml {
2223   my ($form) = @_;
2224
2225   my $record = _make_record();
2226
2227   die if !$record
2228       || !$record->can('customer')
2229       || !$record->customer
2230       || !$record->can('create_pdf_a_print_options')
2231       || !$record->can('create_zugferd_data')
2232       || !$record->customer->create_zugferd_invoices_for_this_customer;
2233
2234   my $xml_content = eval { $record->create_zugferd_data };
2235
2236   if (my $e = SL::X::ZUGFeRDValidation->caught) {
2237     $::form->error($e->message);
2238   }
2239
2240   my $attachment_filename = $::form->generate_attachment_filename;
2241   $attachment_filename    =~ s{\.[^.]+$}{.xml};
2242   my %headers             = (
2243     '-type'           => 'application/xml',
2244     '-connection'     => 'close',
2245     '-attachment'     => $attachment_filename,
2246     '-content-length' => length($xml_content),
2247   );
2248
2249   print $::request->cgi->header(%headers);
2250
2251   $::locale->with_raw_io(\*STDOUT, sub { print $xml_content });
2252 }