X-Git-Url: http://wagnertech.de/git?a=blobdiff_plain;f=bin%2Fmozilla%2Fio.pl;h=60a535f365ade56d88f40f4255a13aee43f697cb;hb=b8125c17c8add08c9b84fb054f797547a853dd3a;hp=7acf49db039e33d155b7b084bbe332e4dc9c14b2;hpb=7f1ff6c83a866d6536c83aae0d24b8d87801d6ac;p=kivitendo-erp.git diff --git a/bin/mozilla/io.pl b/bin/mozilla/io.pl index 7acf49db0..a54f65deb 100644 --- a/bin/mozilla/io.pl +++ b/bin/mozilla/io.pl @@ -38,14 +38,24 @@ use Carp; use CGI; -use CGI::Ajax; +use List::MoreUtils qw(any uniq apply); use List::Util qw(min max first); use SL::CVar; use SL::Common; use SL::CT; +use SL::Locale::String qw(t8); use SL::IC; use SL::IO; +use SL::PriceSource; + +use SL::DB::Customer; +use SL::DB::Default; +use SL::DB::Language; +use SL::DB::Printer; +use SL::DB::Vendor; +use SL::Helper::CreatePDF; +use SL::Helper::Flash; require "bin/mozilla/common.pl"; @@ -98,7 +108,7 @@ use Data::Dumper; sub _check_io_auth { $main::auth->assert('part_service_assembly_edit | vendor_invoice_edit | sales_order_edit | invoice_edit |' . 'request_quotation_edit | sales_quotation_edit | purchase_order_edit | ' . - 'purchase_delivery_order_edit | sales_delivery_order_edit'); + 'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details'); } ######################################## @@ -113,20 +123,24 @@ sub display_row { my $form = $main::form; my %myconfig = %main::myconfig; my $locale = $main::locale; - my $cgi = $main::cgi; + my $cgi = $::request->{cgi}; my $numrows = shift; - my ($readonly, $stock_in_out, $stock_in_out_title); + my ($stock_in_out, $stock_in_out_title); + + my $defaults = AM->get_defaults(); + $form->{show_weight} = $defaults->{show_weight}; + $form->{weightunit} = $defaults->{weightunit}; my $is_purchase = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl'); my $show_min_order_qty = first { $_ eq $form->{type} } qw(request_quotation purchase_order); my $is_delivery_order = $form->{type} =~ /_delivery_order$/; + my $is_quotation = $form->{type} =~ /_quotation$/; + my $is_invoice = $form->{type} =~ /invoice/; my $is_s_p_order = (first { $_ eq $form->{type} } qw(sales_order purchase_order)); if ($is_delivery_order) { - $readonly = ' readonly' if ($form->{closed}); - if ($form->{type} eq 'sales_delivery_order') { $stock_in_out_title = $locale->text('Release From Stock'); $stock_in_out = 'out'; @@ -139,7 +153,7 @@ sub display_row { } # column_index - my @header_sort = qw(runningnumber partnumber description ship qty unit sellprice_pg sellprice discount linetotal); + my @header_sort = qw(runningnumber partnumber description ship qty unit weight sellprice discount linetotal); my @HEADER = ( { id => 'runningnumber', width => 5, value => $locale->text('No.'), display => 1, }, { id => 'partnumber', width => 8, value => $locale->text('Number'), display => 1, }, @@ -148,10 +162,11 @@ sub display_row { { id => 'qty', width => 5, value => $locale->text('Qty'), display => 1, }, { id => 'price_factor', width => 5, value => $locale->text('Price Factor'), display => !$is_delivery_order, }, { id => 'unit', width => 5, value => $locale->text('Unit'), display => 1, }, + { id => 'weight', width => 5, value => $locale->text('Weight'), display => $defaults->{show_weight}, }, { id => 'serialnr', width => 10, value => $locale->text('Serial No.'), display => 0, }, { id => 'projectnr', width => 10, value => $locale->text('Project'), display => 0, }, + { id => 'price_source', width => 5, value => $locale->text('Price Source'), display => !$is_delivery_order, }, { id => 'sellprice', width => 15, value => $locale->text('Price'), display => !$is_delivery_order, }, - { id => 'sellprice_pg', width => 8, value => $locale->text('Pricegroup'), display => !$is_delivery_order && !$is_purchase, }, { id => 'discount', width => 5, value => $locale->text('Discount'), display => !$is_delivery_order, }, { id => 'linetotal', width => 10, value => $locale->text('Extended'), display => !$is_delivery_order, }, { id => 'bin', width => 10, value => $locale->text('Bin'), display => 0, }, @@ -185,12 +200,13 @@ sub display_row { my $deliverydate = $locale->text('Required by'); # special alignings - my %align = map { $_ => 'right' } qw(qty ship right sellprice_pg discount linetotal stock_in_out); + my %align = map { $_ => 'right' } qw(qty ship right discount linetotal stock_in_out weight); my %nowrap = map { $_ => 1 } qw(description unit); $form->{marge_total} = 0; $form->{sellprice_total} = 0; $form->{lastcost_total} = 0; + $form->{totalweight} = 0; my %projectnumber_labels = (); my @projectnumber_values = (""); @@ -203,17 +219,26 @@ sub display_row { _update_ship() if ($is_s_p_order); _update_custom_variables(); + my $totalweight = 0; + + my $record = _make_record(); # rows my @ROWS; for my $i (1 .. $numrows) { my %column_data = (); + my $record_item = $record->id && $record->items ? $record->items->[$i-1] : _make_record_item($i); + # undo formatting map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(qty discount sellprice lastcost price_new price_old) unless ($form->{simple_save}); + if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) { + $form->{"sellprice_$i"} = $form->{"price_new_$i"}; + } + # unit begin $form->{"unit_old_$i"} ||= $form->{"unit_$i"}; $form->{"selected_unit_$i"} ||= $form->{"unit_$i"}; @@ -222,11 +247,11 @@ sub display_row { || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"}; # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen. } - # adjust prices by unit, ignore if pricegroup changed - if ((!$form->{"prices_$i"}) || ($form->{"new_pricegroup_$i"} == $form->{"old_pricegroup_$i"})) { - $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1; - $form->{"unit_old_$i"} = $form->{"selected_unit_$i"}; - } + + $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1; + $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1; + $form->{"unit_old_$i"} = $form->{"selected_unit_$i"}; + my $this_unit = $form->{"unit_$i"}; $this_unit = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units); @@ -243,23 +268,32 @@ sub display_row { } else { $column_data{price_factor} = ' '; } + $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1; $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef); # / unit ending +#count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces +#is shown for lastcost and sellprice. my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2; + $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces; my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || 1; my $discount = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * $form->{"discount_$i"} / 100 / $price_factor, 2); my $linetotal = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2); my $rows = $form->numtextrows($form->{"description_$i"}, 30, 6); - $column_data{runningnumber} = $cgi->textfield(-name => "runningnumber_$i", -size => 5, -value => $i); # HuT - $column_data{partnumber} = $cgi->textfield(-name => "partnumber_$i", -size => 12, -value => $form->{"partnumber_$i"}); + # quick delete single row + $column_data{runningnumber} .= q|| . + q|| . $locale->text('Remove') . q| |; + $column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5, -value => $i); # HuT + + + $column_data{partnumber} = $cgi->textfield(-name => "partnumber_$i", -id => "partnumber_$i", -size => 12, -value => $form->{"partnumber_$i"}); $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead - ? $cgi->textarea( -name => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30) - : $cgi->textfield(-name => "description_$i", -size => 30, -value => $form->{"description_$i"})) - . $cgi->button(-value => $locale->text('L'), -onClick => "set_longdescription_window('longdescription_$i')"); + ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30) + : $cgi->textfield(-name => "description_$i", -id => "description_$i", -value => $form->{"description_$i"}, -size => 30)) + . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)"); my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2; @@ -277,33 +311,48 @@ sub display_row { $column_data{ship} = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"}; } - # build in drop down list for pricesgroups - if ($form->{"prices_$i"}) { - $column_data{sellprice_pg} = qq||; - $column_data{sellprice} = $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => 'check_right_number_format(this)', -value => - (($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"}) - ? $form->format_amount(\%myconfig, $form->{"price_new_$i"}, $decimalplaces) - : $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces))); - } else { - # for last row and report - # set pricegroup drop down list from report menu - if ($form->{"sellprice_$i"} != 0) { - # remember the pricegroup_id in pricegroup_old - # but don't overwrite it - $form->{"pricegroup_old_$i"} = $form->{"pricegroup_id_$i"}; - my $default_option = $form->{"sellprice_$i"}.'--'.$form->{"pricegroup_id_$i"}; - $column_data{sellprice_pg} = NTI($cgi->popup_menu("sellprice_pg_$i", [ $default_option ], $default_option, { $default_option => $form->{"pricegroup_$i"} || '' })); - } else { - $column_data{sellprice_pg} = qq| |; - } - $column_data{sellprice} = $cgi->textfield(-name => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => - $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces)); - - } - $column_data{discount} = $cgi->textfield(-name => "discount_$i", -size => 3, -value => $form->format_amount(\%myconfig, $form->{"discount_$i"})); + my $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces); + my $discount_value = $form->format_amount(\%myconfig, $form->{"discount_$i"}); + my $edit_prices = $main::auth->assert('edit_prices', 1) && !$::form->{"active_price_source_$i"}; + my $edit_discounts = $main::auth->assert('edit_prices', 1) && !$::form->{"active_discount_source_$i"}; + $column_data{sellprice} = (!$edit_prices) + ? $cgi->hidden( -name => "sellprice_$i", -id => "sellprice_$i", -value => $sellprice_value) . $sellprice_value + : $cgi->textfield(-name => "sellprice_$i", -id => "sellprice_$i", -size => 10, -onBlur => "check_right_number_format(this)", -value => $sellprice_value); + $column_data{discount} = (!$edit_discounts) + ? $cgi->hidden( -name => "discount_$i", -id => "discount_$i", -value => $discount_value) . $discount_value . ' %' + : $cgi->textfield(-name => "discount_$i", -id => "discount_$i", -size => 3, -value => $discount_value); $column_data{linetotal} = $form->format_amount(\%myconfig, $linetotal, 2); $column_data{bin} = $form->{"bin_$i"}; + $column_data{weight} = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight}; + + if ($form->{"id_${i}"} && !$is_delivery_order) { + my $price_source = SL::PriceSource->new(record_item => $record_item, record => $record); + my $price = $price_source->price_from_source($::form->{"active_price_source_$i"}); + my $discount = $price_source->price_from_source($::form->{"active_discount_source_$i"}); + my $best_price = $price_source->best_price; + my $best_discount = $price_source->best_discount; + $column_data{price_source} .= $cgi->button(-value => $price->source_description, -onClick => "kivi.io.price_chooser($i)"); + if ($price->source) { + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->invalid, title => $price->invalid }) if $price->invalid; + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->missing, title => $price->missing }) if $price->missing; + if (!$price->missing && !$price->invalid) { + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/up.png', alt => t8('This price has since gone up'), title => t8('This price has since gone up' ) }) if $price->price > $record_item->sellprice; + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/down.png', alt => t8('This price has since gone down'), title => t8('This price has since gone down') }) if $price->price < $record_item->sellprice; + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/ok.png', alt => t8('There is a better price available'), title => t8('There is a better price available') }) if $best_price && $price->source ne $price_source->best_price->source; + } + } + if ($discount->source) { + $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->invalid, title => $discount->invalid }) if $discount->invalid; + $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->missing, title => $discount->missing }) if $discount->missing; + if (!$discount->missing && !$discount->invalid) { + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/up.png', alt => t8('This discount has since gone up'), title => t8('This discount has since gone up') }) if $discount->discount * 100 > $record_item->discount; + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/down.png', alt => t8('This discount has since gone down'), title => t8('This discount has since gone down') }) if $discount->discount * 100 < $record_item->discount; + $column_data{price_source} .= ' ' . $cgi->img({src => 'image/ok.png', alt => t8('There is a better discount available'), title => t8('There is a better discount available') }) if $best_discount && $discount->source ne $price_source->best_discount->source; + } + } + } + if ($is_delivery_order) { $column_data{stock_in_out} = calculate_stock_in_out($i); } @@ -326,8 +375,20 @@ sub display_row { $form->{"marge_percent_$i"} = 0; my $marge_color; - my $real_sellprice = $linetotal; - my $real_lastcost = $form->{"lastcost_$i"} * $form->{"qty_$i"} / ( $form->{"marge_price_factor_$i"} || 1 ); + my $real_sellprice; + if ( $form->{taxincluded} and $form->{"qty_$i"} * 1 and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) { + # if we use taxincluded we need to calculate the marge from the net_value + # all the marge calculations are based on linetotal which we need to + # convert to net first + + # there is no direct form value for the tax_rate of the item, but + # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate + # gives the tax percentage (e.g. 0.19) + $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"}); + } else { + $real_sellprice = $linetotal; + }; + my $real_lastcost = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2); my $marge_percent_warn = $myconfig{marge_percent_warn} * 1 || 15; my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1; @@ -349,14 +410,20 @@ sub display_row {  %s |, $marge_color, $locale->text('Ertrag'),$form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"}, $locale->text('LP'), $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2), - $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, 2) } - if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ || $form->{type} =~ /invoice/) && !$is_delivery_order; + $locale->text('EK'), $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces) } + if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ || $form->{type} =~ /invoice/ || $form->{type} =~ /^credit_note$/ ) && !$is_delivery_order; + + $form->{"listprice_$i"} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2) + if $form->{"id_$i"} && ($form->{type} =~ /^sales_/ || $form->{type} =~ /invoice/) ; # / marge calculations ending +# Calculate total weight + $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"}); + # calculate onhand if ($form->{"id_$i"}) { my $part = IC->get_basic_part_info(id => $form->{"id_$i"}); - my $onhand_color = 'color="#ff0000"' if $part->{onhand} < $part->{rop}; + my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : ''; push @ROW2, { value => sprintf "%s %s %s", $locale->text('On Hand'), $onhand_color, @@ -367,20 +434,33 @@ sub display_row { # / calculate onhand my @hidden_vars; - - if ($is_delivery_order) { + # add hidden ids for persistent (item|invoice)_ids and previous (converted_from*) ids + if ($is_quotation) { + push @hidden_vars, qw(orderitems_id converted_from_orderitems_id); + } + if ($is_s_p_order) { + push @hidden_vars, qw(orderitems_id converted_from_orderitems_id converted_from_invoice_id); + } + if ($is_invoice) { + push @hidden_vars, qw(invoice_id converted_from_orderitems_id converted_from_delivery_order_items_id converted_from_invoice_id); + } + if ($::form->{type} =~ /credit_note/) { + push @hidden_vars, qw(invoice_id converted_from_invoice_id); + } + if ($is_delivery_order) { map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost); - push @hidden_vars, qw(sellprice discount not_discountable price_factor_id lastcost); + push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost); push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}"; + push @hidden_vars, qw(delivery_order_items_id converted_from_orderitems_id converted_from_delivery_order_items_id); } my @HIDDENS = map { value => $_}, ( $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}), $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})), - map { ($cgi->hidden("-name" => $_, "-value" => $form->{$_})); } map { $_."_$i" } - (qw(orderitems_id bo pricegroup_old price_old id inventory_accno bin partsgroup partnotes - income_accno expense_accno listprice assembly taxaccounts ordnumber transdate cusordnumber - longdescription basefactor marge_absolut marge_percent marge_price_factor), @hidden_vars) + map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" } + (qw(bo price_old id inventory_accno bin partsgroup partnotes active_price_source active_discount_source + income_accno expense_accno listprice assembly taxaccounts ordnumber donumber transdate cusordnumber + longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars) ); map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"})); @@ -390,9 +470,11 @@ sub display_row { # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"}); - push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, }; + push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, obj => $record_item }; } + $form->{totalweight} = $totalweight; + print $form->parse_html_template('oe/sales_order', { ROWS => \@ROWS, HEADER => \@HEADER, }); @@ -404,36 +486,6 @@ sub display_row { $main::lxdebug->leave_sub(); } -################################################## -# build html-code for pricegroups in variable $form->{prices_$j} - -sub set_pricegroup { - $main::lxdebug->enter_sub(); - - my $form = $main::form; - my $locale = $main::locale; - my $cgi = $main::cgi; - - _check_io_auth(); - - my $rowcount = shift; - for my $j (1 .. $rowcount) { - next unless $form->{PRICES}{$j}; - # build drop down list for pricegroups - my $option_tmpl = qq||; - $form->{"prices_$j"} = join '', map { sprintf $option_tmpl, @$_{qw(price pricegroup_id selected pricegroup)} } - (+{ pricegroup => $locale->text("none (pricegroup)") }, @{ $form->{PRICES}{$j} }); - - foreach my $item (@{ $form->{PRICES}{$j} }) { - # set new selectedpricegroup_id and prices for "Preis" - $form->{"pricegroup_old_$j"} = $item->{pricegroup_id} if $item->{selected} && $item->{pricegroup_id}; - $form->{"sellprice_$j"} = $item->{price} if $item->{selected} && $item->{pricegroup_id}; - $form->{"price_new_$j"} = $form->{"sellprice_$j"} if $item->{selected} || !$item->{pricegroup_id}; - } - } - $main::lxdebug->leave_sub(); -} - sub select_item { $main::lxdebug->enter_sub(); @@ -447,13 +499,12 @@ sub select_item { $::form->header; my @item_list = map { - $_->{display_sellprice} = $_->{sellprice} * (1 - $::form->{tradediscount}); $_->{display_sellprice} /= $_->{price_factor} if ($_->{price_factor}); $_; } @{ $::form->{item_list} }; # delete action variable - delete @{$::form}{qw(action item_list header)}; + delete @{$::form}{qw(action item_list)}; print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form, MODE => $mode, @@ -505,6 +556,23 @@ sub item_selected { map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields; + if (my $record = _make_record()) { + my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record); + my $best_price = $price_source->best_price; + + if ($best_price) { + $::form->{"sellprice_$i"} = $best_price->price; + $::form->{"active_price_source_$i"} = $best_price->source; + } + + my $best_discount = $price_source->best_discount; + + if ($best_discount) { + $::form->{"discount_$i"} = $best_discount->discount; + $::form->{"active_discount_source_$i"} = $best_discount->source; + } + } + $form->{"marge_price_factor_$i"} = $new_item->{price_factor}; if ($form->{"part_payment_id_$i"} ne "") { @@ -530,7 +598,6 @@ sub item_selected { map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(sellprice listprice weight); - $form->{sellprice} += ($form->{"sellprice_$i"} * $form->{"qty_$i"}); $form->{weight} += ($form->{"weight_$i"} * $form->{"qty_$i"}); if ($form->{"not_discountable_$i"}) { @@ -558,12 +625,6 @@ sub item_selected { $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice listprice lastcost) if $form->{item} ne 'assembly'; - # get pricegroups for parts - IS->get_pricegroups_for_parts(\%myconfig, \%$form); - - # build up html code for prices_$i - set_pricegroup($form->{rowcount}); - &display_form; $main::lxdebug->leave_sub(); @@ -612,11 +673,7 @@ sub check_form { my $count = 0; # remove any makes or model rows - if ($form->{item} eq 'part') { - map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } - qw(listprice sellprice lastcost weight rop); - - } elsif ($form->{item} eq 'assembly') { + if ($form->{item} eq 'assembly') { # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt? #$form->{sellprice} = 0; @@ -649,10 +706,7 @@ sub check_form { $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows}); $form->{assembly_rows} = $count; - } elsif ($form->{item} eq 'service') { - map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(listprice sellprice lastcost); - - } else { + } elsif ($form->{item} !~ m{^(?:part|service)$}) { remove_emptied_rows(1); $form->{creditremaining} -= &invoicetotal; @@ -665,12 +719,6 @@ sub check_form { or (($form->{level} eq undef) and ($form->{type} =~ /invoice/)) or ($form->{type} =~ /sales_order/)) { - # get pricegroups for parts - IS->get_pricegroups_for_parts(\%myconfig, \%$form); - - # build up html code for prices_$i - set_pricegroup($form->{rowcount}); - } &display_form; @@ -689,10 +737,13 @@ sub remove_emptied_rows { taxaccounts bin assembly weight projectnumber project_id oldprojectnumber runningnumber serialnumber partsgroup payment_id not_discountable shop ve gv buchungsgruppen_id language_values - sellprice_pg pricegroup_old price_old price_new unit_old ordnumber + price_old price_new unit_old ordnumber donumber transdate longdescription basefactor marge_total marge_percent marge_price_factor lastcost price_factor_id partnotes - stock_out stock_in has_sernumber reqdate); + stock_out stock_in has_sernumber reqdate orderitems_id + active_price_source active_discount_source delivery_order_items_id + invoice_id converted_from_orderitems_id + converted_from_delivery_order_items_id converted_from_invoice_id); my $ic_cvar_configs = CVar->get_configs(module => 'IC'); push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs }; @@ -762,6 +813,7 @@ sub validate_items { # check if items are valid if ($form->{rowcount} == 1) { + flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.')); &update; ::end_of_request(); } @@ -791,7 +843,10 @@ sub order { $form->{old_employee_id} = $form->{employee_id}; $form->{old_salesman_id} = $form->{salesman_id}; - map { delete $form->{$_} } qw(id printed emailed queued); + # link doc invoice -> quotation (single id no multi mode) + $form->{convert_from_ar_ids} = delete $form->{id}; + + delete $form->{$_} foreach (qw(printed emailed queued)); my $buysell; if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') { $form->{title} = $locale->text('Add Purchase Order'); @@ -807,8 +862,6 @@ sub order { } $form->{script} = 'oe.pl'; - $form->{shipto} = 1; - $form->{rowcount}--; $form->{cp_id} *= 1; @@ -833,6 +886,7 @@ sub order { map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice listprice basefactor discount)); + $form->{"converted_from_invoice_id_$i"} = delete $form->{"invoice_id_$i"}; } &prepare_order; @@ -850,10 +904,18 @@ sub quotation { _check_io_auth(); + # we are coming from *_order and convert to quotation + # it seems that quotation is only called if we have a existing order + if ($form->{type} =~ /(sales|purchase)_order/) { + $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"}; + } + # link doc order -> quotation (single id no multi mode) + $form->{convert_from_oe_ids} = delete $form->{id}; + if ($form->{second_run}) { $form->{print_and_post} = 0; } - map { delete $form->{$_} } qw(id printed emailed queued); + delete $form->{$_} foreach (qw(printed emailed queued)); my $buysell; if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') { @@ -873,8 +935,6 @@ sub quotation { $form->{script} = 'oe.pl'; - $form->{shipto} = 1; - $form->{rowcount}--; require "bin/mozilla/$form->{script}"; @@ -893,7 +953,7 @@ sub quotation { map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } - qw(ship qty sellprice listprice basefactor discount)); + qw(ship qty sellprice listprice basefactor discount lastcost)); } &prepare_order; @@ -927,15 +987,21 @@ sub edit_e_mail { $form->{"email"} = $form->{"cp_email"} if $form->{"cp_email"}; } + $form->{language} = $form->get_template_language(\%myconfig); + $form->{language} = "_" . $form->{language} if $form->{language}; + my $title = $locale->text('E-mail') . " " . $form->get_formname_translation(); $form->{oldmedia} = $form->{media}; $form->{media} = "email"; + my $global_bcc = AM->get_defaults()->{global_bcc}; + + $form->{bcc} = join ', ', grep $_, $form->{bcc}, $global_bcc; + my $attachment_filename = $form->generate_attachment_filename(); my $subject = $form->{subject} || $form->generate_email_subject(); - $form->{"fokus"} = $form->{"email"} ? "Form.subject" : "Form.email"; $form->header; my (@dont_hide_key_list, %dont_hide_key, @hidden_keys); @@ -949,7 +1015,7 @@ sub edit_e_mail { subject => $subject, print_options => print_options('inline' => 1), HIDDEN => [ map +{ name => $_, value => $form->{$_} }, @hidden_keys ], - SHOW_BCC => $myconfig{role} eq 'admin' }); + SHOW_BCC => $::auth->assert('email_bcc', 'may fail') }); $main::lxdebug->leave_sub(); } @@ -1044,11 +1110,12 @@ sub print_options { opthash("inline", $form->{SM}{inline}, $locale->text('In-line')) if ($form->{media} eq 'email'); + my $printable_templates = any { $::lx_office_conf{print_templates}->{$_} } qw(latex opendocument); push @MEDIA, grep $_, opthash("screen", $form->{OP}{screen}, $locale->text('Screen')), - ($form->{printers} && scalar @{ $form->{printers} } && $::lx_office_conf{print_templates}->{latex}) ? + ($printable_templates && $form->{printers} && scalar @{ $form->{printers} }) ? opthash("printer", $form->{OP}{printer}, $locale->text('Printer')) : undef, - ($::lx_office_conf{print_templates}->{latex} && !$options{no_queue}) ? + ($printable_templates && !$options{no_queue}) ? opthash("queue", $form->{OP}{queue}, $locale->text('Queue')) : undef if ($form->{media} ne 'email'); @@ -1163,7 +1230,11 @@ sub print_form { _check_io_auth(); - my ($old_form) = @_; + my $defaults = SL::DB::Default->get; + $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates; + $form->{templates} = $defaults->templates; + + my ($old_form, %params) = @_; my $inv = "inv"; my $due = "due"; @@ -1259,6 +1330,14 @@ sub print_form { $form->{label} = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order'); } + $form->{TEMPLATE_DRIVER_OPTIONS} = { }; + if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice request_quotation purchase_order purchase_delivery_order)) { + $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = { + longdescription => 'html', + partnotes => 'html', + }; + } + $form->isblank("email", $locale->text('E-mail address missing!')) if ($form->{media} eq 'email'); $form->isblank("${inv}date", @@ -1273,31 +1352,7 @@ sub print_form { # $locale->text('Quotation Number missing!') # $locale->text('Quotation Date missing!') - # assign number $form->{what_done} = $form->{formname}; - if (!$form->{"${inv}number"} && !$form->{preview} && !$form->{id}) { - $form->{"${inv}number"} = $form->update_defaults(\%myconfig, $numberfld); - if ($form->{media} ne 'email') { - - # get pricegroups for parts - IS->get_pricegroups_for_parts(\%myconfig, \%$form); - - # build up html code for prices_$i - set_pricegroup($form->{rowcount}); - - $form->{rowcount}--; - - call_sub($display_form); - # saving the history - if(!exists $form->{addition}) { - $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber}; - $form->{addition} = "PRINTED"; - $form->save_history; - } - # /saving the history - ::end_of_request(); - } - } &validate_items; @@ -1307,13 +1362,19 @@ sub print_form { my $language_saved = $form->{language_id}; my $payment_id_saved = $form->{payment_id}; + my $delivery_term_id_saved = $form->{delivery_term_id}; my $salesman_id_saved = $form->{salesman_id}; my $cp_id_saved = $form->{cp_id}; + my $taxzone_id_saved = $form->{taxzone_id}; + my $currency_saved = $form->{currency}; call_sub("$form->{vc}_details") if ($form->{vc}); $form->{language_id} = $language_saved; $form->{payment_id} = $payment_id_saved; + $form->{delivery_term_id} = $delivery_term_id_saved; + $form->{taxzone_id} = $taxzone_id_saved; + $form->{currency} = $currency_saved; $form->{"email"} = $saved_email if ($saved_email); $form->{"cc"} = $saved_cc if ($saved_cc); @@ -1336,11 +1397,15 @@ sub print_form { $output_longdates = 1; } + # Store the output number format so that the template modules know + # how to parse the amounts back if requested. + $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat}; + ($form->{employee}) = split /--/, $form->{employee}; # create the form variables if ($form->{type} =~ /_delivery_order$/) { - DO->order_details(); + DO->order_details(\%myconfig, \%$form); } elsif ($order) { OE->order_details(\%myconfig, \%$form); } else { @@ -1354,32 +1419,8 @@ sub print_form { $form->get_shipto(\%myconfig); } - my @a = qw(name street zipcode city country contact); - - my $shipto = 1; - - # if there is no shipto fill it in from billto - foreach my $item (@a) { - if ($form->{"shipto$item"}) { - $shipto = 0; - last; - } - } - - if ($shipto) { - if ( $form->{formname} eq 'purchase_order' - || $form->{formname} eq 'request_quotation') { - $form->{shiptoname} = $myconfig{company}; - $form->{shiptostreet} = $myconfig{address}; - } else { - map { $form->{"shipto$_"} = $form->{$_} } @a; - } - } - $form->{notes} =~ s/^\s+//g; - $form->{templates} = "$myconfig{templates}"; - delete $form->{printer_command}; $form->{language} = $form->get_template_language(\%myconfig); @@ -1403,7 +1444,7 @@ sub print_form { format_dates($output_dateformat, $output_longdates, qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate - datepaid transdate_oe deliverydate_oe + datepaid transdate_oe deliverydate_oe dodate employee_startdate employee_enddate ), grep({ /^datepaid_\d+$/ || @@ -1417,7 +1458,7 @@ sub print_form { reformat_numbers($output_numberformat, 2, qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount - tax taxbase total paid), + tax taxbase total paid payment), grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form}))); reformat_numbers($output_numberformat, undef, @@ -1452,17 +1493,28 @@ sub print_form { $extension = 'xls'; } - my $email_extension = '_email' if (($form->{media} eq 'email') && (-f "$myconfig{templates}/$form->{formname}_email$form->{language}${printer_code}.${extension}")); + # search for the template + my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template( + name => $form->{formname}, + email => $form->{media} eq 'email', + language_id => $form->{language_id}, + printer_id => $form->{printer_id}, + extension => $extension, + ); - $form->{IN} = "$form->{formname}${email_extension}$form->{language}${printer_code}.${extension}"; + if (!defined $template_file) { + $::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)); + } + + $form->{IN} = $template_file; delete $form->{OUT}; if ($form->{media} eq 'printer') { - #$form->{OUT} = "| $form->{printer_command} &>/dev/null"; - $form->{OUT} = "| $form->{printer_command} "; + $form->{OUT} = $form->{printer_command}; + $form->{OUT_MODE} = '|-'; $form->{printed} .= " $form->{formname}"; - $form->{printed} =~ s/^ //; + $form->{printed} =~ s/^ //; } my $printed = $form->{printed}; @@ -1476,31 +1528,45 @@ sub print_form { my $emailed = $form->{emailed}; if ($form->{media} eq 'queue') { - my %queued = map { s|.*/|| } split / /, $form->{queued}; + my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued}; my $filename; + my $suffix = ($form->{postscript}) ? '.ps' : '.pdf'; if ($filename = $queued{ $form->{formname} }) { - $form->{queued} =~ s/\Q$form->{formname} $filename\E//; unlink $::lx_office_conf{paths}->{spool} . "/$filename"; - $filename =~ s/\..*$//g; + delete $queued{ $form->{formname} }; + + $form->{queued} = join ' ', %queued; + $filename =~ s/\..*$//g; + $filename .= $suffix; + $form->{OUT} = $::lx_office_conf{paths}->{spool} . "/$filename"; + $form->{OUT_MODE} = '>'; + } else { - $filename = time; - $filename .= $$; + my $temp_fh; + ($temp_fh, $filename) = File::Temp::tempfile( + 'kivitendo-spoolXXXXXX', + SUFFIX => "$suffix", + DIR => $::lx_office_conf{paths}->{spool}, + UNLINK => 0, + ); + close $temp_fh; + $form->{OUT} = "$filename"; + # use >> for OUT_MODE because file is already created by File::Temp + $form->{OUT_MODE} = '>>'; + # strip directory so that only filename is stored in table status + ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/; } - $filename .= ($form->{postscript}) ? '.ps' : '.pdf'; - $form->{OUT} = ">" . $::lx_office_conf{paths}->{spool} . "/$filename"; - # add type $form->{queued} .= " $form->{formname} $filename"; - $form->{queued} =~ s/^ //; } my $queued = $form->{queued}; # saving the history if(!exists $form->{addition}) { - $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber}; + $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"}; if($form->{media} =~ /printer/) { $form->{addition} = "PRINTED"; } @@ -1517,6 +1583,17 @@ sub print_form { } # /saving the history + # prepare meta information for template introspection + $form->{template_meta} = { + formname => $form->{formname}, + language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef), + format => $form->{format}, + media => $form->{media}, + extension => $extension, + printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef), + today => DateTime->today, + }; + $form->parse_template(\%myconfig); $form->{callback} = ""; @@ -1565,7 +1642,10 @@ sub print_form { ($form->{media} eq 'printer') ? $locale->text('sent to printer') : $locale->text('emailed to') . " $form->{email}"; - $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|); + + if (!$params{no_redirect}) { + $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|); + } } if ($form->{printing}) { call_sub($display_form); @@ -1615,184 +1695,39 @@ sub post_as_new { sub ship_to { $main::lxdebug->enter_sub(); - my $form = $main::form; - my %myconfig = %main::myconfig; - my $locale = $main::locale; - my $cgi = $main::cgi; - _check_io_auth(); - if ($form->{second_run}) { - $form->{print_and_post} = 0; - } - - my $title = $form->{title}; - $form->{title} = $locale->text('Ship to'); - - map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } - qw(exchangerate creditlimit creditremaining); - - my @shipto_vars = - qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry - shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail - shiptodepartment_1 shiptodepartment_2); - - my @addr_vars = - (qw(name department_1 department_2 street zipcode city country - contact email phone fax)); - - # get details for name - call_sub("$form->{vc}_details", @addr_vars); - - my $number = - ($form->{vc} eq 'customer') - ? $locale->text('Customer Number') - : $locale->text('Vendor Number'); - - # sieht nicht nett aus, funktioniert aber - # das vorausgewählte select-feld wird über shiptocp_gender - # entsprechend vorbelegt - my $selected_m=''; - my $selected_f=''; - if ($form->{shiptocp_gender} eq 'm') { - $selected_m='selected'; - $selected_f=''; - } elsif ($form->{shiptocp_gender} eq 'f') { - $selected_m=''; - $selected_f='selected'; - } + $::form->{print_and_post} = 0 if $::form->{second_run}; - # get pricegroups for parts - IS->get_pricegroups_for_parts(\%myconfig, \%$form); + map { $::form->{$_} = $::form->parse_amount(\%::myconfig, $::form->{$_}) } qw(exchangerate creditlimit creditremaining); - # build up html code for prices_$i - set_pricegroup($form->{rowcount}); + # get details for customer/vendor + call_sub($::form->{vc} . "_details", qw(name department_1 department_2 street zipcode city country contact email phone fax), $::form->{vc} . "number"); - my $nextsub = ($form->{display_form}) ? $form->{display_form} : "display_form"; + $::form->{rowcount}--; - $form->{rowcount}--; + my @shipto_vars = qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry + shiptocontact shiptocp_gender shiptophone shiptofax shiptoemail + shiptodepartment_1 shiptodepartment_2); + my $previous_form = $::auth->save_form_in_session(skip_keys => [ @shipto_vars, qw(header shipto_id) ]); + $::form->{title} = $::locale->text('Ship to'); + $::form->header; - $form->header; + my $vc_obj = ($::form->{vc} eq 'customer' ? "SL::DB::Customer" : "SL::DB::Vendor")->new(id => $::form->{$::form->{vc} . "_id"})->load; - print qq| - - -
- - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| - . $locale->text('Billing Address') . qq|| - . $locale->text('Shipping Address') . qq|
$number$form->{"$form->{vc}number"}
| . $locale->text('Company Name') . qq|$form->{name}
| . $locale->text('Department') . qq|$form->{department_1}
 $form->{department_2}
