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