Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[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 | part_service_assembly_details');
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       $form->{"pricegroup_id_$i"} = $form->{"pricegroup_old_$i"} if $form->{"pricegroup_old_$i"};
425       $form->{"sellprice_pg_$i"}  = $form->{"hidden_prices_$i"}  if $form->{"hidden_prices_$i"};
426       push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost pricegroup_id sellprice_pg);
427       push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
428     }
429
430     my @HIDDENS = map { value => $_}, (
431           $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
432           $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
433           map { ($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
434             (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes
435                 income_accno expense_accno listprice assembly taxaccounts ordnumber transdate cusordnumber
436                 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
437     );
438
439     map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
440
441     $form->{invsubtotal} += $linetotal;
442
443     # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
444     _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
445
446     push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, };
447   }
448
449   $form->{totalweight} = $totalweight;
450
451   print $form->parse_html_template('oe/sales_order', { ROWS   => \@ROWS,
452                                                        HEADER => \@HEADER,
453                                                      });
454
455   if (0 != ($form->{sellprice_total} * 1)) {
456     $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
457   }
458
459   $main::lxdebug->leave_sub();
460 }
461
462 ##################################################
463 # build html-code for pricegroups in variable $form->{prices_$j}
464
465 sub set_pricegroup {
466   $main::lxdebug->enter_sub();
467
468   my $form     = $main::form;
469   my $locale   = $main::locale;
470   my $cgi      = $::request->{cgi};
471
472   _check_io_auth();
473
474   my $rowcount = shift;
475   for my $j (1 .. $rowcount) {
476     next unless $form->{PRICES}{$j};
477     # build drop down list for pricegroups
478     my $option_tmpl = qq|<option value="%s--%s" %s>%s</option>|;
479     $form->{"prices_$j"}  = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} }
480                                          (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} });
481
482     foreach my $item (@{ $form->{PRICES}{$j} }) {
483       # set new selectedpricegroup_id and prices for "Preis"
484       $form->{"pricegroup_old_$j"} = $item->{pricegroup_id}   if $item->{selected} &&  $item->{pricegroup_id};
485       $form->{"sellprice_$j"}      = $item->{price}           if $item->{selected} &&  $item->{pricegroup_id};
486       $form->{"price_new_$j"}      = $form->{"sellprice_$j"}  if $item->{selected} || !$item->{pricegroup_id};
487     }
488
489     # save hidden pricegroups for delivery_orders
490     next unless my @selected_prices = grep { $_->{selected} } @{ $form->{PRICES}{$j} };
491     $form->{"hidden_prices_$j"} = $selected_prices[-1]{price} . "--" . $selected_prices[-1]{pricegroup_id};
492   }
493   $main::lxdebug->leave_sub();
494 }
495
496 sub select_item {
497   $main::lxdebug->enter_sub();
498
499   my %params = @_;
500   my $mode   = $params{mode} || croak "Missing parameter 'mode'";
501
502   _check_io_auth();
503
504   my $previous_form = $::auth->save_form_in_session(form => $::form);
505   $::form->{title}  = $::locale->text('Select from one of the items below');
506   $::form->header;
507
508   my @item_list = map {
509     $_->{display_sellprice}  = $_->{sellprice} * (1 - $::form->{tradediscount});
510     $_->{display_sellprice} /= $_->{price_factor} if ($_->{price_factor});
511     $_;
512   } @{ $::form->{item_list} };
513
514   # delete action variable
515   delete @{$::form}{qw(action item_list)};
516
517   print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
518                                                          MODE          => $mode,
519                                                          ITEM_LIST     => \@item_list,
520                                                          IS_PURCHASE   => $mode eq 'IS' });
521
522   $main::lxdebug->leave_sub();
523 }
524
525 sub item_selected {
526   $main::lxdebug->enter_sub();
527
528   my $form     = $main::form;
529   my %myconfig = %main::myconfig;
530
531   _check_io_auth();
532
533   $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
534
535   my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
536   my $id   = delete($form->{select_item_id})   || croak 'Missing item selection ID';
537   my $i    = $form->{ $mode eq 'IC' ? 'assembly_rows' : 'rowcount' };
538
539   $form->{"id_${i}"} = $id;
540
541   if ($mode eq 'IS') {
542     IS->retrieve_item(\%myconfig, \%$form);
543   } elsif ($mode eq 'IR') {
544     IR->retrieve_item(\%myconfig, \%$form);
545   } elsif ($mode eq 'IC') {
546     IC->assembly_item(\%myconfig, \%$form);
547   } else {
548     croak "Invalid item selection mode '${mode}'";
549   }
550
551   my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
552
553   # if there was a price entered, override it
554   my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
555
556   my @new_fields =
557     qw(id partnumber description sellprice listprice inventory_accno
558        income_accno expense_accno bin unit weight assembly taxaccounts
559        partsgroup formel longdescription not_discountable partnotes lastcost
560        price_factor_id price_factor);
561
562   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
563   push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
564
565   map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
566
567   $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
568
569   if ($form->{"part_payment_id_$i"} ne "") {
570     $form->{payment_id} = $form->{"part_payment_id_$i"};
571   }
572
573   my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
574   $dec           = length $dec;
575   my $decimalplaces = ($dec > 2) ? $dec : 2;
576
577   if ($sellprice) {
578     $form->{"sellprice_$i"} = $sellprice;
579   } else {
580
581     # if there is an exchange rate adjust sellprice
582     if (($form->{exchangerate} * 1) != 0) {
583       $form->{"sellprice_$i"} /= $form->{exchangerate};
584       $form->{"sellprice_$i"} =
585         $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
586     }
587
588     # tradediscount
589     if ($::form->{tradediscount}) {
590       $::form->{"sellprice_$i"} *= 1 - $::form->{tradediscount};
591     }
592   }
593
594   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
595     qw(sellprice listprice weight);
596
597   $form->{weight}    += ($form->{"weight_$i"} * $form->{"qty_$i"});
598
599   if ($form->{"not_discountable_$i"}) {
600     $form->{"discount_$i"} = 0;
601   }
602
603   my $amount =
604     $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) *
605     $form->{"qty_$i"};
606   map { $form->{"${_}_base"} += $amount }
607     (split / /, $form->{"taxaccounts_$i"});
608   map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /,
609     $form->{"taxaccounts_$i"}
610     if !$form->{taxincluded};
611
612   $form->{creditremaining} -= $amount;
613
614   $form->{"runningnumber_$i"} = $i;
615
616   delete $form->{nextsub};
617
618   # format amounts
619   map {
620     $form->{"${_}_$i"} =
621       $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
622   } qw(sellprice listprice lastcost) if $form->{item} ne 'assembly';
623
624   # get pricegroups for parts
625   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
626
627   # build up html code for prices_$i
628   set_pricegroup($form->{rowcount});
629
630   &display_form;
631
632   $main::lxdebug->leave_sub();
633 }
634
635 sub new_item {
636   $main::lxdebug->enter_sub();
637
638   my $form     = $main::form;
639   my %myconfig = %main::myconfig;
640
641   _check_io_auth();
642
643   my $price_key = ($form->{type} =~ m/request_quotation|purchase_order/) || ($form->{script} eq 'ir.pl') ? 'lastcost' : 'sellprice';
644
645   # change callback
646   $form->{old_callback} = $form->escape($form->{callback}, 1);
647   $form->{callback}     = $form->escape("$form->{script}?action=display_form", 1);
648
649   # save all form variables except action in the session and keep the key in the previousform variable
650   my $previousform = $::auth->save_form_in_session(skip_keys => [ qw(action) ]);
651
652   my @HIDDENS;
653   push @HIDDENS,      { 'name' => 'previousform', 'value' => $previousform };
654   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} },                       qw(rowcount vc);
655   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{"${_}_$form->{rowcount}"} }, qw(partnumber description unit);
656   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
657   push @HIDDENS,      { 'name' => $price_key,     'value' => $form->parse_amount(\%myconfig, $form->{"sellprice_$form->{rowcount}"}) };
658   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{"longdescription_$form->{rowcount}"} };
659
660   $form->header();
661   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
662
663   $main::lxdebug->leave_sub();
664 }
665
666 sub check_form {
667   $main::lxdebug->enter_sub();
668
669   my $form     = $main::form;
670   my %myconfig = %main::myconfig;
671
672   _check_io_auth();
673
674   my @a     = ();
675   my $count = 0;
676
677   # remove any makes or model rows
678   if ($form->{item} eq 'assembly') {
679
680     # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
681     #$form->{sellprice} = 0;
682     $form->{weight}    = 0;
683     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
684       qw(listprice sellprice rop stock);
685
686     my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
687
688     for my $i (1 .. ($form->{assembly_rows} - 1)) {
689       if ($form->{"qty_$i"}) {
690         push @a, {};
691         my $j = $#a;
692
693         $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
694
695         map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
696
697         #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
698
699         # fuer assemblies auskommentiert. siehe oben
700         #    $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
701         $form->{weight}    += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
702         $count++;
703       }
704     }
705     # kann das hier auch weg? s.o. jb
706     $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
707
708     $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
709     $form->{assembly_rows} = $count;
710
711   } elsif ($form->{item} !~ m{^(?:part|service)$}) {
712     remove_emptied_rows(1);
713
714     $form->{creditremaining} -= &invoicetotal;
715   }
716
717   #sk
718   # if pricegroups
719   if (   $form->{type} =~ (/sales_quotation/)
720       or (($form->{level} =~ /Sales/) and ($form->{type} =~ /invoice/))
721       or (($form->{level} eq undef) and ($form->{type} =~ /invoice/))
722       or ($form->{type} =~ /sales_order/)) {
723
724     # get pricegroups for parts
725     IS->get_pricegroups_for_parts(\%myconfig, \%$form);
726
727     # build up html code for prices_$i
728     set_pricegroup($form->{rowcount});
729
730   }
731
732   &display_form;
733
734   $main::lxdebug->leave_sub();
735 }
736
737 sub remove_emptied_rows {
738   my $dont_add_empty = shift;
739   my $form           = $::form;
740
741   return unless $form->{rowcount};
742
743   my @flds = qw(id partnumber description qty ship sellprice unit
744                 discount inventory_accno income_accno expense_accno listprice
745                 taxaccounts bin assembly weight projectnumber project_id
746                 oldprojectnumber runningnumber serialnumber partsgroup payment_id
747                 not_discountable shop ve gv buchungsgruppen_id language_values
748                 sellprice_pg pricegroup_old price_old price_new unit_old ordnumber
749                 transdate longdescription basefactor marge_total marge_percent
750                 marge_price_factor lastcost price_factor_id partnotes
751                 stock_out stock_in has_sernumber reqdate);
752
753   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
754   push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
755
756   my @new_rows;
757   for my $i (1 .. $form->{rowcount} - 1) {
758     next unless $form->{"partnumber_$i"};
759
760     push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
761   }
762
763   my $new_rowcount = scalar @new_rows;
764   $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
765   $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
766 }
767
768 sub invoicetotal {
769   $main::lxdebug->enter_sub();
770
771   my $form     = $main::form;
772   my %myconfig = %main::myconfig;
773
774   _check_io_auth();
775
776   $form->{oldinvtotal} = 0;
777
778   # add all parts and deduct paid
779   map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
780
781   my ($amount, $sellprice, $discount, $qty);
782
783   for my $i (1 .. $form->{rowcount}) {
784     $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
785     $discount  = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
786     $qty       = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
787
788     #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
789
790     $amount = $sellprice * (1 - $discount / 100) * $qty;
791     map { $form->{"${_}_base"} += $amount }
792       (split (/ /, $form->{"taxaccounts_$i"}));
793     $form->{oldinvtotal} += $amount;
794   }
795
796   map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
797     split(/ /, $form->{taxaccounts})
798     if !$form->{taxincluded};
799
800   $form->{oldtotalpaid} = 0;
801   for my $i (1 .. $form->{paidaccounts}) {
802     $form->{oldtotalpaid} += $form->{"paid_$i"};
803   }
804
805   $main::lxdebug->leave_sub();
806
807   # return total
808   return ($form->{oldinvtotal} - $form->{oldtotalpaid});
809 }
810
811 sub validate_items {
812   $main::lxdebug->enter_sub();
813
814   my $form     = $main::form;
815   my $locale   = $main::locale;
816
817   _check_io_auth();
818
819   # check if items are valid
820   if ($form->{rowcount} == 1) {
821     flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
822     &update;
823     ::end_of_request();
824   }
825
826   for my $i (1 .. $form->{rowcount} - 1) {
827     $form->isblank("partnumber_$i",
828                    $locale->text('Number missing in Row') . " $i");
829   }
830
831   $main::lxdebug->leave_sub();
832 }
833
834 sub order {
835   $main::lxdebug->enter_sub();
836
837   my $form     = $main::form;
838   my %myconfig = %main::myconfig;
839   my $locale   = $main::locale;
840
841   _check_io_auth();
842
843   if ($form->{second_run}) {
844     $form->{print_and_post} = 0;
845   }
846   $form->{ordnumber} = $form->{invnumber};
847
848   $form->{old_employee_id} = $form->{employee_id};
849   $form->{old_salesman_id} = $form->{salesman_id};
850
851   map { delete $form->{$_} } qw(id printed emailed queued);
852   my $buysell;
853   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
854     $form->{title} = $locale->text('Add Purchase Order');
855     $form->{vc}    = 'vendor';
856     $form->{type}  = 'purchase_order';
857     $buysell       = 'sell';
858   }
859   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
860     $form->{title} = $locale->text('Add Sales Order');
861     $form->{vc}    = 'customer';
862     $form->{type}  = 'sales_order';
863     $buysell       = 'buy';
864   }
865   $form->{script} = 'oe.pl';
866
867   $form->{shipto} = 1;
868
869   $form->{rowcount}--;
870
871   $form->{cp_id} *= 1;
872
873   require "bin/mozilla/$form->{script}";
874   my $script = $form->{"script"};
875   $script =~ s|.*/||;
876   $script =~ s|.pl$||;
877   $locale = new Locale($::lx_office_conf{system}->{language}, $script);
878
879   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
880
881   my $currency = $form->{currency};
882
883   &order_links;
884
885   $form->{currency}     = $currency;
886   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
887   $form->{exchangerate} = $form->{forex} || '';
888
889   for my $i (1 .. $form->{rowcount}) {
890     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
891             if ($form->{"${_}_${i}"}) }
892         qw(ship qty sellprice listprice basefactor discount));
893   }
894
895   &prepare_order;
896   &display_form;
897
898   $main::lxdebug->leave_sub();
899 }
900
901 sub quotation {
902   $main::lxdebug->enter_sub();
903
904   my $form     = $main::form;
905   my %myconfig = %main::myconfig;
906   my $locale   = $main::locale;
907
908   _check_io_auth();
909
910   if ($form->{second_run}) {
911     $form->{print_and_post} = 0;
912   }
913   map { delete $form->{$_} } qw(id printed emailed queued);
914
915   my $buysell;
916   if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
917     $form->{title} = $locale->text('Add Request for Quotation');
918     $form->{vc}    = 'vendor';
919     $form->{type}  = 'request_quotation';
920     $buysell       = 'sell';
921   }
922   if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
923     $form->{title} = $locale->text('Add Quotation');
924     $form->{vc}    = 'customer';
925     $form->{type}  = 'sales_quotation';
926     $buysell       = 'buy';
927   }
928
929   $form->{cp_id} *= 1;
930
931   $form->{script} = 'oe.pl';
932
933   $form->{shipto} = 1;
934
935   $form->{rowcount}--;
936
937   require "bin/mozilla/$form->{script}";
938
939   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
940
941   my $currency = $form->{currency};
942
943   &order_links;
944
945   $form->{currency}     = $currency;
946   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
947   $form->{exchangerate} = $form->{forex} || '';
948
949   for my $i (1 .. $form->{rowcount}) {
950     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
951                                                      $form->{"${_}_${i}"})
952             if ($form->{"${_}_${i}"}) }
953         qw(ship qty sellprice listprice basefactor discount lastcost));
954   }
955
956   &prepare_order;
957   &display_form;
958
959   $main::lxdebug->leave_sub();
960 }
961
962 sub request_for_quotation {
963   quotation();
964 }
965
966 sub edit_e_mail {
967   $main::lxdebug->enter_sub();
968
969   my $form     = $main::form;
970   my %myconfig = %main::myconfig;
971   my $locale   = $main::locale;
972
973   _check_io_auth();
974
975   if ($form->{second_run}) {
976     $form->{print_and_post} = 0;
977     $form->{resubmit}       = 0;
978   }
979
980   $form->{email} = $form->{shiptoemail} if $form->{shiptoemail} && $form->{formname} =~ /(pick|packing|bin)_list/;
981
982   if ($form->{"cp_id"}) {
983     CT->get_contact(\%myconfig, $form);
984     $form->{"email"} = $form->{"cp_email"} if $form->{"cp_email"};
985   }
986
987   $form->{language} = $form->get_template_language(\%myconfig);
988   $form->{language} = "_" . $form->{language} if $form->{language};
989
990   my $title = $locale->text('E-mail') . " " . $form->get_formname_translation();
991
992   $form->{oldmedia} = $form->{media};
993   $form->{media}    = "email";
994
995   my $attachment_filename = $form->generate_attachment_filename();
996   my $subject             = $form->{subject} || $form->generate_email_subject();
997
998   $form->header;
999
1000   my (@dont_hide_key_list, %dont_hide_key, @hidden_keys);
1001   @dont_hide_key_list = qw(action email cc bcc subject message sendmode format header override login password);
1002   @dont_hide_key{@dont_hide_key_list} = (1) x @dont_hide_key_list;
1003   @hidden_keys = sort grep { !$dont_hide_key{$_} } grep { !ref $form->{$_} } keys %$form;
1004
1005   print $form->parse_html_template('generic/edit_email',
1006                                    { title         => $title,
1007                                      a_filename    => $attachment_filename,
1008                                      subject       => $subject,
1009                                      print_options => print_options('inline' => 1),
1010                                      HIDDEN        => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ],
1011                                      SHOW_BCC      => $::auth->assert('email_bcc', 'may fail') });
1012
1013   $main::lxdebug->leave_sub();
1014 }
1015
1016 sub send_email {
1017   $main::lxdebug->enter_sub();
1018
1019   my $form     = $main::form;
1020   my %myconfig = %main::myconfig;
1021
1022   _check_io_auth();
1023
1024   my $callback = $form->{script} . "?action=edit";
1025   map({ $callback .= "\&${_}=" . E($form->{$_}); } qw(type id));
1026
1027   print_form("return");
1028
1029   Common->save_email_status(\%myconfig, $form);
1030
1031   $form->{callback} = $callback;
1032   $form->redirect();
1033
1034   $main::lxdebug->leave_sub();
1035 }
1036
1037 # generate the printing options displayed at the bottom of oe and is forms.
1038 # this function will attempt to guess what type of form is displayed, and will generate according options
1039 #
1040 # about the coding:
1041 # this version builds the arrays of options pretty directly. if you have trouble understanding how,
1042 # the opthash function builds hashrefs which are then pieced together for the template arrays.
1043 # unneeded options are "undef"ed out, and then grepped out.
1044 #
1045 # the inline options is untested, but intended to be used later in metatemplating
1046 sub print_options {
1047   $main::lxdebug->enter_sub();
1048
1049   my $form     = $main::form;
1050   my %myconfig = %main::myconfig;
1051   my $locale   = $main::locale;
1052
1053   _check_io_auth();
1054
1055   my %options = @_;
1056
1057   # names 3 parameters and returns a hashref, for use in templates
1058   sub opthash { +{ value => shift, selected => shift, oname => shift } }
1059   my (@FORMNAME, @LANGUAGE_ID, @FORMAT, @SENDMODE, @MEDIA, @PRINTER_ID, @SELECTS) = ();
1060
1061   # note: "||"-selection is only correct for values where "0" is _not_ a correct entry
1062   $form->{sendmode}   = "attachment";
1063   $form->{format}     = $form->{format} || $myconfig{template_format} || "pdf";
1064   $form->{copies}     = $form->{copies} || $myconfig{copies}          || 3;
1065   $form->{media}      = $form->{media}  || $myconfig{default_media}   || "screen";
1066   $form->{printer_id} = defined $form->{printer_id}           ? $form->{printer_id} :
1067                         defined $myconfig{default_printer_id} ? $myconfig{default_printer_id} : "";
1068
1069   $form->{PD}{ $form->{formname} } = "selected";
1070   $form->{DF}{ $form->{format} }   = "selected";
1071   $form->{OP}{ $form->{media} }    = "selected";
1072   $form->{SM}{ $form->{formname} } = "selected";
1073
1074   push @FORMNAME, grep $_,
1075     ($form->{type} eq 'purchase_order') ? (
1076       opthash("purchase_order",      $form->{PD}{purchase_order},      $locale->text('Purchase Order')),
1077       opthash("bin_list",            $form->{PD}{bin_list},            $locale->text('Bin List'))
1078     ) : undef,
1079     ($form->{type} eq 'credit_note') ?
1080       opthash("credit_note",         $form->{PD}{credit_note},         $locale->text('Credit Note')) : undef,
1081     ($form->{type} eq 'sales_order') ? (
1082       opthash("sales_order",         $form->{PD}{sales_order},         $locale->text('Confirmation')),
1083       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
1084     ) : undef,
1085     ($form->{type} =~ /sales_quotation$/) ?
1086       opthash('sales_quotation',     $form->{PD}{sales_quotation},     $locale->text('Quotation')) : undef,
1087     ($form->{type} =~ /request_quotation$/) ?
1088       opthash('request_quotation',   $form->{PD}{request_quotation},   $locale->text('Request for Quotation')) : undef,
1089     ($form->{type} eq 'invoice') ? (
1090       opthash("invoice",             $form->{PD}{invoice},             $locale->text('Invoice')),
1091       opthash("proforma",            $form->{PD}{proforma},            $locale->text('Proforma Invoice')),
1092     ) : undef,
1093     ($form->{type} eq 'invoice' && $form->{storno}) ? (
1094       opthash("storno_invoice",      $form->{PD}{storno_invoice},      $locale->text('Storno Invoice')),
1095     ) : undef,
1096     ($form->{type} =~ /_delivery_order$/) ? (
1097       opthash($form->{type},         $form->{PD}{$form->{type}},       $locale->text('Delivery Order')),
1098       opthash('pick_list',           $form->{PD}{pick_list},           $locale->text('Pick List')),
1099     ) : undef;
1100
1101   push @SENDMODE,
1102     opthash("attachment",            $form->{SM}{attachment},          $locale->text('Attachment')),
1103     opthash("inline",                $form->{SM}{inline},              $locale->text('In-line'))
1104       if ($form->{media} eq 'email');
1105
1106   my $printable_templates = any { $::lx_office_conf{print_templates}->{$_} } qw(latex opendocument);
1107   push @MEDIA, grep $_,
1108       opthash("screen",              $form->{OP}{screen},              $locale->text('Screen')),
1109     ($printable_templates && $form->{printers} && scalar @{ $form->{printers} }) ?
1110       opthash("printer",             $form->{OP}{printer},             $locale->text('Printer')) : undef,
1111     ($printable_templates && !$options{no_queue}) ?
1112       opthash("queue",               $form->{OP}{queue},               $locale->text('Queue')) : undef
1113         if ($form->{media} ne 'email');
1114
1115   push @FORMAT, grep $_,
1116     ($::lx_office_conf{print_templates}->{opendocument} &&     $::lx_office_conf{applications}->{openofficeorg_writer}  &&     $::lx_office_conf{applications}->{xvfb}
1117                                                         && (-x $::lx_office_conf{applications}->{openofficeorg_writer}) && (-x $::lx_office_conf{applications}->{xvfb})
1118      && !$options{no_opendocument_pdf}) ?
1119       opthash("opendocument_pdf",    $form->{DF}{"opendocument_pdf"},  $locale->text("PDF (OpenDocument/OASIS)")) : undef,
1120     ($::lx_office_conf{print_templates}->{latex}) ?
1121       opthash("pdf",                 $form->{DF}{pdf},                 $locale->text('PDF')) : undef,
1122     ($::lx_office_conf{print_templates}->{latex} && !$options{no_postscript}) ?
1123       opthash("postscript",          $form->{DF}{postscript},          $locale->text('Postscript')) : undef,
1124     (!$options{no_html}) ?
1125       opthash("html", $form->{DF}{html}, "HTML") : undef,
1126     ($::lx_office_conf{print_templates}->{opendocument} && !$options{no_opendocument}) ?
1127       opthash("opendocument",        $form->{DF}{opendocument},        $locale->text("OpenDocument/OASIS")) : undef,
1128     ($::lx_office_conf{print_templates}->{excel} && !$options{no_excel}) ?
1129       opthash("excel",               $form->{DF}{excel},               $locale->text("Excel")) : undef;
1130
1131   push @LANGUAGE_ID,
1132     map { opthash($_->{id}, ($_->{id} eq $form->{language_id} ? 'selected' : ''), $_->{description}) } +{}, @{ $form->{languages} }
1133       if (ref $form->{languages} eq 'ARRAY');
1134
1135   push @PRINTER_ID,
1136     map { opthash($_->{id}, ($_->{id} eq $form->{printer_id} ? 'selected' : ''), $_->{printer_description}) } +{}, @{ $form->{printers} }
1137       if ((ref $form->{printers} eq 'ARRAY') && scalar @{ $form->{printers } });
1138
1139   @SELECTS = map {
1140     sname => $_->[1],
1141     DATA  => $_->[0],
1142     show  => !$options{"hide_" . $_->[1]} && scalar @{ $_->[0] }
1143   },
1144   [ \@FORMNAME,    'formname',    ],
1145   [ \@LANGUAGE_ID, 'language_id', ],
1146   [ \@FORMAT,      'format',      ],
1147   [ \@SENDMODE,    'sendmode',    ],
1148   [ \@MEDIA,       'media',       ],
1149   [ \@PRINTER_ID,  'printer_id',  ];
1150
1151   my %dont_display_groupitems = (
1152     'dunning' => 1,
1153     );
1154
1155   my %template_vars = (
1156     display_copies       => scalar @{ $form->{printers} || [] } && $::lx_office_conf{print_templates}->{latex} && $form->{media} ne 'email',
1157     display_remove_draft => (!$form->{id} && $form->{draft_id}),
1158     display_groupitems   => !$dont_display_groupitems{$form->{type}},
1159     groupitems_checked   => $form->{groupitems} ? "checked" : '',
1160     remove_draft_checked => $form->{remove_draft} ? "checked" : ''
1161   );
1162
1163   my $print_options = $form->parse_html_template("generic/print_options", { SELECTS  => \@SELECTS, %template_vars } );
1164
1165   if ($options{inline}) {
1166     $main::lxdebug->leave_sub();
1167     return $print_options;
1168   }
1169
1170   print $print_options;
1171
1172   $main::lxdebug->leave_sub();
1173 }
1174
1175 sub print {
1176   $main::lxdebug->enter_sub();
1177
1178   my $form     = $main::form;
1179   my $locale   = $main::locale;
1180
1181   _check_io_auth();
1182
1183   if ($form->{print_nextsub}) {
1184     call_sub($form->{print_nextsub});
1185     $main::lxdebug->leave_sub();
1186     return;
1187   }
1188
1189   # if this goes to the printer pass through
1190   my $old_form;
1191   if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1192     $form->error($locale->text('Select postscript or PDF!'))
1193       if ($form->{format} !~ /(postscript|pdf)/);
1194
1195     $old_form = new Form;
1196     map { $old_form->{$_} = $form->{$_} } keys %$form;
1197   }
1198
1199   if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1200     if ($form->{formname} eq "proforma") {
1201       $form->{proforma} = 1;
1202     }
1203     $form->{print_and_save} = 1;
1204     my $formname = $form->{formname};
1205     save();
1206     $form->{formname} = $formname;
1207     edit();
1208     $::lxdebug->leave_sub();
1209     ::end_of_request();
1210   }
1211   elsif (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)) {
1212     $form->{print_and_save} = 1;
1213     save();
1214   }
1215
1216
1217   &print_form($old_form);
1218
1219   $main::lxdebug->leave_sub();
1220 }
1221
1222 sub print_form {
1223   $main::lxdebug->enter_sub();
1224
1225   my $form     = $main::form;
1226   my %myconfig = %main::myconfig;
1227   my $locale   = $main::locale;
1228
1229   _check_io_auth();
1230
1231   my $defaults = SL::DB::Default->get;
1232   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
1233   $form->{templates} = $defaults->templates;
1234
1235   my ($old_form) = @_;
1236
1237   my $inv       = "inv";
1238   my $due       = "due";
1239   my $numberfld = "invnumber";
1240   my $order;
1241
1242   my $display_form =
1243     ($form->{display_form}) ? $form->{display_form} : "display_form";
1244
1245   # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1246   $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1247
1248   if ($form->{formname} eq "invoice") {
1249     $form->{label} = $locale->text('Invoice');
1250   }
1251   if ($form->{formname} eq 'sales_order') {
1252     $inv                  = "ord";
1253     $due                  = "req";
1254     $form->{"${inv}date"} = $form->{transdate};
1255     $form->{label}        = $locale->text('Confirmation');
1256     $numberfld            = "sonumber";
1257     $order                = 1;
1258   }
1259
1260   if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1261     $inv                  = "inv";
1262     $due                  = "due";
1263     $form->{"${inv}date"} = $form->{invdate};
1264     $form->{label}        = $locale->text('Proforma Invoice');
1265     $numberfld            = "sonumber";
1266     $order                = 0;
1267   }
1268
1269   if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1270     $inv                  = "inv";
1271     $due                  = "due";
1272     $form->{"${inv}date"} = $form->{transdate};
1273     $form->{"invdate"}    = $form->{transdate};
1274     $form->{invnumber}    = $form->{ordnumber};
1275     $form->{label}        = $locale->text('Proforma Invoice');
1276     $numberfld            = "sonumber";
1277     $order                = 1;
1278   }
1279
1280   if ($form->{formname} eq 'purchase_order') {
1281     $inv                  = "ord";
1282     $due                  = "req";
1283     $form->{"${inv}date"} = $form->{transdate};
1284     $form->{label}        = $locale->text('Purchase Order');
1285     $numberfld            = "ponumber";
1286     $order                = 1;
1287   }
1288   if ($form->{formname} eq 'bin_list') {
1289     $inv                  = "ord";
1290     $due                  = "req";
1291     $form->{"${inv}date"} = $form->{transdate};
1292     $form->{label}        = $locale->text('Bin List');
1293     $order                = 1;
1294   }
1295   if ($form->{formname} eq 'sales_quotation') {
1296     $inv                  = "quo";
1297     $due                  = "req";
1298     $form->{"${inv}date"} = $form->{transdate};
1299     $form->{label}        = $locale->text('Quotation');
1300     $numberfld            = "sqnumber";
1301     $order                = 1;
1302   }
1303
1304   if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1305     $inv                  = "quo";
1306     $due                  = "req";
1307     $form->{"${inv}date"} = $form->{transdate};
1308     $form->{"invdate"}    = $form->{transdate};
1309     $form->{label}        = $locale->text('Proforma Invoice');
1310     $numberfld            = "sqnumber";
1311     $order                = 1;
1312   }
1313
1314   if ($form->{formname} eq 'request_quotation') {
1315     $inv                  = "quo";
1316     $due                  = "req";
1317     $form->{"${inv}date"} = $form->{transdate};
1318     $form->{label}        = $locale->text('RFQ');
1319     $numberfld            = "rfqnumber";
1320     $order                = 1;
1321   }
1322
1323   if ($form->{type} =~ /_delivery_order$/) {
1324     undef $due;
1325     $inv                  = "do";
1326     $form->{"${inv}date"} = $form->{transdate};
1327     $numberfld            = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1328     $form->{label}        = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1329   }
1330
1331   $form->isblank("email", $locale->text('E-mail address missing!'))
1332     if ($form->{media} eq 'email');
1333   $form->isblank("${inv}date",
1334            $locale->text($form->{label})
1335            . ": "
1336            . $locale->text(' Date missing!'));
1337
1338   # $locale->text('Invoice Number missing!')
1339   # $locale->text('Invoice Date missing!')
1340   # $locale->text('Order Number missing!')
1341   # $locale->text('Order Date missing!')
1342   # $locale->text('Quotation Number missing!')
1343   # $locale->text('Quotation Date missing!')
1344
1345   # assign number
1346   $form->{what_done} = $form->{formname};
1347   if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) {
1348     $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld);
1349     if ($form->{media} ne 'email') {
1350
1351       # get pricegroups for parts
1352       IS->get_pricegroups_for_parts(\%myconfig, \%$form);
1353
1354       # build up html code for prices_$i
1355       set_pricegroup($form->{rowcount});
1356
1357       $form->{rowcount}--;
1358
1359       call_sub($display_form);
1360       # saving the history
1361       if(!exists $form->{addition}) {
1362         $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1363         $form->{addition} = "PRINTED";
1364         $form->save_history;
1365       }
1366       # /saving the history
1367       ::end_of_request();
1368     }
1369   }
1370
1371   &validate_items;
1372
1373   # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1374   my ($saved_email, $saved_cc, $saved_bcc) =
1375     ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1376
1377   my $language_saved = $form->{language_id};
1378   my $payment_id_saved = $form->{payment_id};
1379   my $delivery_term_id_saved = $form->{delivery_term_id};
1380   my $salesman_id_saved = $form->{salesman_id};
1381   my $cp_id_saved = $form->{cp_id};
1382   my $taxzone_id_saved = $form->{taxzone_id};
1383   my $currency_saved = $form->{currency};
1384
1385   call_sub("$form->{vc}_details") if ($form->{vc});
1386
1387   $form->{language_id} = $language_saved;
1388   $form->{payment_id} = $payment_id_saved;
1389   $form->{delivery_term_id} = $delivery_term_id_saved;
1390   $form->{taxzone_id} = $taxzone_id_saved;
1391   $form->{currency} = $currency_saved;
1392
1393   $form->{"email"} = $saved_email if ($saved_email);
1394   $form->{"cc"}    = $saved_cc    if ($saved_cc);
1395   $form->{"bcc"}   = $saved_bcc   if ($saved_bcc);
1396
1397   if (!$cp_id_saved) {
1398     # No contact was selected. Delete all contact variables because
1399     # IS->customer_details() and IR->vendor_details() get the default
1400     # contact anyway.
1401     map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1402   }
1403
1404   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1405   if ($form->{"language_id"}) {
1406     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1407       AM->get_language_details(\%myconfig, $form, $form->{language_id});
1408   } else {
1409     $output_dateformat = $myconfig{"dateformat"};
1410     $output_numberformat = $myconfig{"numberformat"};
1411     $output_longdates = 1;
1412   }
1413
1414   # Store the output number format so that the template modules know
1415   # how to parse the amounts back if requested.
1416   $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
1417
1418   ($form->{employee}) = split /--/, $form->{employee};
1419
1420   # create the form variables
1421   if ($form->{type} =~ /_delivery_order$/) {
1422     DO->order_details(\%myconfig, \%$form);
1423   } elsif ($order) {
1424     OE->order_details(\%myconfig, \%$form);
1425   } else {
1426     IS->invoice_details(\%myconfig, \%$form, $locale);
1427   }
1428
1429   $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
1430   $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
1431
1432   if ($form->{shipto_id}) {
1433     $form->get_shipto(\%myconfig);
1434   }
1435
1436   my @a = qw(name department_1 department_2 street zipcode city country contact phone fax email);
1437
1438   my $shipto = 1;
1439
1440   # if there is no shipto fill it in from billto
1441   foreach my $item (@a) {
1442     if ($form->{"shipto$item"}) {
1443       $shipto = 0;
1444       last;
1445     }
1446   }
1447
1448   if ($shipto) {
1449     if (   $form->{formname} eq 'purchase_order'
1450         || $form->{formname} eq 'request_quotation') {
1451       $form->{shiptoname}   = $defaults->company;
1452       $form->{shiptostreet} = $defaults->address;
1453     } else {
1454       map { $form->{"shipto$_"} = $form->{$_} } @a;
1455     }
1456   }
1457
1458   $form->{notes} =~ s/^\s+//g;
1459
1460   delete $form->{printer_command};
1461
1462   $form->{language} = $form->get_template_language(\%myconfig);
1463
1464   my $printer_code;
1465   if ($form->{media} ne 'email') {
1466     $printer_code = $form->get_printer_code(\%myconfig);
1467     if ($printer_code ne "") {
1468       $printer_code = "_" . $printer_code;
1469     }
1470   }
1471
1472   if ($form->{language} ne "") {
1473     my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
1474     map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
1475
1476     $form->{language} = "_" . $form->{language};
1477   }
1478
1479   # Format dates.
1480   format_dates($output_dateformat, $output_longdates,
1481                qw(invdate orddate quodate pldate duedate reqdate transdate
1482                   shippingdate deliverydate validitydate paymentdate
1483                   datepaid transdate_oe deliverydate_oe dodate
1484                   employee_startdate employee_enddate
1485                   ),
1486                grep({ /^datepaid_\d+$/ ||
1487                         /^transdate_oe_\d+$/ ||
1488                         /^deliverydate_oe_\d+$/ ||
1489                         /^reqdate_\d+$/ ||
1490                         /^deliverydate_\d+$/ ||
1491                         /^transdate_\d+$/
1492                     } keys(%{$form})));
1493
1494   reformat_numbers($output_numberformat, 2,
1495                    qw(invtotal ordtotal quototal subtotal linetotal
1496                       listprice sellprice netprice discount
1497                       tax taxbase total paid payment),
1498                    grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
1499
1500   reformat_numbers($output_numberformat, undef,
1501                    qw(qty price_factor),
1502                    grep({ /^qty_\d+$/
1503                         } keys(%{$form})));
1504
1505   my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1506
1507   if (scalar @{ $cvar_date_fields }) {
1508     format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1509   }
1510
1511   while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1512     reformat_numbers($output_numberformat, $precision, @{ $field_list });
1513   }
1514
1515   my $extension = 'html';
1516   if ($form->{format} eq 'postscript') {
1517     $form->{postscript}   = 1;
1518     $extension            = 'tex';
1519
1520   } elsif ($form->{"format"} =~ /pdf/) {
1521     $form->{pdf}          = 1;
1522     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
1523
1524   } elsif ($form->{"format"} =~ /opendocument/) {
1525     $form->{opendocument} = 1;
1526     $extension            = 'odt';
1527   } elsif ($form->{"format"} =~ /excel/) {
1528     $form->{excel} = 1;
1529     $extension            = 'xls';
1530   }
1531
1532   # search for the template
1533   my @template_files;
1534   push @template_files, "$form->{formname}_email$form->{language}$printer_code.$extension" if $form->{media} eq 'email';
1535   push @template_files, "$form->{formname}$form->{language}$printer_code.$extension";
1536   push @template_files, "$form->{formname}.$extension";
1537   push @template_files, "default.$extension";
1538   @template_files = uniq @template_files;
1539   $form->{IN}     = first { -f ($defaults->templates . "/$_") } @template_files;
1540
1541   if (!defined $form->{IN}) {
1542     $::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));
1543   }
1544
1545   delete $form->{OUT};
1546
1547   if ($form->{media} eq 'printer') {
1548     $form->{OUT}      = $form->{printer_command};
1549     $form->{OUT_MODE} = '|-';
1550     $form->{printed} .= " $form->{formname}";
1551     $form->{printed}  =~ s/^ //;
1552   }
1553   my $printed = $form->{printed};
1554
1555   if ($form->{media} eq 'email') {
1556     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1557       unless $form->{subject};
1558
1559     $form->{emailed} .= " $form->{formname}";
1560     $form->{emailed} =~ s/^ //;
1561   }
1562   my $emailed = $form->{emailed};
1563
1564   if ($form->{media} eq 'queue') {
1565     my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
1566
1567     my $filename;
1568     my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
1569     if ($filename = $queued{ $form->{formname} }) {
1570       unlink $::lx_office_conf{paths}->{spool} . "/$filename";
1571       delete $queued{ $form->{formname} };
1572
1573       $form->{queued}    =  join ' ', %queued;
1574       $filename          =~ s/\..*$//g;
1575       $filename         .=  $suffix;
1576       $form->{OUT}       =  $::lx_office_conf{paths}->{spool} . "/$filename";
1577       $form->{OUT_MODE}  =  '>';
1578
1579     } else {
1580       my $temp_fh;
1581       ($temp_fh, $filename) = File::Temp::tempfile(
1582         'kivitendo-spoolXXXXXX',
1583         SUFFIX => "$suffix",
1584         DIR    => $::lx_office_conf{paths}->{spool},
1585         UNLINK => 0,
1586       );
1587       close $temp_fh;
1588       $form->{OUT} = "$filename";
1589       # use >> for OUT_MODE because file is already created by File::Temp
1590       $form->{OUT_MODE} = '>>';
1591       # strip directory so that only filename is stored in table status
1592       ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
1593     }
1594
1595     # add type
1596     $form->{queued} .= " $form->{formname} $filename";
1597     $form->{queued} =~ s/^ //;
1598   }
1599   my $queued = $form->{queued};
1600
1601 # saving the history
1602   if(!exists $form->{addition}) {
1603     $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1604     if($form->{media} =~ /printer/) {
1605       $form->{addition} = "PRINTED";
1606     }
1607     elsif($form->{media} =~ /email/) {
1608       $form->{addition} = "MAILED";
1609     }
1610     elsif($form->{media} =~ /queue/) {
1611       $form->{addition} = "QUEUED";
1612     }
1613     elsif($form->{media} =~ /screen/) {
1614       $form->{addition} = "SCREENED";
1615     }
1616     $form->save_history;
1617   }
1618   # /saving the history
1619
1620   # prepare meta information for template introspection
1621   $form->{template_meta} = {
1622     formname  => $form->{formname},
1623     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
1624     format    => $form->{format},
1625     media     => $form->{media},
1626     extension => $extension,
1627     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
1628     today     => DateTime->today,
1629   };
1630
1631   $form->parse_template(\%myconfig);
1632
1633   $form->{callback} = "";
1634
1635   if ($form->{media} eq 'email') {
1636     $form->{message} = $locale->text('sent') unless $form->{message};
1637   }
1638   my $message = $form->{message};
1639
1640   # if we got back here restore the previous form
1641   if ($form->{media} =~ /(printer|email|queue)/) {
1642
1643     $form->update_status(\%myconfig)
1644       if ($form->{media} eq 'queue' && $form->{id});
1645
1646     return $main::lxdebug->leave_sub() if ($old_form eq "return");
1647
1648     if ($old_form) {
1649
1650       $old_form->{"${inv}number"} = $form->{"${inv}number"};
1651
1652       # restore and display form
1653       map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1654
1655       $form->{queued}  = $queued;
1656       $form->{printed} = $printed;
1657       $form->{emailed} = $emailed;
1658       $form->{message} = $message;
1659
1660       $form->{rowcount}--;
1661       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1662         qw(exchangerate creditlimit creditremaining);
1663
1664       for my $i (1 .. $form->{paidaccounts}) {
1665         map {
1666           $form->{"${_}_$i"} =
1667             $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1668         } qw(paid exchangerate);
1669       }
1670
1671       call_sub($display_form);
1672       ::end_of_request();
1673     }
1674
1675     my $msg =
1676       ($form->{media} eq 'printer')
1677       ? $locale->text('sent to printer')
1678       : $locale->text('emailed to') . " $form->{email}";
1679     $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1680   }
1681   if ($form->{printing}) {
1682    call_sub($display_form);
1683    ::end_of_request();
1684   }
1685
1686   $main::lxdebug->leave_sub();
1687 }
1688
1689 sub customer_details {
1690   $main::lxdebug->enter_sub();
1691
1692   my $form     = $main::form;
1693   my %myconfig = %main::myconfig;
1694
1695   IS->customer_details(\%myconfig, \%$form, @_);
1696
1697   $main::lxdebug->leave_sub();
1698 }
1699
1700 sub vendor_details {
1701   $main::lxdebug->enter_sub();
1702
1703   my $form     = $main::form;
1704   my %myconfig = %main::myconfig;
1705
1706   IR->vendor_details(\%myconfig, \%$form, @_);
1707
1708   $main::lxdebug->leave_sub();
1709 }
1710
1711 sub post_as_new {
1712   $main::lxdebug->enter_sub();
1713
1714   my $form     = $main::form;
1715
1716   _check_io_auth();
1717
1718   $form->{postasnew} = 1;
1719   map { delete $form->{$_} } qw(printed emailed queued);
1720
1721   &post;
1722
1723   $main::lxdebug->leave_sub();
1724 }
1725
1726 sub ship_to {
1727   $main::lxdebug->enter_sub();
1728
1729   _check_io_auth();
1730
1731   $::form->{print_and_post} = 0 if $::form->{second_run};
1732
1733   map { $::form->{$_} = $::form->parse_amount(\%::myconfig, $::form->{$_}) } qw(exchangerate creditlimit creditremaining);
1734
1735   # get details for customer/vendor
1736   call_sub($::form->{vc} . "_details", qw(name department_1 department_2 street zipcode city country contact email phone fax), $::form->{vc} . "number");
1737
1738   # get pricegroups for parts
1739   IS->get_pricegroups_for_parts(\%::myconfig, \%$::form);
1740
1741   # build up html code for prices_$i
1742   set_pricegroup($::form->{rowcount});
1743
1744   $::form->{rowcount}--;
1745
1746   my @shipto_vars   = qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry
1747                          shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail
1748                          shiptodepartment_1 shiptodepartment_2);
1749   my $previous_form = $::auth->save_form_in_session(skip_keys => [ @shipto_vars, qw(header shipto_id) ]);
1750   $::form->{title}  = $::locale->text('Ship to');
1751   $::form->header;
1752
1753   print $::form->parse_html_template('io/ship_to', { previousform => $previous_form,
1754                                                      nextsub      => $::form->{display_form} || 'display_form',
1755                                                    });
1756
1757   $main::lxdebug->leave_sub();
1758 }
1759
1760 sub ship_to_entered {
1761   $::auth->restore_form_from_session(delete $::form->{previousform});
1762   call_sub($::form->{nextsub});
1763 }
1764
1765 sub relink_accounts {
1766   $main::lxdebug->enter_sub();
1767
1768   my $form     = $main::form;
1769   my %myconfig = %main::myconfig;
1770
1771   _check_io_auth();
1772
1773   $form->{"taxaccounts"} =~ s/\s*$//;
1774   $form->{"taxaccounts"} =~ s/^\s*//;
1775   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1776     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1777   }
1778   $form->{"taxaccounts"} = "";
1779
1780   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1781
1782   $main::lxdebug->leave_sub();
1783 }
1784
1785 sub set_duedate {
1786   $main::lxdebug->enter_sub();
1787
1788   my $form     = $main::form;
1789   my %myconfig = %main::myconfig;
1790
1791   _check_io_auth();
1792
1793   my $invdate = $form->{invdate} eq 'undefined' ? undef : $form->{invdate};
1794   my $duedate = $form->get_duedate(\%myconfig, $invdate);
1795
1796   print $form->ajax_response_header() . ($duedate || $invdate);
1797
1798   $main::lxdebug->leave_sub();
1799 }
1800
1801 sub _update_part_information {
1802   $main::lxdebug->enter_sub();
1803
1804   my $form     = $main::form;
1805
1806   my %part_information = IC->get_basic_part_info('id'        => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ],
1807                                                  'vendor_id' => $form->{vendor_id});
1808
1809   $form->{PART_INFORMATION} = \%part_information;
1810
1811   foreach my $i (1..$form->{rowcount}) {
1812     next unless ($form->{"id_${i}"});
1813
1814     my $info                 = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
1815     $form->{"partunit_${i}"} = $info->{unit};
1816     $form->{"weight_$i"}     = $info->{weight};
1817   }
1818
1819   $main::lxdebug->leave_sub();
1820 }
1821
1822 sub _update_ship {
1823   $main::lxdebug->enter_sub();
1824
1825   my $form     = $main::form;
1826   my %myconfig = %main::myconfig;
1827
1828   if (!$form->{ordnumber} || !$form->{id}) {
1829     map { $form->{"ship_$_"} = 0 } (1..$form->{rowcount});
1830     $main::lxdebug->leave_sub();
1831     return;
1832   }
1833
1834   my $all_units = AM->retrieve_all_units();
1835
1836   my %ship = DO->get_shipped_qty('type'  => ($form->{type} eq 'purchase_order') ? 'purchase' : 'sales',
1837                                  'oe_id' => $form->{id},);
1838
1839   foreach my $i (1..$form->{rowcount}) {
1840     next unless ($form->{"id_${i}"});
1841
1842     $form->{"ship_$i"} = 0;
1843
1844     my $ship_entry = $ship{$form->{"id_$i"}};
1845
1846     next if (!$ship_entry || ($ship_entry->{qty} <= 0));
1847
1848     my $rowqty =
1849       ($form->{simple_save} ? $form->{"qty_$i"} : $form->parse_amount(\%myconfig, $form->{"qty_$i"}))
1850       * $all_units->{$form->{"unit_$i"}}->{factor}
1851       / $all_units->{$form->{"partunit_$i"}}->{factor};
1852
1853     $form->{"ship_$i"}  = min($rowqty, $ship_entry->{qty});
1854     $ship_entry->{qty} -= $form->{"ship_$i"};
1855   }
1856
1857   foreach my $i (1..$form->{rowcount}) {
1858     next unless ($form->{"id_${i}"});
1859
1860     my $ship_entry = $ship{$form->{"id_$i"}};
1861
1862     next if (!$ship_entry || ($ship_entry->{qty} <= 0.01));
1863
1864     $form->{"ship_$i"} += $ship_entry->{qty};
1865     $ship_entry->{qty}  = 0;
1866   }
1867
1868   $main::lxdebug->leave_sub();
1869 }
1870
1871 sub _update_custom_variables {
1872   $main::lxdebug->enter_sub();
1873
1874   my $form     = $main::form;
1875
1876   $form->{CVAR_CONFIGS}         = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
1877   $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
1878
1879   $main::lxdebug->leave_sub();
1880 }
1881
1882 sub _render_custom_variables_inputs {
1883   $main::lxdebug->enter_sub(2);
1884
1885   my $form     = $main::form;
1886
1887   my %params = @_;
1888
1889   if (!$form->{CVAR_CONFIGS}->{IC}) {
1890     $main::lxdebug->leave_sub();
1891     return;
1892   }
1893
1894   my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
1895
1896   my $num_visible_cvars = 0;
1897   foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
1898     $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
1899
1900     my $description = '';
1901     if ($cvar->{flag_editable} && $cvar->{valid}) {
1902       $num_visible_cvars++;
1903       $description = $cvar->{description} . ' ';
1904     }
1905
1906     my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
1907
1908     push @{ $params{ROW2} }, {
1909       line_break     => $num_visible_cvars == 1,
1910       description    => $description,
1911       cvar           => 1,
1912       render_options => {
1913          hide_non_editable => 1,
1914          var               => $cvar,
1915          name_prefix       => 'ic_',
1916          name_postfix      => "_$params{row}",
1917          valid             => $cvar->{valid},
1918          value             => CVar->parse($::form->{$form_key}, $cvar),
1919       }
1920     };
1921   }
1922
1923   $main::lxdebug->leave_sub(2);
1924 }
1925
1926 sub _remove_billed_or_delivered_rows {
1927   my (%params) = @_;
1928
1929   croak "Missing parameter 'quantities'" if !$params{quantities};
1930
1931   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
1932   my @new_rows;
1933
1934   my $make_key = sub {
1935     my ($row) = @_;
1936     return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
1937     my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
1938     return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
1939   };
1940
1941   my $removed_rows = 0;
1942   my $row          = 0;
1943   while ($row < $::form->{rowcount}) {
1944     $row++;
1945     next unless $::form->{"id_$row"};
1946
1947     my $parts_id                      = $::form->{"id_$row"};
1948     my $base_qty                      = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
1949
1950     my $key                           = $make_key->($row);
1951     my $sub_qty                       = min($base_qty, $params{quantities}->{$key});
1952     $params{quantities}->{$key}      -= $sub_qty;
1953
1954     if (!$sub_qty || ($sub_qty != $base_qty)) {
1955       $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
1956       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
1957
1958     } else {
1959       $removed_rows++;
1960     }
1961   }
1962
1963   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
1964   $::form->{rowcount} -= $removed_rows;
1965 }