| . $locale->text('Street') . qq|$form->{street}
| . $locale->text('Zipcode') . qq|$form->{zipcode}
| . $locale->text('City') . qq|$form->{city}
| . $locale->text('Country') . qq|$form->{country}
| . $locale->text('Contact') . qq|$form->{contact}
| . $locale->text('Gender') . qq| -
| . $locale->text('Phone') . qq|$form->{phone}
| . $locale->text('Fax') . qq|$form->{fax}
| . $locale->text('E-mail') . qq|$form->{email}
-
-| . $cgi->hidden("-name" => "nextsub", "-value" => $nextsub); -; - - - - # delete shipto - map({ delete $form->{$_} } (@shipto_vars, qw(header shipto_id))); - $form->{title} = $title; - - foreach my $key (keys %$form) { - next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key})); - $form->{$key} =~ s/\"/"/g; - print qq|\n|; - } - - print qq| - -
- -
- -
- - - -|; + print $::form->parse_html_template('io/ship_to', { previousform => $previous_form, + nextsub => $::form->{display_form} || 'display_form', + vc_obj => $vc_obj, + }); $main::lxdebug->leave_sub(); } +sub ship_to_entered { + $::auth->restore_form_from_session(delete $::form->{previousform}); + call_sub($::form->{nextsub}); +} + sub relink_accounts { $main::lxdebug->enter_sub(); @@ -1824,7 +1759,7 @@ sub set_duedate { my $invdate = $form->{invdate} eq 'undefined' ? undef : $form->{invdate}; my $duedate = $form->get_duedate(\%myconfig, $invdate); - print $form->ajax_response_header() . $duedate; + print $form->ajax_response_header() . ($duedate || $invdate); $main::lxdebug->leave_sub(); } @@ -1844,6 +1779,7 @@ sub _update_part_information { my $info = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { }; $form->{"partunit_${i}"} = $info->{unit}; + $form->{"weight_$i"} = $info->{weight}; } $main::lxdebug->leave_sub(); @@ -1923,30 +1859,193 @@ sub _render_custom_variables_inputs { my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id}); + # get partsgroup_id from part + my $partsgroup_id; + if ($params{part_id}) { + $partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id; + } + my $num_visible_cvars = 0; foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) { $cvar->{valid} = $params{part_id} && $valid->($cvar->{id}); + # set partsgroup filter + my $partsgroup_filtered = 0; + if ($cvar->{flag_partsgroup_filter}) { + if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) { + $partsgroup_filtered = 1; + } + } + + my $hide_non_editable = 1; + + my $show = 0; my $description = ''; - if ($cvar->{flag_editable} && $cvar->{valid}) { + if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) { $num_visible_cvars++; $description = $cvar->{description} . ' '; + $show = 1; } + my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}"; + push @{ $params{ROW2} }, { - line_break => $num_visible_cvars == 1, + line_break => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)), description => $description, cvar => 1, render_options => { - hide_non_editable => 1, + hide_non_editable => $hide_non_editable, var => $cvar, name_prefix => 'ic_', name_postfix => "_$params{row}", valid => $cvar->{valid}, - value => $form->{"ic_cvar_" . $cvar->{name} . "_$params{row}"}, + value => CVar->parse($::form->{$form_key}, $cvar), + partsgroup_filtered => $partsgroup_filtered, } }; } $main::lxdebug->leave_sub(2); } + +sub _remove_billed_or_delivered_rows { + my (%params) = @_; + + croak "Missing parameter 'quantities'" if !$params{quantities}; + + my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form }; + my @new_rows; + + my $make_key = sub { + my ($row) = @_; + return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"}; + my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"}; + return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"}; + }; + + my $removed_rows = 0; + my $row = 0; + while ($row < $::form->{rowcount}) { + $row++; + next unless $::form->{"id_$row"}; + + my $parts_id = $::form->{"id_$row"}; + my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor; + + my $key = $make_key->($row); + my $sub_qty = min($base_qty, $params{quantities}->{$key}); + $params{quantities}->{$key} -= $sub_qty; + + if (!$sub_qty || ($sub_qty != $base_qty)) { + $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor); + push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields }; + + } else { + $removed_rows++; + } + } + + $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount}); + $::form->{rowcount} -= $removed_rows; +} + +# TODO: both of these are makeshift so that price sources can operate on rdbo objects. if +# this ever gets rewritten in controller style, throw this out +sub _make_record_item { + my ($row) = @_; + + my $class = { + sales_order => 'OrderItem', + purchase_order => 'OrderItem', + sales_quotation => 'OrderItem', + request_quotation => 'OrderItem', + invoice => 'InvoiceItem', + credit_note => 'InvoiceItem', + purchase_invoice => 'InvoiceItem', + purchase_delivery_order => 'DeliveryOrderItem', + sales_delivery_order => 'DeliveryOrderItem', + }->{$::form->{type}}; + + return unless $class; + + $class = 'SL::DB::' . $class; + + eval "require $class"; + + my $obj = $::form->{"orderitems_id_$row"} + ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{"orderitems_id_$row"}) + : $class->new; + + for my $method (apply { s/_$row$// } grep { /_$row$/ } keys %$::form) { + next unless $obj->meta->column($method); + if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) { + $obj->${\"$method\_as_date"}($::form->{"$method\_$row"}); + } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) { + $obj->${\"$method\_as_number"}($::form->{"$method\_$row"}); + } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) { + $obj->$method(!!$::form->{$method}); + } else { + $obj->$method($::form->{"$method\_$row"}); + } + } + + if ($::form->{"id_$row"}) { + $obj->part(SL::DB::Part->load_cached($::form->{"id_$row"})); + } + + return $obj; +} + +sub _make_record { + my $class = { + sales_order => 'Order', + purchase_order => 'Order', + sales_quotation => 'Order', + request_quotation => 'Order', + purchase_delivery_order => 'DeliveryOrder', + sales_delivery_order => 'DeliveryOrder', + }->{$::form->{type}}; + + if ($::form->{type} =~ /invoice|credit_note/) { + $class = $::form->{vc} eq 'customer' ? 'Invoice' + : $::form->{vc} eq 'vendor' ? 'PurchaseInvoice' + : do { die 'unknown invoice type' }; + } + + return unless $class; + + $class = 'SL::DB::' . $class; + + eval "require $class"; + + my $obj = $::form->{id} + ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{id}) + : $class->new; + + for my $method (keys %$::form) { + next unless $obj->can($method); + next unless $obj->meta->column($method); + + if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) { + $obj->${\"$method\_as_date"}($::form->{$method}); + } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) { + $obj->${\"$method\_as_number"}($::form->{$method}); + } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) { + $obj->$method(!!$::form->{$method}); + } else { + $obj->$method($::form->{$method}); + } + } + + my @items; + for my $i (1 .. $::form->{rowcount}) { + next unless $::form->{"id_$i"}; + push @items, _make_record_item($i); + } + + $obj->items(@items) if @items; + $obj->is_sales(!!$obj->customer_id) if $class eq 'SL::DB::DeliveryOrder'; + + return $obj; +} +