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