$::request->layout->focus() größtenteils durch class="initial_focus" ersetzen
[kivitendo-erp.git] / bin / mozilla / io.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #############################################################################
7 # Changelog: Wann - Wer - Was
8 # Veraendert 2005-01-05 - Marco Welter <mawe@linux-studio.de> - Neue Optik
9 # 08.11.2008 - information@richardson-bueren.de jb  - Backport von Revision 7339 xplace - E-Mail-Vorlage automatisch auswählen
10 # 02.02.2009 - information@richardson-bueren.de jb - Backport von Revision 8535 xplace - Erweiterung der Waren bei Lieferantenauftrag um den Eintrag Mindestlagerbestand. Offen: Auswahlliste auf Lieferantenaufträge einschränken -> Erledigt 2.2.09 Prüfung wie das Skript heisst (oe.pl) -> das ist nur die halbe Miete, nochmal mb fragen -> mb gefragt und es gibt die variable is_purchase
11 #############################################################################
12 # SQL-Ledger, Accounting
13 # Copyright (c) 1998-2002
14 #
15 #  Author: Dieter Simader
16 #   Email: dsimader@sql-ledger.org
17 #     Web: http://www.sql-ledger.org
18 #
19 #
20 # This program is free software; you can redistribute it and/or modify
21 # it under the terms of the GNU General Public License as published by
22 # the Free Software Foundation; either version 2 of the License, or
23 # (at your option) any later version.
24 #
25 # This program is distributed in the hope that it will be useful,
26 # but WITHOUT ANY WARRANTY; without even the implied warranty of
27 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28 # GNU General Public License for more details.
29 # You should have received a copy of the GNU General Public License
30 # along with this program; if not, write to the Free Software
31 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 #
33 #######################################################################
34 #
35 # common routines used in is, ir, oe
36 #
37 #######################################################################
38
39 use Carp;
40 use CGI;
41 use List::MoreUtils qw(any uniq);
42 use List::Util qw(min max first);
43
44 use SL::CVar;
45 use SL::Common;
46 use SL::CT;
47 use SL::IC;
48 use SL::IO;
49
50 use SL::DB::Default;
51 use SL::DB::Language;
52 use SL::DB::Printer;
53 use SL::Helper::Flash;
54
55 require "bin/mozilla/common.pl";
56
57 use strict;
58
59 # any custom scripts for this one
60 if (-f "bin/mozilla/custom_io.pl") {
61   eval { require "bin/mozilla/custom_io.pl"; };
62 }
63 if (-f "bin/mozilla/$::form->{login}_io.pl") {
64   eval { require "bin/mozilla/$::form->{login}_io.pl"; };
65 }
66
67 1;
68
69 # end of main
70
71 # this is for our long dates
72 # $locale->text('January')
73 # $locale->text('February')
74 # $locale->text('March')
75 # $locale->text('April')
76 # $locale->text('May ')
77 # $locale->text('June')
78 # $locale->text('July')
79 # $locale->text('August')
80 # $locale->text('September')
81 # $locale->text('October')
82 # $locale->text('November')
83 # $locale->text('December')
84
85 # this is for our short month
86 # $locale->text('Jan')
87 # $locale->text('Feb')
88 # $locale->text('Mar')
89 # $locale->text('Apr')
90 # $locale->text('May')
91 # $locale->text('Jun')
92 # $locale->text('Jul')
93 # $locale->text('Aug')
94 # $locale->text('Sep')
95 # $locale->text('Oct')
96 # $locale->text('Nov')
97 # $locale->text('Dec')
98 use SL::IS;
99 use SL::PE;
100 use SL::AM;
101 use Data::Dumper;
102
103 sub _check_io_auth {
104   $main::auth->assert('part_service_assembly_edit   | vendor_invoice_edit       | sales_order_edit    | invoice_edit |' .
105                 'request_quotation_edit       | sales_quotation_edit      | purchase_order_edit | ' .
106                 'purchase_delivery_order_edit | sales_delivery_order_edit');
107 }
108
109 ########################################
110 # Eintrag fuer Version 2.2.0 geaendert #
111 # neue Optik im Rechnungsformular      #
112 ########################################
113 sub display_row {
114   $main::lxdebug->enter_sub();
115
116   _check_io_auth();
117
118   my $form     = $main::form;
119   my %myconfig = %main::myconfig;
120   my $locale   = $main::locale;
121   my $cgi      = $::request->{cgi};
122
123   my $numrows = shift;
124
125   my ($stock_in_out, $stock_in_out_title);
126
127   my $defaults = AM->get_defaults();
128   $form->{show_weight} = $defaults->{show_weight};
129   $form->{weightunit} = $defaults->{weightunit};
130
131   my $is_purchase        = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
132   my $show_min_order_qty =  first { $_ eq $form->{type} } qw(request_quotation purchase_order);
133   my $is_delivery_order  = $form->{type} =~ /_delivery_order$/;
134   my $is_s_p_order       = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
135
136   if ($is_delivery_order) {
137     if ($form->{type} eq 'sales_delivery_order') {
138       $stock_in_out_title = $locale->text('Release From Stock');
139       $stock_in_out       = 'out';
140     } else {
141       $stock_in_out_title = $locale->text('Transfer To Stock');
142       $stock_in_out       = 'in';
143     }
144
145     retrieve_partunits();
146   }
147
148   # column_index
149   my @header_sort = qw(runningnumber partnumber description ship qty unit weight sellprice_pg sellprice discount linetotal);
150   my @HEADER = (
151     {  id => 'runningnumber', width => 5,     value => $locale->text('No.'),                  display => 1, },
152     {  id => 'partnumber',    width => 8,     value => $locale->text('Number'),               display => 1, },
153     {  id => 'description',   width => 30,    value => $locale->text('Part Description'),     display => 1, },
154     {  id => 'ship',          width => 5,     value => $locale->text('Delivered'),            display => $is_s_p_order, },
155     {  id => 'qty',           width => 5,     value => $locale->text('Qty'),                  display => 1, },
156     {  id => 'price_factor',  width => 5,     value => $locale->text('Price Factor'),         display => !$is_delivery_order, },
157     {  id => 'unit',          width => 5,     value => $locale->text('Unit'),                 display => 1, },
158     {  id => 'weight',        width => 5,     value => $locale->text('Weight'),               display => $defaults->{show_weight}, },
159     {  id => 'serialnr',      width => 10,    value => $locale->text('Serial No.'),           display => 0, },
160     {  id => 'projectnr',     width => 10,    value => $locale->text('Project'),              display => 0, },
161     {  id => 'sellprice',     width => 15,    value => $locale->text('Price'),                display => !$is_delivery_order, },
162     {  id => 'sellprice_pg',  width => 8,     value => $locale->text('Pricegroup'),           display => !$is_delivery_order && !$is_purchase, },
163     {  id => 'discount',      width => 5,     value => $locale->text('Discount'),             display => !$is_delivery_order, },
164     {  id => 'linetotal',     width => 10,    value => $locale->text('Extended'),             display => !$is_delivery_order, },
165     {  id => 'bin',           width => 10,    value => $locale->text('Bin'),                  display => 0, },
166     {  id => 'stock_in_out',  width => 10,    value => $stock_in_out_title,                   display => $is_delivery_order, },
167   );
168   my @column_index = map { $_->{id} } grep { $_->{display} } @HEADER;
169
170
171   # cache units
172   my $all_units       = AM->retrieve_units(\%myconfig, $form);
173
174   my %price_factors   = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
175
176   my $colspan = scalar @column_index;
177
178   $form->{invsubtotal} = 0;
179   map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
180
181   # about details
182   $myconfig{show_form_details} = 1                            unless (defined($myconfig{show_form_details}));
183   $form->{show_details}        = $myconfig{show_form_details} unless (defined($form->{show_details}));
184   # /about details
185
186   # translations, unused commented out
187 #  $runningnumber = $locale->text('No.');
188 #  my $deliverydate  = $locale->text('Delivery Date');
189   my $serialnumber  = $locale->text('Serial No.');
190   my $projectnumber = $locale->text('Project');
191 #  $partsgroup    = $locale->text('Group');
192   my $reqdate       = $locale->text('Reqdate');
193   my $deliverydate  = $locale->text('Required by');
194
195   # special alignings
196   my %align  = map { $_ => 'right' } qw(qty ship right sellprice_pg discount linetotal stock_in_out weight);
197   my %nowrap = map { $_ => 1 }       qw(description unit);
198
199   $form->{marge_total}           = 0;
200   $form->{sellprice_total}       = 0;
201   $form->{lastcost_total}        = 0;
202   $form->{totalweight}           = 0;
203   my %projectnumber_labels = ();
204   my @projectnumber_values = ("");
205
206   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
207     push(@projectnumber_values, $item->{"id"});
208     $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
209   }
210
211   _update_part_information();
212   _update_ship() if ($is_s_p_order);
213   _update_custom_variables();
214
215   my $totalweight = 0;
216
217   # rows
218
219   my @ROWS;
220   for my $i (1 .. $numrows) {
221     my %column_data = ();
222
223     # undo formatting
224     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
225       qw(qty discount sellprice lastcost price_new price_old)
226         unless ($form->{simple_save});
227
228 # unit begin
229     $form->{"unit_old_$i"}      ||= $form->{"unit_$i"};
230     $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
231
232     if (   !$all_units->{$form->{"selected_unit_$i"}}                                            # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
233         || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
234       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};                 # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
235     }
236     # adjust prices by unit, ignore if pricegroup changed
237     if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) {
238         $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
239         $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
240         $form->{"unit_old_$i"}   = $form->{"selected_unit_$i"};
241     }
242     my $this_unit = $form->{"unit_$i"};
243     $this_unit    = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
244
245     if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
246       my @values = ('', map { $_->{id}                      } @{ $form->{ALL_PRICE_FACTORS} });
247       my %labels =      map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
248
249       $column_data{price_factor} =
250         NTI($cgi->popup_menu('-name'    => "price_factor_id_$i",
251                              '-default' => $form->{"price_factor_id_$i"},
252                              '-values'  => \@values,
253                              '-labels'  => \%labels,
254                              '-style'   => 'width:90px'));
255     } else {
256       $column_data{price_factor} = '&nbsp;';
257     }
258     $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
259
260     $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
261 # / unit ending
262
263 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
264 #is shown for lastcost and sellprice.
265     my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
266     $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
267
268     my $price_factor   = $price_factors{$form->{"price_factor_id_$i"}} || 1;
269     my $discount       = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} *        $form->{"discount_$i"}  / 100 / $price_factor, 2);
270     my $linetotal      = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
271     my $rows            = $form->numtextrows($form->{"description_$i"}, 30, 6);
272
273     $column_data{runningnumber} = $cgi->textfield(-name => "runningnumber_$i", -size => 5,  -value => $i);    # HuT
274     $column_data{partnumber}    = $cgi->textfield(-name => "partnumber_$i",    -size => 12, -value => $form->{"partnumber_$i"});
275     $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
276                                 ? $cgi->textarea( -name => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
277                                 : $cgi->textfield(-name => "description_$i",   -size => 30, -value => $form->{"description_$i"}))
278                                 . $cgi->button(-value => $locale->text('L'), -onClick => "set_longdescription_window('longdescription_$i')");
279
280     my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
281
282     $column_data{qty}  = $cgi->textfield(-name => "qty_$i", -size => 5, -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
283     $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_window('qty_$i','alu_$i', 'formel_$i', $i)", -value => $locale->text('*/'))
284                        . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"}) . $cgi->hidden("-name" => "alu_$i", "-value" => $form->{"alu_$i"})
285       if $form->{"formel_$i"};
286
287     $column_data{ship} = '';
288     if ($form->{"id_$i"}) {
289       my $ship_qty        = $form->{"ship_$i"} * 1;
290       $ship_qty          *= $all_units->{$form->{"partunit_$i"}}->{factor};
291       $ship_qty          /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
292
293       $column_data{ship}  = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"};
294     }
295
296     # build in drop down list for pricesgroups
297     # $sellprice_value setzt den Wert etwas unabhängiger von der Darstellung.
298     # Hintergrund: Preisgruppen werden hier überprüft und neu berechnet.
299     # Vorher wurde der ganze cgi->textfield Block zweimal identisch eingebaut, dass passiert
300     # jetzt nach der Abfrage.
301     my $sellprice_value;
302     if ($form->{"prices_$i"}) {
303       $column_data{sellprice_pg} = qq|<select name="sellprice_pg_$i" style="width: 8em">$form->{"prices_$i"}</select>|;
304       $sellprice_value           =($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})
305                                       ? $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces)
306                                       : $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
307     } else {
308       # for last row and report
309       # set pricegroup drop down list from report menu
310       if ($form->{"sellprice_$i"} != 0) {
311         # remember the pricegroup_id in pricegroup_old
312         # but don't overwrite it
313         $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"};
314         my $default_option           = $form->{"sellprice_$i"}.'--'.$form->{"pricegroup_id_$i"};
315         $column_data{sellprice_pg}   = NTI($cgi->popup_menu("sellprice_pg_$i", [ $default_option ], $default_option, { $default_option => $form->{"pricegroup_$i"} || '' }));
316       } else {
317         $column_data{sellprice_pg} = qq|&nbsp;|;
318       }
319       $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
320
321     }
322     # Falls der Benutzer die Preise nicht anpassen sollte, wird das entsprechende
323     # Textfield auf readonly gesetzt. Anm. von Sven: Manipulation der Preise ist
324     # immer noch möglich, konsequenterweise sollten diese NUR aus der Datenbank
325     # geholt werden.
326     my $edit_prices = $main::auth->assert('edit_prices', 1);
327     $column_data{sellprice} = (!$edit_prices)
328                                 ? $cgi->textfield(-readonly => "readonly",
329                                                   -name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value)
330                                 : $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value);
331     $column_data{discount}    = (!$edit_prices)
332                                   ? $cgi->textfield(-readonly => "readonly",
333                                                     -name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}))
334                                   : $cgi->textfield(-name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"}));
335     $column_data{linetotal}   = $form->format_amount(\%myconfig, $linetotal, 2);
336     $column_data{bin}         = $form->{"bin_$i"};
337
338     $column_data{weight}      = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
339
340     if ($is_delivery_order) {
341       $column_data{stock_in_out} =  calculate_stock_in_out($i);
342     }
343
344     my @ROW1 = map { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} }, @column_index;
345
346     # second row
347     my @ROW2 = ();
348     push @ROW2, { value => qq|<b>$serialnumber</b> <input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">| }
349       if $form->{type} !~ /_quotation/;
350     push @ROW2, { value => qq|<b>$projectnumber</b> | . NTI($cgi->popup_menu('-name'  => "project_id_$i",        '-values'  => \@projectnumber_values,
351                                                                              '-labels' => \%projectnumber_labels, '-default' => $form->{"project_id_$i"})) };
352     push @ROW2, { value => qq|<b>$reqdate</b> <input name="reqdate_$i" size="11" onBlur="check_right_date_format(this)" value="$form->{"reqdate_$i"}">| }
353       if ($form->{type} =~ /order/ ||  $form->{type} =~ /invoice/);
354     push @ROW2, { value => sprintf qq|<b>%s</b>&nbsp;<input type="checkbox" name="subtotal_$i" value="1" %s>|,
355                    $locale->text('Subtotal'), $form->{"subtotal_$i"} ? 'checked' : '' };
356
357 # begin marge calculations
358     $form->{"lastcost_$i"}     *= 1;
359     $form->{"marge_percent_$i"} = 0;
360
361     my $marge_color;
362     my $real_sellprice;
363     if ( $form->{taxincluded} and $form->{"qty_$i"} * 1  and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
364       # if we use taxincluded we need to calculate the marge from the net_value
365       # all the marge calculations are based on linetotal which we need to
366       # convert to net first
367
368       # there is no direct form value for the tax_rate of the item, but
369       # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
370       # gives the tax percentage (e.g. 0.19)
371       $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
372     } else {
373       $real_sellprice            = $linetotal;
374     };
375     my $real_lastcost            = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
376     my $marge_percent_warn       = $myconfig{marge_percent_warn} * 1 || 15;
377     my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
378
379     if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
380       $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
381       $marge_color                = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
382     }
383
384     $form->{"marge_absolut_$i"}  = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
385     $form->{"marge_total"}      += $form->{"marge_absolut_$i"};
386     $form->{"lastcost_total"}   += $real_lastcost;
387     $form->{"sellprice_total"}  += $real_sellprice;
388
389     map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
390
391     push @ROW2, { value => sprintf qq|
392          <font %s><b>%s</b> %s &nbsp;%s%% </font>
393         &nbsp;<b>%s</b> %s
394         &nbsp;<b>%s</b> <input size="5" name="lastcost_$i" value="%s">|,
395                    $marge_color, $locale->text('Ertrag'),$form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"},
396                    $locale->text('LP'), $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2),
397                    $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces) }
398       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/ || $form->{type} =~ /^credit_note$/ ) && !$is_delivery_order;
399
400     $form->{"listprice_$i"} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2)
401       if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ ||  $form->{type} =~ /invoice/) ;
402 # / marge calculations ending
403
404 # Calculate total weight
405     $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
406
407 # calculate onhand
408     if ($form->{"id_$i"}) {
409       my $part         = IC->get_basic_part_info(id => $form->{"id_$i"});
410       my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
411       push @ROW2, { value => sprintf "<b>%s</b> <font %s>%s %s</font>",
412                       $locale->text('On Hand'),
413                       $onhand_color,
414                       $form->format_amount(\%myconfig, $part->{onhand}, 2),
415                       $part->{unit}
416       };
417     }
418 # / calculate onhand
419
420     my @hidden_vars;
421
422     if ($is_delivery_order) {
423       map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
424       push @hidden_vars, qw(sellprice discount not_discountable price_factor_id lastcost pricegroup_id);
425       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
426     }
427
428     my @HIDDENS = map { value => $_}, (
429           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
430           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
431           map { ($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
432             (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes
433                 income_accno expense_accno listprice assembly taxaccounts ordnumber transdate cusordnumber
434                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
435     );
436
437     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
438
439     $form->{invsubtotal} += $linetotal;
440
441     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
442     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
443
444     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, };
445   }
446
447   $form->{totalweight} = $totalweight;
448
449   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
450                                                        HEADER => \@HEADER,
451                                                      });
452
453   if (0 != ($form->{sellprice_total} * 1)) {
454     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
455   }
456
457   $main::lxdebug->leave_sub();
458 }
459
460 ##################################################
461 # build html-code for pricegroups in variable $form->{prices_$j}
462
463 sub set_pricegroup {
464   $main::lxdebug->enter_sub();
465
466   my $form     = $main::form;
467   my $locale   = $main::locale;
468   my $cgi      = $::request->{cgi};
469
470   _check_io_auth();
471
472   my $rowcount = shift;
473   for my $j (1 .. $rowcount) {
474     next unless $form->{PRICES}{$j};
475     # build drop down list for pricegroups
476     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
477     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} }
478                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
479
480     foreach my $item (@{ $form->{PRICES}{$j} }) {
481       # set new selectedpricegroup_id and prices for "Preis"
482       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
483       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
484       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
485     }
486   }
487   $main::lxdebug->leave_sub();
488 }
489
490 sub select_item {
491   $main::lxdebug->enter_sub();
492
493   my %params = @_;
494   my $mode   = $params{mode} || croak "Missing parameter 'mode'";
495
496   _check_io_auth();
497
498   my $previous_form = $::auth->save_form_in_session(form => $::form);
499   $::form->{title}  = $::locale->text('Select from one of the items below');
500   $::form->header;
501
502   my @item_list = map {
503     $_->{display_sellprice}  = $_->{sellprice} * (1 - $::form->{tradediscount});
504     $_->{display_sellprice} /= $_->{price_factor} if ($_->{price_factor});
505     $_;
506   } @{ $::form->{item_list} };
507
508   # delete action variable
509   delete @{$::form}{qw(action item_list)};
510
511   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
512                                                          MODE          => $mode,
513                                                          ITEM_LIST     => \@item_list,
514                                                          IS_PURCHASE   => $mode eq 'IS' });
515
516   $main::lxdebug->leave_sub();
517 }
518
519 sub item_selected {
520   $main::lxdebug->enter_sub();
521
522   my $form     = $main::form;
523   my %myconfig = %main::myconfig;
524
525   _check_io_auth();
526
527   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
528
529   my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
530   my $id   = delete($form->{select_item_id})   || croak 'Missing item selection ID';
531   my $i    = $form->{ $mode eq 'IC' ? 'assembly_rows' : 'rowcount' };
532
533   $form->{"id_${i}"} = $id;
534
535   if ($mode eq 'IS') {
536     IS->retrieve_item(\%myconfig, \%$form);
537   } elsif ($mode eq 'IR') {
538     IR->retrieve_item(\%myconfig, \%$form);
539   } elsif ($mode eq 'IC') {
540     IC->assembly_item(\%myconfig, \%$form);
541   } else {
542     croak "Invalid item selection mode '${mode}'";
543   }
544
545   my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
546
547   # if there was a price entered, override it
548   my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
549
550   my @new_fields =
551     qw(id partnumber description sellprice listprice inventory_accno
552        income_accno expense_accno bin unit weight assembly taxaccounts
553        partsgroup formel longdescription not_discountable partnotes lastcost
554        price_factor_id price_factor);
555
556   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
557   push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
558
559   map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
560
561   $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
562
563   if ($form->{"part_payment_id_$i"} ne "") {
564     $form->{payment_id} = $form->{"part_payment_id_$i"};
565   }
566
567   my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
568   $dec           = length $dec;
569   my $decimalplaces = ($dec > 2) ? $dec : 2;
570
571   if ($sellprice) {
572     $form->{"sellprice_$i"} = $sellprice;
573   } else {
574
575     # if there is an exchange rate adjust sellprice
576     if (($form->{exchangerate} * 1) != 0) {
577       $form->{"sellprice_$i"} /= $form->{exchangerate};
578       $form->{"sellprice_$i"} =
579         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
580     }
581
582     # tradediscount
583     if ($::form->{tradediscount}) {
584       $::form->{"sellprice_$i"} *= 1 - $::form->{tradediscount};
585     }
586   }
587
588   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
589     qw(sellprice listprice weight);
590
591   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
592
593   if ($form->{"not_discountable_$i"}) {
594     $form->{"discount_$i"} = 0;
595   }
596
597   my $amount =
598     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
599     $form->{"qty_$i"};
600   map { $form->{"${_}_base"} += $amount }
601     (split / /, $form->{"taxaccounts_$i"});
602   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
603     $form->{"taxaccounts_$i"}
604     if !$form->{taxincluded};
605
606   $form->{creditremaining} -= $amount;
607
608   $form->{"runningnumber_$i"} = $i;
609
610   delete $form->{nextsub};
611
612   # format amounts
613   map {
614     $form->{"${_}_$i"} =
615       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
616   } qw(sellprice listprice lastcost) if $form->{item} ne 'assembly';
617
618   # get pricegroups for parts
619   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
620
621   # build up html code for prices_$i
622   set_pricegroup($form->{rowcount});
623
624   &display_form;
625
626   $main::lxdebug->leave_sub();
627 }
628
629 sub new_item {
630   $main::lxdebug->enter_sub();
631
632   my $form     = $main::form;
633   my %myconfig = %main::myconfig;
634
635   _check_io_auth();
636
637   my $price_key = ($form->{type} =~ m/request_quotation|purchase_order/) || ($form->{script} eq 'ir.pl') ? 'lastcost' : 'sellprice';
638
639   # change callback
640   $form->{old_callback} = $form->escape($form->{callback}, 1);
641   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
642
643   # save all form variables except action in the session and keep the key in the previousform variable
644   my $previousform = $::auth->save_form_in_session(skip_keys => [ qw(action) ]);
645
646   my @HIDDENS;
647   push @HIDDENS,      { 'name' => 'previousform', 'value' => $previousform };
648   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc);
649   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit);
650   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
651   push @HIDDENS,      { 'name' => $price_key,     'value' => $form->parse_amount(\%myconfig, $form->{"sellprice_$form->{rowcount}"}) };
652   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{"longdescription_$form->{rowcount}"} };
653
654   $form->header();
655   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
656
657   $main::lxdebug->leave_sub();
658 }
659
660 sub check_form {
661   $main::lxdebug->enter_sub();
662
663   my $form     = $main::form;
664   my %myconfig = %main::myconfig;
665
666   _check_io_auth();
667
668   my @a     = ();
669   my $count = 0;
670
671   # remove any makes or model rows
672   if ($form->{item} eq 'part') {
673     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
674       qw(listprice sellprice lastcost weight rop);
675
676   } elsif ($form->{item} eq 'assembly') {
677
678     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
679     #$form->{sellprice} = 0;
680     $form->{weight}    = 0;
681     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
682       qw(listprice sellprice rop stock);
683
684     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
685
686     for my $i (1 .. ($form->{assembly_rows} - 1)) {
687       if ($form->{"qty_$i"}) {
688         push @a, {};
689         my $j = $#a;
690
691         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
692
693         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
694
695         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
696
697         # fuer assemblies auskommentiert. siehe oben
698         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
699         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
700         $count++;
701       }
702     }
703     # kann das hier auch weg? s.o. jb
704     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
705
706     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
707     $form->{assembly_rows} = $count;
708
709   } elsif ($form->{item} eq 'service') {
710     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(listprice sellprice lastcost);
711
712   } else {
713     remove_emptied_rows(1);
714
715     $form->{creditremaining} -= &invoicetotal;
716   }
717
718   #sk
719   # if pricegroups
720   if (   $form->{type} =~ (/sales_quotation/)
721       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
722       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
723       or ($form->{type} =~ /sales_order/)) {
724
725     # get pricegroups for parts
726     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
727
728     # build up html code for prices_$i
729     set_pricegroup($form->{rowcount});
730
731   }
732
733   &display_form;
734
735   $main::lxdebug->leave_sub();
736 }
737
738 sub remove_emptied_rows {
739   my $dont_add_empty = shift;
740   my $form           = $::form;
741
742   return unless $form->{rowcount};
743
744   my @flds = qw(id partnumber description qty ship sellprice unit
745                 discount inventory_accno income_accno expense_accno listprice
746                 taxaccounts bin assembly weight projectnumber project_id
747                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
748                 not_discountable shop ve gv buchungsgruppen_id language_values
749                 sellprice_pg pricegroup_old price_old price_new unit_old ordnumber
750                 transdate longdescription basefactor marge_total marge_percent
751                 marge_price_factor lastcost price_factor_id partnotes
752                 stock_out stock_in has_sernumber reqdate);
753
754   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
755   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
756
757   my @new_rows;
758   for my $i (1 .. $form->{rowcount} - 1) {
759     next unless $form->{"partnumber_$i"};
760
761     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
762   }
763
764   my $new_rowcount = scalar @new_rows;
765   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
766   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
767 }
768
769 sub invoicetotal {
770   $main::lxdebug->enter_sub();
771
772   my $form     = $main::form;
773   my %myconfig = %main::myconfig;
774
775   _check_io_auth();
776
777   $form->{oldinvtotal} = 0;
778
779   # add all parts and deduct paid
780   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
781
782   my ($amount, $sellprice, $discount, $qty);
783
784   for my $i (1 .. $form->{rowcount}) {
785     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
786     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
787     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
788
789     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
790
791     $amount = $sellprice * (1 - $discount / 100) * $qty;
792     map { $form->{"${_}_base"} += $amount }
793       (split (/ /, $form->{"taxaccounts_$i"}));
794     $form->{oldinvtotal} += $amount;
795   }
796
797   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
798     split(/ /, $form->{taxaccounts})
799     if !$form->{taxincluded};
800
801   $form->{oldtotalpaid} = 0;
802   for my $i (1 .. $form->{paidaccounts}) {
803     $form->{oldtotalpaid} += $form->{"paid_$i"};
804   }
805
806   $main::lxdebug->leave_sub();
807
808   # return total
809   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
810 }
811
812 sub validate_items {
813   $main::lxdebug->enter_sub();
814
815   my $form     = $main::form;
816   my $locale   = $main::locale;
817
818   _check_io_auth();
819
820   # check if items are valid
821   if ($form->{rowcount} == 1) {
822     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
823     &update;
824     ::end_of_request();
825   }
826
827   for my $i (1 .. $form->{rowcount} - 1) {
828     $form->isblank("partnumber_$i",
829                    $locale->text('Number missing in Row') . " $i");
830   }
831
832   $main::lxdebug->leave_sub();
833 }
834
835 sub order {
836   $main::lxdebug->enter_sub();
837
838   my $form     = $main::form;
839   my %myconfig = %main::myconfig;
840   my $locale   = $main::locale;
841
842   _check_io_auth();
843
844   if ($form->{second_run}) {
845     $form->{print_and_post} = 0;
846   }
847   $form->{ordnumber} = $form->{invnumber};
848
849   $form->{old_employee_id} = $form->{employee_id};
850   $form->{old_salesman_id} = $form->{salesman_id};
851
852   map { delete $form->{$_} } qw(id printed emailed queued);
853   my $buysell;
854   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
855     $form->{title} = $locale->text('Add Purchase Order');
856     $form->{vc}    = 'vendor';
857     $form->{type}  = 'purchase_order';
858     $buysell       = 'sell';
859   }
860   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
861     $form->{title} = $locale->text('Add Sales Order');
862     $form->{vc}    = 'customer';
863     $form->{type}  = 'sales_order';
864     $buysell       = 'buy';
865   }
866   $form->{script} = 'oe.pl';
867
868   $form->{shipto} = 1;
869
870   $form->{rowcount}--;
871
872   $form->{cp_id} *= 1;
873
874   require "bin/mozilla/$form->{script}";
875   my $script = $form->{"script"};
876   $script =~ s|.*/||;
877   $script =~ s|.pl$||;
878   $locale = new Locale($::lx_office_conf{system}->{language}, $script);
879
880   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
881
882   my $currency = $form->{currency};
883
884   &order_links;
885
886   $form->{currency}     = $currency;
887   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
888   $form->{exchangerate} = $form->{forex} || '';
889
890   for my $i (1 .. $form->{rowcount}) {
891     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
892             if ($form->{"${_}_${i}"}) }
893         qw(ship qty sellprice listprice basefactor discount));
894   }
895
896   &prepare_order;
897   &display_form;
898
899   $main::lxdebug->leave_sub();
900 }
901
902 sub quotation {
903   $main::lxdebug->enter_sub();
904
905   my $form     = $main::form;
906   my %myconfig = %main::myconfig;
907   my $locale   = $main::locale;
908
909   _check_io_auth();
910
911   if ($form->{second_run}) {
912     $form->{print_and_post} = 0;
913   }
914   map { delete $form->{$_} } qw(id printed emailed queued);
915
916   my $buysell;
917   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
918     $form->{title} = $locale->text('Add Request for Quotation');
919     $form->{vc}    = 'vendor';
920     $form->{type}  = 'request_quotation';
921     $buysell       = 'sell';
922   }
923   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
924     $form->{title} = $locale->text('Add Quotation');
925     $form->{vc}    = 'customer';
926     $form->{type}  = 'sales_quotation';
927     $buysell       = 'buy';
928   }
929
930   $form->{cp_id} *= 1;
931
932   $form->{script} = 'oe.pl';
933
934   $form->{shipto} = 1;
935
936   $form->{rowcount}--;
937
938   require "bin/mozilla/$form->{script}";
939
940   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
941
942   my $currency = $form->{currency};
943
944   &order_links;
945
946   $form->{currency}     = $currency;
947   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
948   $form->{exchangerate} = $form->{forex} || '';
949
950   for my $i (1 .. $form->{rowcount}) {
951     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
952                                                      $form->{"${_}_${i}"})
953             if ($form->{"${_}_${i}"}) }
954         qw(ship qty sellprice listprice basefactor discount));
955   }
956
957   &prepare_order;
958   &display_form;
959
960   $main::lxdebug->leave_sub();
961 }
962
963 sub request_for_quotation {
964   quotation();
965 }
966
967 sub edit_e_mail {
968   $main::lxdebug->enter_sub();
969
970   my $form     = $main::form;
971   my %myconfig = %main::myconfig;
972   my $locale   = $main::locale;
973
974   _check_io_auth();
975
976   if ($form->{second_run}) {
977     $form->{print_and_post} = 0;
978     $form->{resubmit}       = 0;
979   }
980
981   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
982
983   if ($form->{"cp_id"}) {
984     CT->get_contact(\%myconfig, $form);
985     $form->{"email"} = $form->{"cp_email"} if $form->{"cp_email"};
986   }
987
988   $form->{language} = $form->get_template_language(\%myconfig);
989   $form->{language} = "_" . $form->{language} if $form->{language};
990
991   my $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
992
993   $form->{oldmedia} = $form->{media};
994   $form->{media}    = "email";
995
996   my $attachment_filename = $form->generate_attachment_filename();
997   my $subject             = $form->{subject} || $form->generate_email_subject();
998
999   $form->header;
1000
1001   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
1002   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override login password);
1003   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
1004   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
1005
1006   print $form->parse_html_template('generic/edit_email',
1007                                    { title         => $title,
1008                                      a_filename    => $attachment_filename,
1009                                      subject       => $subject,
1010                                      print_options => print_options('inline' => 1),
1011                                      HIDDEN        => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
1012                                      SHOW_BCC      => $::auth->assert('email_bcc', 'may fail') });
1013
1014   $main::lxdebug->leave_sub();
1015 }
1016
1017 sub send_email {
1018   $main::lxdebug->enter_sub();
1019
1020   my $form     = $main::form;
1021   my %myconfig = %main::myconfig;
1022
1023   _check_io_auth();
1024
1025   my $callback = $form->{script} . "?action=edit";
1026   map({ $callback .= "\&${_}=" . E($form->{$_}); } qw(type id));
1027
1028   print_form("return");
1029
1030   Common->save_email_status(\%myconfig, $form);
1031
1032   $form->{callback} = $callback;
1033   $form->redirect();
1034
1035   $main::lxdebug->leave_sub();
1036 }
1037
1038 # generate the printing options displayed at the bottom of oe and is forms.
1039 # this function will attempt to guess what type of form is displayed, and will generate according options
1040 #
1041 # about the coding:
1042 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
1043 # the opthash function builds hashrefs which are then pieced together for the template arrays.
1044 # unneeded options are "undef"ed out, and then grepped out.
1045 #
1046 # the inline options is untested, but intended to be used later in metatemplating
1047 sub print_options {
1048   $main::lxdebug->enter_sub();
1049
1050   my $form     = $main::form;
1051   my %myconfig = %main::myconfig;
1052   my $locale   = $main::locale;
1053
1054   _check_io_auth();
1055
1056   my %options = @_;
1057
1058   # names 3 parameters and returns a hashref, for use in templates
1059   sub opthash { +{ value => shift, selected => shift, oname => shift } }
1060   my (@FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
1061
1062   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
1063   $form->{sendmode}   = "attachment";
1064   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
1065   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
1066   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
1067   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
1068                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
1069
1070   $form->{PD}{ $form->{formname} } = "selected";
1071   $form->{DF}{ $form->{format} }   = "selected";
1072   $form->{OP}{ $form->{media} }    = "selected";
1073   $form->{SM}{ $form->{formname} } = "selected";
1074
1075   push @FORMNAME, grep $_,
1076     ($form->{type} eq 'purchase_order') ? (
1077       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
1078       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List'))
1079     ) : undef,
1080     ($form->{type} eq 'credit_note') ?
1081       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
1082     ($form->{type} eq 'sales_order') ? (
1083       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
1084       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
1085     ) : undef,
1086     ($form->{type} =~ /sales_quotation$/) ?
1087       opthash('sales_quotation',     $form->{PD}{sales_quotation},     $locale->text('Quotation')) : undef,
1088     ($form->{type} =~ /request_quotation$/) ?
1089       opthash('request_quotation',   $form->{PD}{request_quotation},   $locale->text('Request for Quotation')) : undef,
1090     ($form->{type} eq 'invoice') ? (
1091       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
1092       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
1093     ) : undef,
1094     ($form->{type} eq 'invoice' && $form->{storno}) ? (
1095       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
1096     ) : undef,
1097     ($form->{type} =~ /_delivery_order$/) ? (
1098       opthash($form->{type},         $form->{PD}{$form->{type}},       $locale->text('Delivery Order')),
1099       opthash('pick_list',           $form->{PD}{pick_list},           $locale->text('Pick List')),
1100     ) : undef;
1101
1102   push @SENDMODE,
1103     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
1104     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
1105       if ($form->{media} eq 'email');
1106
1107   my $printable_templates = any { $::lx_office_conf{print_templates}->{$_} } qw(latex opendocument);
1108   push @MEDIA, grep $_,
1109       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
1110     ($printable_templates && $form->{printers} && scalar @{ $form->{printers} }) ?
1111       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
1112     ($printable_templates && !$options{no_queue}) ?
1113       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
1114         if ($form->{media} ne 'email');
1115
1116   push @FORMAT, grep $_,
1117     ($::lx_office_conf{print_templates}->{opendocument} &&     $::lx_office_conf{applications}->{openofficeorg_writer}  &&     $::lx_office_conf{applications}->{xvfb}
1118                                                         && (-x $::lx_office_conf{applications}->{openofficeorg_writer}) && (-x $::lx_office_conf{applications}->{xvfb})
1119      && !$options{no_opendocument_pdf}) ?
1120       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
1121     ($::lx_office_conf{print_templates}->{latex}) ?
1122       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
1123     ($::lx_office_conf{print_templates}->{latex} && !$options{no_postscript}) ?
1124       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
1125     (!$options{no_html}) ?
1126       opthash("html", $form->{DF}{html}, "HTML") : undef,
1127     ($::lx_office_conf{print_templates}->{opendocument} && !$options{no_opendocument}) ?
1128       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef,
1129     ($::lx_office_conf{print_templates}->{excel} && !$options{no_excel}) ?
1130       opthash("excel",               $form->{DF}{excel},               $locale->text("Excel")) : undef;
1131
1132   push @LANGUAGE_ID,
1133     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
1134       if (ref $form->{languages} eq 'ARRAY');
1135
1136   push @PRINTER_ID,
1137     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
1138       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
1139
1140   @SELECTS = map {
1141     sname => $_->[1],
1142     DATA  => $_->[0],
1143     show  => !$options{"hide_" . $_->[1]} && scalar @{ $_->[0] }
1144   },
1145   [ \@FORMNAME,    'formname',    ],
1146   [ \@LANGUAGE_ID, 'language_id', ],
1147   [ \@FORMAT,      'format',      ],
1148   [ \@SENDMODE,    'sendmode',    ],
1149   [ \@MEDIA,       'media',       ],
1150   [ \@PRINTER_ID,  'printer_id',  ];
1151
1152   my %dont_display_groupitems = (
1153     'dunning' => 1,
1154     );
1155
1156   my %template_vars = (
1157     display_copies       => scalar @{ $form->{printers} || [] } && $::lx_office_conf{print_templates}->{latex} && $form->{media} ne 'email',
1158     display_remove_draft => (!$form->{id} && $form->{draft_id}),
1159     display_groupitems   => !$dont_display_groupitems{$form->{type}},
1160     groupitems_checked   => $form->{groupitems} ? "checked" : '',
1161     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
1162   );
1163
1164   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
1165
1166   if ($options{inline}) {
1167     $main::lxdebug->leave_sub();
1168     return $print_options;
1169   }
1170
1171   print $print_options;
1172
1173   $main::lxdebug->leave_sub();
1174 }
1175
1176 sub print {
1177   $main::lxdebug->enter_sub();
1178
1179   my $form     = $main::form;
1180   my $locale   = $main::locale;
1181
1182   _check_io_auth();
1183
1184   if ($form->{print_nextsub}) {
1185     call_sub($form->{print_nextsub});
1186     $main::lxdebug->leave_sub();
1187     return;
1188   }
1189
1190   # if this goes to the printer pass through
1191   my $old_form;
1192   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1193     $form->error($locale->text('Select postscript or PDF!'))
1194       if ($form->{format} !~ /(postscript|pdf)/);
1195
1196     $old_form = new Form;
1197     map { $old_form->{$_} = $form->{$_} } keys %$form;
1198   }
1199
1200   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1201     if ($form->{formname} eq "proforma") {
1202       $form->{proforma} = 1;
1203     }
1204     $form->{print_and_save} = 1;
1205     my $formname = $form->{formname};
1206     &save();
1207     $form->{formname} = $formname;
1208     &edit();
1209     $::lxdebug->leave_sub();
1210     ::end_of_request();
1211   }
1212
1213   &print_form($old_form);
1214
1215   $main::lxdebug->leave_sub();
1216 }
1217
1218 sub print_form {
1219   $main::lxdebug->enter_sub();
1220
1221   my $form     = $main::form;
1222   my %myconfig = %main::myconfig;
1223   my $locale   = $main::locale;
1224
1225   _check_io_auth();
1226
1227   my $defaults = SL::DB::Default->get;
1228   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
1229   $form->{templates} = $defaults->templates;
1230
1231   my ($old_form) = @_;
1232
1233   my $inv       = "inv";
1234   my $due       = "due";
1235   my $numberfld = "invnumber";
1236   my $order;
1237
1238   my $display_form =
1239     ($form->{display_form}) ? $form->{display_form} : "display_form";
1240
1241   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1242   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1243
1244   if ($form->{formname} eq "invoice") {
1245     $form->{label} = $locale->text('Invoice');
1246   }
1247   if ($form->{formname} eq 'sales_order') {
1248     $inv                  = "ord";
1249     $due                  = "req";
1250     $form->{"${inv}date"} = $form->{transdate};
1251     $form->{label}        = $locale->text('Confirmation');
1252     $numberfld            = "sonumber";
1253     $order                = 1;
1254   }
1255
1256   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1257     $inv                  = "inv";
1258     $due                  = "due";
1259     $form->{"${inv}date"} = $form->{invdate};
1260     $form->{label}        = $locale->text('Proforma Invoice');
1261     $numberfld            = "sonumber";
1262     $order                = 0;
1263   }
1264
1265   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1266     $inv                  = "inv";
1267     $due                  = "due";
1268     $form->{"${inv}date"} = $form->{transdate};
1269     $form->{"invdate"}    = $form->{transdate};
1270     $form->{invnumber}    = $form->{ordnumber};
1271     $form->{label}        = $locale->text('Proforma Invoice');
1272     $numberfld            = "sonumber";
1273     $order                = 1;
1274   }
1275
1276   if ($form->{formname} eq 'purchase_order') {
1277     $inv                  = "ord";
1278     $due                  = "req";
1279     $form->{"${inv}date"} = $form->{transdate};
1280     $form->{label}        = $locale->text('Purchase Order');
1281     $numberfld            = "ponumber";
1282     $order                = 1;
1283   }
1284   if ($form->{formname} eq 'bin_list') {
1285     $inv                  = "ord";
1286     $due                  = "req";
1287     $form->{"${inv}date"} = $form->{transdate};
1288     $form->{label}        = $locale->text('Bin List');
1289     $order                = 1;
1290   }
1291   if ($form->{formname} eq 'sales_quotation') {
1292     $inv                  = "quo";
1293     $due                  = "req";
1294     $form->{"${inv}date"} = $form->{transdate};
1295     $form->{label}        = $locale->text('Quotation');
1296     $numberfld            = "sqnumber";
1297     $order                = 1;
1298   }
1299
1300   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1301     $inv                  = "quo";
1302     $due                  = "req";
1303     $form->{"${inv}date"} = $form->{transdate};
1304     $form->{"invdate"}    = $form->{transdate};
1305     $form->{label}        = $locale->text('Proforma Invoice');
1306     $numberfld            = "sqnumber";
1307     $order                = 1;
1308   }
1309
1310   if ($form->{formname} eq 'request_quotation') {
1311     $inv                  = "quo";
1312     $due                  = "req";
1313     $form->{"${inv}date"} = $form->{transdate};
1314     $form->{label}        = $locale->text('RFQ');
1315     $numberfld            = "rfqnumber";
1316     $order                = 1;
1317   }
1318
1319   if ($form->{type} =~ /_delivery_order$/) {
1320     undef $due;
1321     $inv                  = "do";
1322     $form->{"${inv}date"} = $form->{transdate};
1323     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1324     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1325   }
1326
1327   $form->isblank("email", $locale->text('E-mail address missing!'))
1328     if ($form->{media} eq 'email');
1329   $form->isblank("${inv}date",
1330            $locale->text($form->{label})
1331            . ": "
1332            . $locale->text(' Date missing!'));
1333
1334   # $locale->text('Invoice Number missing!')
1335   # $locale->text('Invoice Date missing!')
1336   # $locale->text('Order Number missing!')
1337   # $locale->text('Order Date missing!')
1338   # $locale->text('Quotation Number missing!')
1339   # $locale->text('Quotation Date missing!')
1340
1341   # assign number
1342   $form->{what_done} = $form->{formname};
1343   if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) {
1344     $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld);
1345     if ($form->{media} ne 'email') {
1346
1347       # get pricegroups for parts
1348       IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1349
1350       # build up html code for prices_$i
1351       set_pricegroup($form->{rowcount});
1352
1353       $form->{rowcount}--;
1354
1355       call_sub($display_form);
1356       # saving the history
1357       if(!exists $form->{addition}) {
1358         $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1359         $form->{addition} = "PRINTED";
1360         $form->save_history;
1361       }
1362       # /saving the history
1363       ::end_of_request();
1364     }
1365   }
1366
1367   &validate_items;
1368
1369   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1370   my ($saved_email, $saved_cc, $saved_bcc) =
1371     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1372
1373   my $language_saved = $form->{language_id};
1374   my $payment_id_saved = $form->{payment_id};
1375   my $salesman_id_saved = $form->{salesman_id};
1376   my $cp_id_saved = $form->{cp_id};
1377   my $taxzone_id_saved = $form->{taxzone_id};
1378   my $currency_saved = $form->{currency};
1379
1380   call_sub("$form->{vc}_details") if ($form->{vc});
1381
1382   $form->{language_id} = $language_saved;
1383   $form->{payment_id} = $payment_id_saved;
1384   $form->{taxzone_id} = $taxzone_id_saved;
1385   $form->{currency} = $currency_saved;
1386
1387   $form->{"email"} = $saved_email if ($saved_email);
1388   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1389   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1390
1391   if (!$cp_id_saved) {
1392     # No contact was selected. Delete all contact variables because
1393     # IS->customer_details() and IR->vendor_details() get the default
1394     # contact anyway.
1395     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1396   }
1397
1398   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1399   if ($form->{"language_id"}) {
1400     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1401       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1402   } else {
1403     $output_dateformat = $myconfig{"dateformat"};
1404     $output_numberformat = $myconfig{"numberformat"};
1405     $output_longdates = 1;
1406   }
1407
1408   # Store the output number format so that the template modules know
1409   # how to parse the amounts back if requested.
1410   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
1411
1412   ($form->{employee}) = split /--/, $form->{employee};
1413
1414   # create the form variables
1415   if ($form->{type} =~ /_delivery_order$/) {
1416     DO->order_details(\%myconfig, \%$form);
1417   } elsif ($order) {
1418     OE->order_details(\%myconfig, \%$form);
1419   } else {
1420     IS->invoice_details(\%myconfig, \%$form, $locale);
1421   }
1422
1423   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
1424   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
1425
1426   if ($form->{shipto_id}) {
1427     $form->get_shipto(\%myconfig);
1428   }
1429
1430   my @a = qw(name department_1 department_2 street zipcode city country contact phone fax email);
1431
1432   my $shipto = 1;
1433
1434   # if there is no shipto fill it in from billto
1435   foreach my $item (@a) {
1436     if ($form->{"shipto$item"}) {
1437       $shipto = 0;
1438       last;
1439     }
1440   }
1441
1442   if ($shipto) {
1443     if (   $form->{formname} eq 'purchase_order'
1444         || $form->{formname} eq 'request_quotation') {
1445       $form->{shiptoname}   = $defaults->company;
1446       $form->{shiptostreet} = $defaults->address;
1447     } else {
1448       map { $form->{"shipto$_"} = $form->{$_} } @a;
1449     }
1450   }
1451
1452   $form->{notes} =~ s/^\s+//g;
1453
1454   delete $form->{printer_command};
1455
1456   $form->{language} = $form->get_template_language(\%myconfig);
1457
1458   my $printer_code;
1459   if ($form->{media} ne 'email') {
1460     $printer_code = $form->get_printer_code(\%myconfig);
1461     if ($printer_code ne "") {
1462       $printer_code = "_" . $printer_code;
1463     }
1464   }
1465
1466   if ($form->{language} ne "") {
1467     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
1468     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
1469
1470     $form->{language} = "_" . $form->{language};
1471   }
1472
1473   # Format dates.
1474   format_dates($output_dateformat, $output_longdates,
1475                qw(invdate orddate quodate pldate duedate reqdate transdate
1476                   shippingdate deliverydate validitydate paymentdate
1477                   datepaid transdate_oe deliverydate_oe dodate
1478                   employee_startdate employee_enddate
1479                   ),
1480                grep({ /^datepaid_\d+$/ ||
1481                         /^transdate_oe_\d+$/ ||
1482                         /^deliverydate_oe_\d+$/ ||
1483                         /^reqdate_\d+$/ ||
1484                         /^deliverydate_\d+$/ ||
1485                         /^transdate_\d+$/
1486                     } keys(%{$form})));
1487
1488   reformat_numbers($output_numberformat, 2,
1489                    qw(invtotal ordtotal quototal subtotal linetotal
1490                       listprice sellprice netprice discount
1491                       tax taxbase total paid payment),
1492                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
1493
1494   reformat_numbers($output_numberformat, undef,
1495                    qw(qty price_factor),
1496                    grep({ /^qty_\d+$/
1497                         } keys(%{$form})));
1498
1499   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1500
1501   if (scalar @{ $cvar_date_fields }) {
1502     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1503   }
1504
1505   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1506     reformat_numbers($output_numberformat, $precision, @{ $field_list });
1507   }
1508
1509   my $extension = 'html';
1510   if ($form->{format} eq 'postscript') {
1511     $form->{postscript}   = 1;
1512     $extension            = 'tex';
1513
1514   } elsif ($form->{"format"} =~ /pdf/) {
1515     $form->{pdf}          = 1;
1516     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
1517
1518   } elsif ($form->{"format"} =~ /opendocument/) {
1519     $form->{opendocument} = 1;
1520     $extension            = 'odt';
1521   } elsif ($form->{"format"} =~ /excel/) {
1522     $form->{excel} = 1;
1523     $extension            = 'xls';
1524   }
1525
1526   # search for the template
1527   my @template_files;
1528   push @template_files, "$form->{formname}_email$form->{language}$printer_code.$extension" if $form->{media} eq 'email';
1529   push @template_files, "$form->{formname}$form->{language}$printer_code.$extension";
1530   push @template_files, "$form->{formname}.$extension";
1531   push @template_files, "default.$extension";
1532   @template_files = uniq @template_files;
1533   $form->{IN}     = first { -f ($defaults->templates . "/$_") } @template_files;
1534
1535   if (!defined $form->{IN}) {
1536     $::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));
1537   }
1538
1539   delete $form->{OUT};
1540
1541   if ($form->{media} eq 'printer') {
1542     $form->{OUT}      = $form->{printer_command};
1543     $form->{OUT_MODE} = '|-';
1544     $form->{printed} .= " $form->{formname}";
1545     $form->{printed}  =~ s/^ //;
1546   }
1547   my $printed = $form->{printed};
1548
1549   if ($form->{media} eq 'email') {
1550     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1551       unless $form->{subject};
1552
1553     $form->{emailed} .= " $form->{formname}";
1554     $form->{emailed} =~ s/^ //;
1555   }
1556   my $emailed = $form->{emailed};
1557
1558   if ($form->{media} eq 'queue') {
1559     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
1560
1561     my $filename;
1562     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
1563     if ($filename = $queued{ $form->{formname} }) {
1564       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
1565       delete $queued{ $form->{formname} };
1566
1567       $form->{queued}    =  join ' ', %queued;
1568       $filename          =~ s/\..*$//g;
1569       $filename         .=  $suffix;
1570       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
1571       $form->{OUT_MODE}  =  '>';
1572
1573     } else {
1574       my $temp_fh;
1575       ($temp_fh, $filename) = File::Temp::tempfile(
1576         'kivitendo-spoolXXXXXX',
1577         SUFFIX => "$suffix",
1578         DIR    => $::lx_office_conf{paths}->{spool},
1579         UNLINK => 0,
1580       );
1581       close $temp_fh;
1582       $form->{OUT} = "$filename";
1583       # use >> for OUT_MODE because file is already created by File::Temp
1584       $form->{OUT_MODE} = '>>';
1585       # strip directory so that only filename is stored in table status
1586       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
1587     }
1588
1589     # add type
1590     $form->{queued} .= " $form->{formname} $filename";
1591     $form->{queued} =~ s/^ //;
1592   }
1593   my $queued = $form->{queued};
1594
1595 # saving the history
1596   if(!exists $form->{addition}) {
1597     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1598     if($form->{media} =~ /printer/) {
1599       $form->{addition} = "PRINTED";
1600     }
1601     elsif($form->{media} =~ /email/) {
1602       $form->{addition} = "MAILED";
1603     }
1604     elsif($form->{media} =~ /queue/) {
1605       $form->{addition} = "QUEUED";
1606     }
1607     elsif($form->{media} =~ /screen/) {
1608       $form->{addition} = "SCREENED";
1609     }
1610     $form->save_history;
1611   }
1612   # /saving the history
1613
1614   # prepare meta information for template introspection
1615   $form->{template_meta} = {
1616     formname  => $form->{formname},
1617     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
1618     format    => $form->{format},
1619     media     => $form->{media},
1620     extension => $extension,
1621     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
1622     today     => DateTime->today,
1623   };
1624
1625   $form->parse_template(\%myconfig);
1626
1627   $form->{callback} = "";
1628
1629   if ($form->{media} eq 'email') {
1630     $form->{message} = $locale->text('sent') unless $form->{message};
1631   }
1632   my $message = $form->{message};
1633
1634   # if we got back here restore the previous form
1635   if ($form->{media} =~ /(printer|email|queue)/) {
1636
1637     $form->update_status(\%myconfig)
1638       if ($form->{media} eq 'queue' && $form->{id});
1639
1640     return $main::lxdebug->leave_sub() if ($old_form eq "return");
1641
1642     if ($old_form) {
1643
1644       $old_form->{"${inv}number"} = $form->{"${inv}number"};
1645
1646       # restore and display form
1647       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1648
1649       $form->{queued}  = $queued;
1650       $form->{printed} = $printed;
1651       $form->{emailed} = $emailed;
1652       $form->{message} = $message;
1653
1654       $form->{rowcount}--;
1655       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1656         qw(exchangerate creditlimit creditremaining);
1657
1658       for my $i (1 .. $form->{paidaccounts}) {
1659         map {
1660           $form->{"${_}_$i"} =
1661             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1662         } qw(paid exchangerate);
1663       }
1664
1665       call_sub($display_form);
1666       ::end_of_request();
1667     }
1668
1669     my $msg =
1670       ($form->{media} eq 'printer')
1671       ? $locale->text('sent to printer')
1672       : $locale->text('emailed to') . " $form->{email}";
1673     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1674   }
1675   if ($form->{printing}) {
1676    call_sub($display_form);
1677    ::end_of_request();
1678   }
1679
1680   $main::lxdebug->leave_sub();
1681 }
1682
1683 sub customer_details {
1684   $main::lxdebug->enter_sub();
1685
1686   my $form     = $main::form;
1687   my %myconfig = %main::myconfig;
1688
1689   IS->customer_details(\%myconfig, \%$form, @_);
1690
1691   $main::lxdebug->leave_sub();
1692 }
1693
1694 sub vendor_details {
1695   $main::lxdebug->enter_sub();
1696
1697   my $form     = $main::form;
1698   my %myconfig = %main::myconfig;
1699
1700   IR->vendor_details(\%myconfig, \%$form, @_);
1701
1702   $main::lxdebug->leave_sub();
1703 }
1704
1705 sub post_as_new {
1706   $main::lxdebug->enter_sub();
1707
1708   my $form     = $main::form;
1709
1710   _check_io_auth();
1711
1712   $form->{postasnew} = 1;
1713   map { delete $form->{$_} } qw(printed emailed queued);
1714
1715   &post;
1716
1717   $main::lxdebug->leave_sub();
1718 }
1719
1720 sub ship_to {
1721   $main::lxdebug->enter_sub();
1722
1723   _check_io_auth();
1724
1725   $::form->{print_and_post} = 0 if $::form->{second_run};
1726
1727   map { $::form->{$_} = $::form->parse_amount(\%::myconfig, $::form->{$_}) } qw(exchangerate creditlimit creditremaining);
1728
1729   # get details for customer/vendor
1730   call_sub($::form->{vc} . "_details", qw(name department_1 department_2 street zipcode city country contact email phone fax), $::form->{vc} . "number");
1731
1732   # get pricegroups for parts
1733   IS->get_pricegroups_for_parts(\%::myconfig, \%$::form);
1734
1735   # build up html code for prices_$i
1736   set_pricegroup($::form->{rowcount});
1737
1738   $::form->{rowcount}--;
1739
1740   my @shipto_vars   = qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
1741                          shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail
1742                          shiptodepartment_1 shiptodepartment_2);
1743   my $previous_form = $::auth->save_form_in_session(skip_keys => [ @shipto_vars, qw(header shipto_id) ]);
1744   $::form->{title}  = $::locale->text('Ship to');
1745   $::form->header;
1746
1747   print $::form->parse_html_template('io/ship_to', { previousform => $previous_form,
1748                                                      nextsub      => $::form->{display_form} || 'display_form',
1749                                                    });
1750
1751   $main::lxdebug->leave_sub();
1752 }
1753
1754 sub ship_to_entered {
1755   $::auth->restore_form_from_session(delete $::form->{previousform});
1756   call_sub($::form->{nextsub});
1757 }
1758
1759 sub relink_accounts {
1760   $main::lxdebug->enter_sub();
1761
1762   my $form     = $main::form;
1763   my %myconfig = %main::myconfig;
1764
1765   _check_io_auth();
1766
1767   $form->{"taxaccounts"} =~ s/\s*$//;
1768   $form->{"taxaccounts"} =~ s/^\s*//;
1769   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1770     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1771   }
1772   $form->{"taxaccounts"} = "";
1773
1774   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1775
1776   $main::lxdebug->leave_sub();
1777 }
1778
1779 sub set_duedate {
1780   $main::lxdebug->enter_sub();
1781
1782   my $form     = $main::form;
1783   my %myconfig = %main::myconfig;
1784
1785   _check_io_auth();
1786
1787   my $invdate = $form->{invdate} eq 'undefined' ? undef : $form->{invdate};
1788   my $duedate = $form->get_duedate(\%myconfig, $invdate);
1789
1790   print $form->ajax_response_header() . ($duedate || $invdate);
1791
1792   $main::lxdebug->leave_sub();
1793 }
1794
1795 sub _update_part_information {
1796   $main::lxdebug->enter_sub();
1797
1798   my $form     = $main::form;
1799
1800   my %part_information = IC->get_basic_part_info('id'        => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ],
1801                                                  'vendor_id' => $form->{vendor_id});
1802
1803   $form->{PART_INFORMATION} = \%part_information;
1804
1805   foreach my $i (1..$form->{rowcount}) {
1806     next unless ($form->{"id_${i}"});
1807
1808     my $info                 = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
1809     $form->{"partunit_${i}"} = $info->{unit};
1810     $form->{"weight_$i"}     = $info->{weight};
1811   }
1812
1813   $main::lxdebug->leave_sub();
1814 }
1815
1816 sub _update_ship {
1817   $main::lxdebug->enter_sub();
1818
1819   my $form     = $main::form;
1820   my %myconfig = %main::myconfig;
1821
1822   if (!$form->{ordnumber} || !$form->{id}) {
1823     map { $form->{"ship_$_"} = 0 } (1..$form->{rowcount});
1824     $main::lxdebug->leave_sub();
1825     return;
1826   }
1827
1828   my $all_units = AM->retrieve_all_units();
1829
1830   my %ship = DO->get_shipped_qty('type'  => ($form->{type} eq 'purchase_order') ? 'purchase' : 'sales',
1831                                  'oe_id' => $form->{id},);
1832
1833   foreach my $i (1..$form->{rowcount}) {
1834     next unless ($form->{"id_${i}"});
1835
1836     $form->{"ship_$i"} = 0;
1837
1838     my $ship_entry = $ship{$form->{"id_$i"}};
1839
1840     next if (!$ship_entry || ($ship_entry->{qty} <= 0));
1841
1842     my $rowqty =
1843       ($form->{simple_save} ? $form->{"qty_$i"} : $form->parse_amount(\%myconfig, $form->{"qty_$i"}))
1844       * $all_units->{$form->{"unit_$i"}}->{factor}
1845       / $all_units->{$form->{"partunit_$i"}}->{factor};
1846
1847     $form->{"ship_$i"}  = min($rowqty, $ship_entry->{qty});
1848     $ship_entry->{qty} -= $form->{"ship_$i"};
1849   }
1850
1851   foreach my $i (1..$form->{rowcount}) {
1852     next unless ($form->{"id_${i}"});
1853
1854     my $ship_entry = $ship{$form->{"id_$i"}};
1855
1856     next if (!$ship_entry || ($ship_entry->{qty} <= 0.01));
1857
1858     $form->{"ship_$i"} += $ship_entry->{qty};
1859     $ship_entry->{qty}  = 0;
1860   }
1861
1862   $main::lxdebug->leave_sub();
1863 }
1864
1865 sub _update_custom_variables {
1866   $main::lxdebug->enter_sub();
1867
1868   my $form     = $main::form;
1869
1870   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
1871   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
1872
1873   $main::lxdebug->leave_sub();
1874 }
1875
1876 sub _render_custom_variables_inputs {
1877   $main::lxdebug->enter_sub(2);
1878
1879   my $form     = $main::form;
1880
1881   my %params = @_;
1882
1883   if (!$form->{CVAR_CONFIGS}->{IC}) {
1884     $main::lxdebug->leave_sub();
1885     return;
1886   }
1887
1888   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
1889
1890   my $num_visible_cvars = 0;
1891   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
1892     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
1893
1894     my $description = '';
1895     if ($cvar->{flag_editable} && $cvar->{valid}) {
1896       $num_visible_cvars++;
1897       $description = $cvar->{description} . ' ';
1898     }
1899
1900     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
1901
1902     push @{ $params{ROW2} }, {
1903       line_break     => $num_visible_cvars == 1,
1904       description    => $description,
1905       cvar           => 1,
1906       render_options => {
1907          hide_non_editable => 1,
1908          var               => $cvar,
1909          name_prefix       => 'ic_',
1910          name_postfix      => "_$params{row}",
1911          valid             => $cvar->{valid},
1912          value             => CVar->parse($::form->{$form_key}, $cvar),
1913       }
1914     };
1915   }
1916
1917   $main::lxdebug->leave_sub(2);
1918 }
1919
1920 sub _remove_billed_or_delivered_rows {
1921   my (%params) = @_;
1922
1923   croak "Missing parameter 'quantities'" if !$params{quantities};
1924
1925   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
1926   my @new_rows;
1927
1928   my $removed_rows = 0;
1929   my $row          = 0;
1930   while ($row < $::form->{rowcount}) {
1931     $row++;
1932     next unless $::form->{"id_$row"};
1933
1934     my $parts_id                      = $::form->{"id_$row"};
1935     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
1936
1937     my $sub_qty                       = min($base_qty, $params{quantities}->{$parts_id});
1938     $params{quantities}->{$parts_id} -= $sub_qty;
1939
1940     if (!$sub_qty || ($sub_qty != $base_qty)) {
1941       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
1942       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
1943
1944     } else {
1945       $removed_rows++;
1946     }
1947   }
1948
1949   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
1950   $::form->{rowcount} -= $removed_rows;
1951 }