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