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