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