1 #=====================================================================
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
15 # Author: Dieter Simader
16 # Email: dsimader@sql-ledger.org
17 # Web: http://www.sql-ledger.org
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.
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., 51 Franklin Street, Fifth Floor, Boston,
34 #######################################################################
36 # common routines used in is, ir, oe
38 #######################################################################
42 use List::MoreUtils qw(any uniq apply);
43 use List::Util qw(sum min max first);
44 use List::UtilsBy qw(sort_by uniq_by);
49 use SL::Controller::Base;
51 use SL::Locale::String qw(t8);
56 use SL::Presenter::Part;
57 use SL::Presenter::Chart;
58 use SL::Presenter::Tag;
59 use SL::Util qw(trim);
65 use SL::DB::DeliveryOrder::TypeData qw();
70 use SL::Helper::CreatePDF;
71 use SL::Helper::Flash;
72 use SL::Helper::PrintOptions;
73 use SL::Helper::ShippedQty;
75 require "bin/mozilla/common.pl";
79 # any custom scripts for this one
80 if (-f "bin/mozilla/custom_io.pl") {
81 eval { require "bin/mozilla/custom_io.pl"; };
83 if (-f "bin/mozilla/$::myconfig{login}_io.pl") {
84 eval { require "bin/mozilla/$::myconfig{login}_io.pl"; };
91 # this is for our long dates
92 # $locale->text('January')
93 # $locale->text('February')
94 # $locale->text('March')
95 # $locale->text('April')
96 # $locale->text('May ')
97 # $locale->text('June')
98 # $locale->text('July')
99 # $locale->text('August')
100 # $locale->text('September')
101 # $locale->text('October')
102 # $locale->text('November')
103 # $locale->text('December')
105 # this is for our short month
106 # $locale->text('Jan')
107 # $locale->text('Feb')
108 # $locale->text('Mar')
109 # $locale->text('Apr')
110 # $locale->text('May')
111 # $locale->text('Jun')
112 # $locale->text('Jul')
113 # $locale->text('Aug')
114 # $locale->text('Sep')
115 # $locale->text('Oct')
116 # $locale->text('Nov')
117 # $locale->text('Dec')
123 $main::auth->assert('part_service_assembly_edit | vendor_invoice_edit | sales_order_edit | invoice_edit |' .
124 'request_quotation_edit | sales_quotation_edit | purchase_order_edit | ' .
125 'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details');
128 ########################################
129 # Eintrag fuer Version 2.2.0 geaendert #
130 # neue Optik im Rechnungsformular #
131 ########################################
133 $main::lxdebug->enter_sub();
135 my $form = $main::form;
136 my %myconfig = %main::myconfig;
137 my $locale = $main::locale;
138 my $cgi = $::request->{cgi};
142 my ($stock_in_out, $stock_in_out_title);
144 my $defaults = AM->get_defaults();
145 $form->{show_weight} = $defaults->{show_weight};
146 $form->{weightunit} = $defaults->{weightunit};
148 my $is_purchase = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
149 my $is_delivery_order = $form->{type} =~ /_delivery_order$/;
150 my $is_quotation = $form->{type} =~ /_quotation$/;
151 my $is_invoice = $form->{type} =~ /invoice/;
152 my $is_credit_note = $form->{type} =~ /credit_note/;
153 my $is_s_p_order = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
154 my $show_ship_missing = $is_s_p_order && $::instance_conf->get_sales_purchase_order_ship_missing_column;
155 my $show_marge = (!$is_purchase || $is_invoice || $is_credit_note) && !$is_delivery_order;
157 if ($is_delivery_order) {
158 if ($form->{type} eq 'sales_delivery_order') {
159 $stock_in_out_title = $locale->text('Release From Stock');
160 $stock_in_out = 'out';
162 $stock_in_out_title = $locale->text('Transfer To Stock');
163 $stock_in_out = 'in';
166 retrieve_partunits();
170 my @header_sort = qw(
171 runningnumber partnumber vendor_partnumber type_and_classific description ship ship_missing qty price_factor
172 unit weight price_source sellprice discount linetotal
175 # position of serialnr is used below!
177 tax_chart tax serialnr projectnr reqdate subtotal recurring_billing_mode marge listprice lastcost onhand
180 # serialnr is important for delivery_orders
181 if ($form->{type} eq 'sales_delivery_order') {
182 splice @row2_sort, 0, 3;
183 splice @header_sort, 4, 0, "serialnr";
187 runningnumber => { width => 5, value => $locale->text('No.'), display => 1, },
188 partnumber => { width => 8, value => $locale->text('Number'), display => 1, },
190 => { width => 2, value => $locale->text('Type'), display => 1, },
191 description => { width => 30, value => $locale->text('Part Description'), display => 1, },
192 ship => { width => 5, value => $locale->text('Delivered'), display => $is_s_p_order, },
193 ship_missing => { width => 5, value => $locale->text('Not delivered'), display => $show_ship_missing, },
194 qty => { width => 5, value => $locale->text('Qty'), display => 1, },
195 price_factor => { width => 5, value => $locale->text('Price Factor'), display => !$is_delivery_order, },
196 unit => { width => 5, value => $locale->text('Unit'), display => 1, },
197 weight => { width => 5, value => $locale->text('Weight'), display => $defaults->{show_weight}, },
198 serialnr => { width => 10, value => $locale->text('Serial No.'), display => !$is_quotation },
199 projectnr => { width => 10, value => $locale->text('Project'), display => 1, },
200 price_source => { width => 5, value => $locale->text('Price Source'), display => !$is_delivery_order, },
201 sellprice => { width => 15, value => $locale->text('Price'), display => !$is_delivery_order, },
202 discount => { width => 5, value => $locale->text('Discount'), display => !$is_delivery_order, },
203 linetotal => { width => 10, value => $locale->text('Extended'), display => !$is_delivery_order, },
204 bin => { width => 10, value => $locale->text('Bin'), display => 0, },
205 stock_in_out => { width => 10, value => $stock_in_out_title, display => $is_delivery_order, },
206 reqdate => { value => $locale->text('Reqdate'), display => $is_s_p_order || $is_delivery_order || $is_invoice, },
207 subtotal => { value => $locale->text('Subtotal'), display => 1, },
208 recurring_billing_mode => { value => $locale->text('Recurring billing'), display => $form->{type} eq 'sales_order', },
209 marge => { value => $locale->text('Ertrag'), display => $show_marge, },
210 listprice => { value => $locale->text('LP'), display => $show_marge, },
211 lastcost => { value => $locale->text('EK'), display => $show_marge, },
212 onhand => { value => $locale->text('On Hand'), display => 1, },
213 vendor_partnumber => { width => 8, value => $locale->text('Vendor Part Number'), display => $is_delivery_order && $is_purchase, },
214 tax_chart => { value => "", display => $is_purchase && $is_invoice },
215 tax => { value => $locale->text('Tax'), display => $is_purchase && $is_invoice },
216 orderer => { width => 10, value => $locale->text('Orderer'), display => 1, },
218 my @HEADER = map { $column_def{$_} } @header_sort;
221 my $all_units = AM->retrieve_units(\%myconfig, $form);
223 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
226 $form->{invsubtotal} = 0;
227 map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
230 $myconfig{show_form_details} = 1 unless (defined($myconfig{show_form_details}));
231 $form->{show_details} = $myconfig{show_form_details} unless (defined($form->{show_details}));
234 # translations, unused commented out
235 my $deliverydate = $locale->text('Required by');
238 my %align = map { $_ => 'right' } qw(qty ship right discount linetotal stock_in_out weight ship_missing);
239 my %nowrap = map { $_ => 1 } qw(description unit price_source);
241 $form->{marge_total} = 0;
242 $form->{sellprice_total} = 0;
243 $form->{lastcost_total} = 0;
244 $form->{totalweight} = 0;
245 my %projectnumber_labels = ();
246 my @projectnumber_values = ("");
248 foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
249 push(@projectnumber_values, $item->{"id"});
250 $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
253 _update_part_information();
254 _update_ship() if ($is_s_p_order);
255 _update_custom_variables();
259 my $record = _make_record();
263 for my $i (1 .. $numrows) {
264 my %column_data = ();
266 my $record_item = $record->id && $record->items ? $record->items->[$i-1] : _make_record_item($i);
269 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
270 qw(qty discount sellprice lastcost price_new price_old)
271 unless ($form->{simple_save});
273 if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
274 $form->{"sellprice_$i"} = $form->{"price_new_$i"};
278 $form->{"unit_old_$i"} ||= $form->{"unit_$i"};
279 $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
281 if ( !$all_units->{$form->{"selected_unit_$i"}} # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
282 || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
283 $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"}; # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
286 $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
287 $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
288 $form->{"unit_old_$i"} = $form->{"selected_unit_$i"};
290 my $this_unit = $form->{"unit_$i"};
291 $this_unit = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
293 if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
294 my @values = ('', map { $_->{id} } @{ $form->{ALL_PRICE_FACTORS} });
295 my %labels = map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
297 $column_data{price_factor} =
298 NTI($cgi->popup_menu('-name' => "price_factor_id_$i",
299 '-default' => $form->{"price_factor_id_$i"},
300 '-values' => \@values,
301 '-labels' => \%labels,
302 '-style' => 'width:90px'));
304 $column_data{price_factor} = ' ';
306 $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
308 $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
311 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
312 #is shown for lastcost and sellprice.
313 my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
314 $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
316 my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || 1;
317 my $discount = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * $form->{"discount_$i"} / 100 / $price_factor, 2);
318 my $linetotal = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
319 my $rows = $form->numtextrows($form->{"description_$i"}, 30, 6);
321 # quick delete single row
322 $column_data{runningnumber} = q|<a onclick= "$('#partnumber_| . $i . q|').val(''); $('#update_button').click();">| .
323 q|<img class="icon-delete" alt="| . $locale->text('Remove') . q|"></a> |;
324 $column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5, -value => $i); # HuT
327 $column_data{partnumber} = $cgi->textfield(-name => "partnumber_$i", -id => "partnumber_$i", -size => 12, -value => $form->{"partnumber_$i"});
328 $column_data{vendor_partnumber} = $form->{"vendor_partnumber_$i"};
329 $column_data{type_and_classific} = SL::Presenter::Part::type_abbreviation($form->{"part_type_$i"}).
330 SL::Presenter::Part::classification_abbreviation($form->{"classification_id_$i"}) if $form->{"id_$i"};
331 $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
332 ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
333 : $cgi->textfield(-name => "description_$i", -id => "description_$i", -value => $form->{"description_$i"}, -size => 30))
334 . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
336 my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
338 $column_data{qty} = $cgi->textfield(-name => "qty_$i", -size => 5, -class => "numeric", -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
339 $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_dialog('qty_$i', '', 'formel_$i', '')", -value => $locale->text('*/'))
340 . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"})
341 if $form->{"formel_$i"};
343 $column_data{ship} = '';
344 if ($form->{"id_$i"}) {
345 my $ship_qty = $form->{"ship_$i"} * 1;
346 $ship_qty *= $all_units->{$form->{"partunit_$i"}}->{factor};
347 $ship_qty /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
349 $column_data{ship} = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"}
350 . $cgi->hidden(-name => "ship_$i", -value => $form->{"ship_$i"}, $qty_dec);
352 my $ship_missing_qty = $form->{"qty_$i"} - $ship_qty;
353 my $ship_missing_amount = $form->round_amount($ship_missing_qty * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
355 $column_data{ship_missing} = $form->format_amount(\%myconfig, $ship_missing_qty) . ' ' . $form->{"unit_$i"} . '; ' . $form->format_amount(\%myconfig, $ship_missing_amount, $decimalplaces);
358 $column_data{linetotal} = $form->format_amount(\%myconfig, $linetotal, 2);
359 $column_data{bin} = $form->{"bin_$i"};
361 $column_data{weight} = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
363 my $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
364 my $discount_value = $form->format_amount(\%myconfig, $form->{"discount_$i"});
367 if ($form->{"id_${i}"} && !$is_delivery_order) {
368 my $price_source = SL::PriceSource->new(record_item => $record_item, record => $record);
369 $price = $price_source->price_from_source($::form->{"active_price_source_$i"});
370 my $discount = $price_source->discount_from_source($::form->{"active_discount_source_$i"});
371 my $best_price = $price_source->best_price;
372 my $best_discount = $price_source->best_discount;
373 $column_data{price_source} .= $cgi->button(-value => $price->source_description, -onClick => "kivi.io.price_chooser($i)");
374 if ($price->source) {
375 $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->invalid, title => $price->invalid }) if $price->invalid;
376 $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->missing, title => $price->missing }) if $price->missing;
377 if (!$price->missing && !$price->invalid) {
378 $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 > 0.01;
379 $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 < -0.01;
380 $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;
383 if ($discount->source) {
384 $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->invalid, title => $discount->invalid }) if $discount->invalid;
385 $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->missing, title => $discount->missing }) if $discount->missing;
386 if (!$discount->missing && !$discount->invalid) {
387 $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 > 0.01;
388 $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 < -0.01;
389 $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;
394 my $right_to_edit_prices = (!$is_purchase && $main::auth->assert('sales_edit_prices', 1)) || ($is_purchase && $main::auth->assert('purchase_edit_prices', 1));
395 my $edit_prices = $right_to_edit_prices && (!$::form->{"active_price_source_$i"} || !$price || $price->editable);
396 my $edit_discounts = $right_to_edit_prices && !$::form->{"active_discount_source_$i"};
397 $column_data{sellprice} = (!$edit_prices)
398 ? $cgi->hidden( -name => "sellprice_$i", -id => "sellprice_$i", -value => $sellprice_value) . $sellprice_value
399 : $cgi->textfield(-name => "sellprice_$i", -id => "sellprice_$i", -size => 10, -class => "numeric", -value => $sellprice_value);
400 $column_data{discount} = (!$edit_discounts)
401 ? $cgi->hidden( -name => "discount_$i", -id => "discount_$i", -value => $discount_value) . $discount_value . ' %'
402 : $cgi->textfield(-name => "discount_$i", -id => "discount_$i", -size => 3, -"data-validate" => "number", -class => "numeric", -value => $discount_value);
404 if ($is_delivery_order) {
405 $column_data{stock_in_out} = calculate_stock_in_out($i);
409 if ($is_purchase && $is_invoice) { #only calc if used
410 my ($tax_chart_id, $chart_title, $chart_picker);
411 if ($record_item && $record_item->part && ($record_item->part->type eq 'part')) {
412 my $tax_chart_type = $form->{"tax_chart_type_$i"};
414 $::instance_conf->get_inventory_system eq 'periodic' ? 'expense'
416 $tax_chart_id = $form->{"${tax_chart_type}_chart_id_$i"};
418 $chart_title = SL::Presenter::Tag::select_tag("tax_chart_type_$i", [
419 {value => 'expense', title => $locale->text('Expense Account')},
420 {value => 'inventory', title => $locale->text('Inventory Account')},
422 value_key => 'value', title_key => 'title',
423 default => $tax_chart_type,
424 onchange => "kivi.io.update_tax_chart_picker(this.value, $i)",
428 SL::Presenter::Tag::html_tag('span',
429 SL::Presenter::Chart::chart_picker(
430 "expense_chart_id_$i", $form->{"expense_chart_id_$i"},
431 type => "AP_amount", style => "width: 150px"),
432 id => "expense_chart_span_$i",
433 style => $tax_chart_type eq 'expense' ? '' : 'display:none',
436 SL::Presenter::Tag::html_tag('span',
437 SL::Presenter::Chart::chart_picker(
438 "inventory_chart_id_$i", $form->{"inventory_chart_id_$i"},
439 type => "IC", style => "width: 150px"),
440 id => "inventory_chart_span_$i",
441 style => $tax_chart_type eq 'inventory' ? '' : 'display:none',
444 $tax_chart_id = $form->{"expense_chart_id_$i"};
445 $chart_title = $locale->text('Expense Account');
446 $chart_picker = SL::Presenter::Chart::chart_picker(
447 "expense_chart_id_$i", $form->{"expense_chart_id_$i"},
448 type => "AP_amount", style => "width: 150px");
450 # change tax dropdown after change
451 my $js_set_on_select_item = '<script type="text/javascript">
453 $(document).ready(function() {
454 $("#expense_chart_id_' . $i . '").on("set_item:ChartPicker", function(e, item) {
455 kivi.io.update_tax_ids(this);
457 $("#inventory_chart_id_' . $i . '").on("set_item:ChartPicker", function(e, item) {
458 kivi.io.update_tax_ids(this);
464 $column_data{tax_chart} = SL::Presenter::Tag::html_tag('span',
465 $chart_title . $chart_picker . $js_set_on_select_item);
467 my $tax_value_title_sub = sub {
471 $item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
476 if ($form->{"expense_chart_id_$i"}) {
477 @taxes = IO->get_active_taxes_for_chart($tax_chart_id,
478 $form->{"reqdate_$i"} // $form->{deliverydate} // $form->{transdate});
480 # tax_id_ is used in io.js->update_tax_ids
481 $column_data{tax} = SL::Presenter::Tag::select_tag(
482 "tax_id_$i", \@taxes, default => $form->{"tax_id_$i"},
483 value_title_sub => $tax_value_title_sub,
484 style => "width: 100px");
487 $column_data{serialnr} = qq|<input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}" data-validate="trimmed_whitespaces">|;
488 $column_data{projectnr} = NTI($cgi->popup_menu(
489 '-name' => "project_id_$i",
490 '-values' => \@projectnumber_values,
491 '-labels' => \%projectnumber_labels,
492 '-default' => $form->{"project_id_$i"}
494 $column_data{reqdate} = qq|<input name="reqdate_$i" size="11" data-validate="date" value="$form->{"reqdate_$i"}">|;
495 $column_data{subtotal} = sprintf qq|<input type="checkbox" name="subtotal_$i" value="1" %s>|, $form->{"subtotal_$i"} ? 'checked' : '';
496 $column_data{recurring_billing_mode} = SL::Presenter::Tag::select_tag(
497 "recurring_billing_mode_$i",
498 [[ 'always', $::locale->text('always') ], [ 'once', $::locale->text('once') ], [ 'never', $::locale->text('never') ]],
499 default => $::form->{"recurring_billing_mode_$i"} || 'always',
503 $column_data{orderer} = qq|: $form->{"orderer_$i"}|;
505 # begin marge calculations
506 $form->{"lastcost_$i"} *= 1;
507 $form->{"marge_percent_$i"} = 0;
511 if ( $form->{taxincluded} and $form->{"qty_$i"} * 1 and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
512 # if we use taxincluded we need to calculate the marge from the net_value
513 # all the marge calculations are based on linetotal which we need to
514 # convert to net first
516 # there is no direct form value for the tax_rate of the item, but
517 # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
518 # gives the tax percentage (e.g. 0.19)
519 $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
521 $real_sellprice = $linetotal;
523 my $real_lastcost = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"}, 2);
524 my $marge_percent_warn = $myconfig{marge_percent_warn} * 1 || 15;
525 my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
527 if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
528 $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
529 $marge_color = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
532 $form->{"marge_absolut_$i"} = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
533 $form->{"marge_total"} += $form->{"marge_absolut_$i"};
534 $form->{"lastcost_total"} += $real_lastcost;
535 $form->{"sellprice_total"} += $real_sellprice;
537 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
539 $column_data{marge} = sprintf qq|<font %s>%s %s%%</font>|,
540 $marge_color, $form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"};
541 $column_data{listprice} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2);
542 $column_data{lastcost} = sprintf qq|<input size="5" name="lastcost_$i" value="%s">|, $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
543 # / marge calculations ending
545 # Calculate total weight
546 $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
549 if ($form->{"id_$i"}) {
550 my $part = IC->get_basic_part_info(id => $form->{"id_$i"});
551 my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
552 $column_data{onhand} = sprintf "<font %s>%s %s</font>",
554 $form->format_amount(\%myconfig, $part->{onhand}, 2),
559 my @ROW1 = map { { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} } } grep { $column_def{$_}{display} } @header_sort;
560 my @ROW2 = map { { value => sprintf "<b>%s</b> %s", $column_def{$_}{value}, $column_data{$_} } } grep { $column_def{$_}{display} } @row2_sort;
563 # add hidden ids for persistent (item|invoice)_ids and previous (converted_from*) ids
565 push @hidden_vars, qw(orderitems_id converted_from_orderitems_id);
568 push @hidden_vars, qw(orderitems_id converted_from_orderitems_id converted_from_invoice_id);
571 push @hidden_vars, qw(invoice_id converted_from_orderitems_id converted_from_delivery_order_items_id converted_from_invoice_id);
573 if ($::form->{type} =~ /credit_note/) {
574 push @hidden_vars, qw(invoice_id converted_from_invoice_id converted_from_reclamation_items_id);
576 if ($is_delivery_order) {
577 map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
578 push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost);
579 push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
580 push @hidden_vars, qw(delivery_order_items_id converted_from_orderitems_id converted_from_delivery_order_items_id has_sernumber);
583 my @HIDDENS = map { value => $_}, (
584 $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
585 $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
586 map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
587 (qw(bo price_old id inventory_accno bin partsgroup partnotes active_price_source active_discount_source
589 income_accno expense_accno listprice part_type taxaccounts ordnumber donumber transdate cusordnumber
590 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
593 map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
595 $form->{invsubtotal} += $linetotal;
597 # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
598 _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
600 my $colspan = scalar @ROW1;
601 push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, obj => $record_item };
604 $form->{totalweight} = $totalweight;
606 print $form->parse_html_template('oe/sales_order', { ROWS => \@ROWS,
610 if (abs($form->{sellprice_total} * 1) >= 0.01) {
611 $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
614 $main::lxdebug->leave_sub();
617 sub setup_io_select_item_action_bar {
620 for my $bar ($::request->layout->get('actionbar')) {
624 submit => [ '#form' ],
625 accesskey => 'enter',
632 $main::lxdebug->enter_sub();
635 my $mode = $params{mode} || croak "Missing parameter 'mode'";
636 my $pre_entered_qty = $params{pre_entered_qty} || 1;
639 setup_io_select_item_action_bar();
641 my $previous_form = $::auth->save_form_in_session(form => $::form);
642 $::form->{title} = $::myconfig{item_multiselect} ?
643 $::locale->text('Set count for one or more of the items to select them'):
644 $::locale->text('Select from one of the items below');
647 my @item_list = map {
648 # maybe there is a better backend function or way to calc
649 $_->{display_sellprice} = ($_->{price_factor}) ? $_->{sellprice} / $_->{price_factor} : $_->{sellprice};
651 } @{ $::form->{item_list} };
653 # delete action variable
654 delete @{$::form}{qw(action item_list)};
656 print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
658 ITEM_LIST => \@item_list,
659 IS_ASSEMBLY => $mode eq 'IC',
660 IS_PURCHASE => $mode eq 'IS',
661 PRE_ENTERED_QTY => $pre_entered_qty, });
663 $main::lxdebug->leave_sub();
668 # this function is used for adding parts to records (mode = IR/IS)
669 # and to assemblies (mode = IC)
671 $main::lxdebug->enter_sub();
673 my $form = $main::form;
674 my %myconfig = %main::myconfig;
678 $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
680 my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
681 my $row_key = $mode eq 'IC' ? 'assembly_rows' : 'rowcount';
682 my $curr_row = $form->{ $row_key };
686 if ($myconfig{item_multiselect}) {
689 next unless $form->{$_};
690 next unless /^select_qty_(\d+)/;
691 $multi_items{"id_${row}"} = $1;
692 $multi_items{"qty_${row}"} = $form->{$_};
695 $form->{$_} = $multi_items{$_} for keys %multi_items;
697 $form->{"id_${row}"} = delete($form->{select_item_id}) || croak 'Missing item selection ID';
701 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
702 qw(sellprice weight);
704 if ( $mode eq 'IC' ) {
706 # the qty variables of the existing assembly items are all still formatted, so we parse them here
707 # including the qty of the just added part
708 $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for (1 .. $row - 1);
710 if ($myconfig{item_multiselect}) {
711 # other modes and multiselection:
712 # parse all newly entered qtys
713 $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for ($curr_row .. $row - 1);
717 for my $i ($curr_row .. $row - 1) {
718 $form->{ $row_key } = $i;
720 my $id = $form->{"id_${i}"};
722 delete $form->{item_list};
725 IS->retrieve_item(\%myconfig, \%$form);
726 } elsif ($mode eq 'IR') {
727 IR->retrieve_item(\%myconfig, \%$form);
728 } elsif ($mode eq 'IC') {
729 IC->assembly_item(\%myconfig, \%$form);
731 croak "Invalid item selection mode '${mode}'";
734 my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
736 # if there was a price entered, override it
738 unless ( $mode eq 'IC' ) {
739 $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
743 qw(id partnumber description sellprice listprice inventory_accno
744 income_accno expense_accno bin unit weight part_type taxaccounts
745 partsgroup formel longdescription not_discountable partnotes lastcost
746 price_factor_id price_factor);
748 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
749 push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
751 map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
753 if (my $record = _make_record()) {
754 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
755 my $best_price = $price_source->best_price;
758 $::form->{"sellprice_$i"} = $best_price->price;
759 $::form->{"active_price_source_$i"} = $best_price->source;
762 my $best_discount = $price_source->best_discount;
764 if ($best_discount) {
765 $::form->{"discount_$i"} = $best_discount->discount;
766 $::form->{"active_discount_source_$i"} = $best_discount->source;
770 $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
772 if ($form->{"part_payment_id_$i"} ne "") {
773 $form->{payment_id} = $form->{"part_payment_id_$i"};
776 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
778 my $decimalplaces = ($dec > 2) ? $dec : 2;
781 $form->{"sellprice_$i"} = $sellprice;
784 # if there is an exchange rate adjust sellprice
785 if (($form->{exchangerate} * 1) != 0) {
786 $form->{"sellprice_$i"} /= $form->{exchangerate};
787 $form->{"sellprice_$i"} =
788 $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
792 # at this stage qty of newly added part needs to be have been parsed
793 $form->{weight} += ($form->{"weight_$i"} * $form->{"qty_$i"});
795 if ($form->{"not_discountable_$i"}) {
796 $form->{"discount_$i"} = 0;
800 $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"}) * $form->{"qty_$i"};
801 map { $form->{"${_}_base"} += $amount } (split / /, $form->{"taxaccounts_$i"});
802 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
804 $form->{creditremaining} -= $amount;
805 $form->{"runningnumber_$i"} = $i;
810 $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
811 } qw(sellprice lastcost qty) if $form->{part_type} ne 'assembly';
812 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0) if $form->{part_type} ne 'assembly';
814 delete $form->{nextsub};
820 $main::lxdebug->leave_sub();
826 my $price = $::form->{vc} eq 'customer' ? 'sellprice_as_number' : 'lastcost_as_number';
827 my $previousform = $::auth->save_form_in_session;
828 my $callback = build_std_url("action=return_from_new_item", "previousform=$previousform");
829 my $i = $::form->{rowcount};
831 my $parts_classification_type = $::form->{vc} eq 'customer' ? 'sales' : 'purchases';
834 push @HIDDENS, { 'name' => 'callback', 'value' => $callback };
835 push @HIDDENS, map +{ 'name' => $_, 'value' => $::form->{$_} }, qw(rowcount vc);
836 push @HIDDENS, map +{ 'name' => "part.$_", 'value' => $::form->{"${_}_$i"} }, qw(partnumber description unit price_factor_id);
837 push @HIDDENS, { 'name' => "part.$price", 'value' => $::form->{"sellprice_$i"} };
838 push @HIDDENS, { 'name' => "part.notes", 'value' => $::form->{"longdescription_$i"} };
840 push @HIDDENS, { 'name' => "parts_classification_type", 'value' => $parts_classification_type };
843 print $::form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
846 sub return_from_new_item {
849 my $part = SL::DB::Manager::Part->find_by(id => delete $::form->{new_parts_id}) or die 'can not find part that was just saved!';
851 $::auth->restore_form_from_session(delete $::form->{previousform}, form => $::form);
853 $::form->{"id_$::form->{rowcount}"} = $part->id;
855 my $url = build_std_url("script=$::form->{script}", "RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session);
856 print $::request->{cgi}->redirect($url);
860 $main::lxdebug->enter_sub();
862 my $form = $main::form;
863 my %myconfig = %main::myconfig;
870 # remove any makes or model rows
871 if ($form->{part_type} eq 'assembly') {
873 # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
874 #$form->{sellprice} = 0;
876 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
877 qw(sellprice rop stock);
879 my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
881 for my $i (1 .. ($form->{assembly_rows} - 1)) {
882 if ($form->{"qty_$i"}) {
886 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
888 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
890 #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
892 # fuer assemblies auskommentiert. siehe oben
893 # $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
894 $form->{weight} += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
898 # kann das hier auch weg? s.o. jb
899 $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
901 $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
902 $form->{assembly_rows} = $count;
904 } elsif ($form->{part_type} !~ m{^(?:part|service)$}) {
905 remove_emptied_rows(1);
907 $form->{creditremaining} -= &invoicetotal;
912 $main::lxdebug->leave_sub();
915 sub remove_emptied_rows {
916 my $dont_add_empty = shift;
919 return unless $form->{rowcount};
921 my @flds = qw(id partnumber description qty ship sellprice unit
922 discount inventory_accno income_accno expense_accno listprice
923 taxaccounts bin assembly weight projectnumber project_id
924 oldprojectnumber runningnumber serialnumber partsgroup payment_id
925 not_discountable shop ve gv buchungsgruppen_id language_values
926 price_old price_new unit_old ordnumber donumber
927 transdate longdescription basefactor marge_total marge_percent
928 marge_price_factor lastcost price_factor_id partnotes
929 stock_out stock_in has_sernumber reqdate orderitems_id
930 active_price_source active_discount_source delivery_order_items_id
931 invoice_id converted_from_orderitems_id
932 converted_from_delivery_order_items_id converted_from_invoice_id
933 converted_from_reclamation_items_id recurring_billing_mode
934 expense_chart_id inventory_chart_id tax_id tax_chart_type subtotal
937 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
938 push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
941 for my $i (1 .. $form->{rowcount} - 1) {
942 next unless $form->{"partnumber_$i"};
944 push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
947 my $new_rowcount = scalar @new_rows;
948 $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
949 $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
953 $main::lxdebug->enter_sub();
955 my $form = $main::form;
956 my %myconfig = %main::myconfig;
960 $form->{oldinvtotal} = 0;
962 # add all parts and deduct paid
963 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
965 my ($amount, $sellprice, $discount, $qty);
967 for my $i (1 .. $form->{rowcount}) {
968 $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
969 $discount = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
970 $qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
972 #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
974 $amount = $sellprice * (1 - $discount / 100) * $qty;
975 map { $form->{"${_}_base"} += $amount }
976 (split (/ /, $form->{"taxaccounts_$i"}));
977 $form->{oldinvtotal} += $amount;
980 map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
981 split(/ /, $form->{taxaccounts})
982 if !$form->{taxincluded};
984 $form->{oldtotalpaid} = 0;
985 for my $i (1 .. $form->{paidaccounts}) {
986 $form->{oldtotalpaid} += $form->{"paid_$i"};
989 $main::lxdebug->leave_sub();
992 return ($form->{oldinvtotal} - $form->{oldtotalpaid});
996 $main::lxdebug->enter_sub();
998 my $form = $main::form;
999 my $locale = $main::locale;
1003 # check if items are valid
1004 if ($form->{rowcount} == 1) {
1005 flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
1007 $::dispatcher->end_request;
1010 for my $i (1 .. $form->{rowcount} - 1) {
1011 $form->isblank("partnumber_$i",
1012 $locale->text('Number missing in Row') . " $i");
1015 $main::lxdebug->leave_sub();
1019 $main::lxdebug->enter_sub();
1021 $::form->{email_journal_id} = delete $::form->{workflow_email_journal_id};
1022 $::form->{email_attachment_id} = delete $::form->{workflow_email_attachment_id};
1023 $::form->{callback} = delete $::form->{workflow_email_callback};
1027 # At this point, the record is saved and the exchangerate contains
1028 # an unformatted value. _make_record uses RDBO attributes (i.e. _as_number)
1029 # to assign values and thus expects an formatted value.
1030 $::form->{exchangerate} = $::form->format_amount(\%::myconfig, $::form->{exchangerate});
1032 my $order = _make_record();
1034 $order->currency(SL::DB::Currency->new(name => $::form->{currency})->load) if $::form->{currency};
1035 $order->globalproject_id(undef) if !$order->globalproject_id;
1036 $order->payment_id(undef) if !$order->payment_id;
1039 foreach my $item (@{$order->items_sorted}) {
1040 $item->custom_variables([]);
1042 $item->price_factor_id(undef) if !$item->price_factor_id;
1043 $item->project_id(undef) if !$item->project_id;
1045 # autovivify all cvars that are not in the form (cvars_by_config can do it).
1046 # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1047 foreach my $var (@{ $item->cvars_by_config }) {
1048 my $key = 'ic_cvar_' . $var->config->name . '_' . $row;
1049 $var->unparsed_value($::form->{$key});
1050 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1052 $item->parse_custom_variable_values;
1057 require SL::Controller::Order;
1058 my $c = SL::Controller::Order->new(order => $order);
1059 $c->reinit_after_new_order();
1062 $main::lxdebug->leave_sub();
1063 $::dispatcher->end_request;
1067 my $form = $main::form;
1068 my %myconfig = %main::myconfig;
1069 my $locale = $main::locale;
1073 if ($form->{second_run}) {
1074 $form->{print_and_post} = 0;
1076 $form->{ordnumber} = $form->{invnumber};
1078 $form->{old_employee_id} = $form->{employee_id};
1079 $form->{old_salesman_id} = $form->{salesman_id};
1081 delete $form->{$_} foreach (qw(id printed emailed queued));
1083 # When creating a new sales order from a saved sales invoice, reset id,
1084 # ordnumber, transdate and deliverydate as we are creating a new order. This
1085 # workflow is probably mainly used as a template mechanism for creating new
1086 # orders from existing invoices, so we probably don't want to link the items.
1087 # Is this order function called anywhere else?
1088 # The worksflows in oe already call sales_order and purchase_order in oe, not
1089 # this general function which now only seems to be called from saved sales
1091 # Why is ordnumber set to invnumber above, does this ever make sense?
1093 if ( $form->{script} eq 'is.pl' && $form->{type} eq 'invoice' ) {
1094 delete $form->{$_} foreach (qw(ordnumber id transdate deliverydate));
1098 if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
1099 $form->{title} = $locale->text('Add Purchase Order');
1100 $form->{vc} = 'vendor';
1101 $form->{type} = 'purchase_order';
1104 if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
1105 $form->{title} = $locale->text('Add Sales Order');
1106 $form->{vc} = 'customer';
1107 $form->{type} = 'sales_order';
1110 $form->{script} = 'oe.pl';
1112 $form->{rowcount}--;
1114 $form->{cp_id} *= 1;
1116 require "bin/mozilla/$form->{script}";
1117 my $script = $form->{"script"};
1119 $script =~ s|.pl$||;
1120 $locale = Locale->new($::lx_office_conf{system}->{language}, $script);
1122 map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1124 my $currency = $form->{currency};
1128 $form->{currency} = $currency;
1129 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
1130 $form->{exchangerate} = $form->{forex} || '';
1132 for my $i (1 .. $form->{rowcount}) {
1133 map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
1134 if ($form->{"${_}_${i}"}) }
1135 qw(ship qty sellprice basefactor discount));
1136 $form->{"converted_from_invoice_id_$i"} = delete $form->{"invoice_id_$i"};
1143 $main::lxdebug->enter_sub();
1145 my $form = $main::form;
1146 my %myconfig = %main::myconfig;
1147 my $locale = $main::locale;
1151 # we are coming from *_order and convert to quotation
1152 # it seems that quotation is only called if we have a existing order
1153 if ($form->{type} =~ /(sales|purchase)_order/) {
1154 $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1156 if ($form->{second_run}) {
1157 $form->{print_and_post} = 0;
1159 delete $form->{$_} foreach (qw(id printed emailed queued quonumber transaction_description));
1162 if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
1163 $form->{title} = $locale->text('Add Request for Quotation');
1164 $form->{vc} = 'vendor';
1165 $form->{type} = 'request_quotation';
1168 if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
1169 $form->{title} = $locale->text('Add Quotation');
1170 $form->{vc} = 'customer';
1171 $form->{type} = 'sales_quotation';
1175 $form->{cp_id} *= 1;
1177 $form->{script} = 'oe.pl';
1179 $form->{rowcount}--;
1181 require "bin/mozilla/$form->{script}";
1183 map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1185 my $currency = $form->{currency};
1189 $form->{currency} = $currency;
1190 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
1191 $form->{exchangerate} = $form->{forex} || '';
1193 for my $i (1 .. $form->{rowcount}) {
1194 map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
1195 $form->{"${_}_${i}"})
1196 if ($form->{"${_}_${i}"}) }
1197 qw(ship qty sellprice basefactor discount lastcost));
1203 $main::lxdebug->leave_sub();
1206 sub request_for_quotation {
1210 sub sales_reclamation {
1211 my $id = $::form->{id};
1212 my $type = $::form->{type};
1214 require SL::Controller::Reclamation;
1215 my $c = SL::Controller::Reclamation->new();
1217 controller => 'Reclamation',
1218 action => 'add_from_record',
1219 type => 'sales_reclamation',
1220 email_journal_id => $::form->{workflow_email_journal_id},
1221 email_attachment_id => $::form->{workflow_email_attachment_id},
1222 callback => $::form->{workflow_email_callback},
1228 sub purchase_reclamation {
1229 my $id = $::form->{id};
1230 my $type = $::form->{type};
1232 require SL::Controller::Reclamation;
1233 my $c = SL::Controller::Reclamation->new();
1235 controller => 'Reclamation',
1236 action => 'add_from_record',
1237 type => 'purchase_reclamation',
1238 email_journal_id => $::form->{workflow_email_journal_id},
1239 email_attachment_id => $::form->{workflow_email_attachment_id},
1240 callback => $::form->{workflow_email_callback},
1247 $::lxdebug->enter_sub();
1253 my $inline = delete $options{inline};
1255 require SL::Helper::PrintOptions;
1256 my $print_options = SL::Helper::PrintOptions->get_print_options(
1258 myconfig => \%::myconfig,
1259 locale => $::locale,
1260 options => \%options);
1263 $::lxdebug->leave_sub();
1264 return $print_options;
1267 print $print_options;
1268 $::lxdebug->leave_sub();
1273 $main::lxdebug->enter_sub();
1275 my $form = $main::form;
1276 my $locale = $main::locale;
1280 if ($form->{print_nextsub}) {
1281 call_sub($form->{print_nextsub});
1282 $main::lxdebug->leave_sub();
1286 # if this goes to the printer pass through
1288 if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1289 $form->error($locale->text('Select postscript or PDF!'))
1290 if ($form->{format} !~ /(postscript|pdf)/);
1292 $old_form = Form->new;
1293 map { $old_form->{$_} = $form->{$_} } keys %$form;
1296 if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1297 if ($form->{formname} eq "proforma") {
1298 $form->{proforma} = 1;
1300 $form->{print_and_save} = 1;
1301 my $formname = $form->{formname};
1303 $form->{formname} = $formname;
1305 $::lxdebug->leave_sub();
1306 $::dispatcher->end_request;
1309 &print_form($old_form);
1311 $main::lxdebug->leave_sub();
1315 $main::lxdebug->enter_sub();
1317 my $form = $main::form;
1318 my %myconfig = %main::myconfig;
1319 my $locale = $main::locale;
1323 my $defaults = SL::DB::Default->get;
1324 $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
1325 $form->{templates} = $defaults->templates;
1327 my ($old_form, %params) = @_;
1331 my $numberfld = "invnumber";
1335 ($form->{display_form}) ? $form->{display_form} : "display_form";
1337 # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1338 $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1340 if ($form->{formname} eq "invoice") {
1341 $form->{label} = $locale->text('Invoice');
1344 if ($form->{formname} eq "invoice_for_advance_payment") {
1345 $form->{label} = $locale->text('Invoice for Advance Payment');
1348 if ($form->{formname} eq "final_invoice") {
1349 $form->{label} = $locale->text('Final Invoice');
1352 if ($form->{formname} eq 'sales_order') {
1355 $form->{"${inv}date"} = $form->{transdate};
1356 $form->{label} = $locale->text('Confirmation');
1357 $numberfld = "sonumber";
1361 if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1364 $form->{"${inv}date"} = $form->{invdate};
1365 $form->{label} = $locale->text('Proforma Invoice');
1366 $numberfld = "sonumber";
1370 if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1373 $form->{"${inv}date"} = $form->{transdate};
1374 $form->{"invdate"} = $form->{transdate};
1375 $form->{invnumber} = $form->{ordnumber};
1376 $form->{label} = $locale->text('Proforma Invoice');
1377 $numberfld = "sonumber";
1381 if ($form->{formname} eq 'purchase_order') {
1384 $form->{"${inv}date"} = $form->{transdate};
1385 $form->{label} = $locale->text('Purchase Order');
1386 $numberfld = "ponumber";
1389 if ($form->{formname} eq 'bin_list') {
1392 $form->{"${inv}date"} = $form->{transdate};
1393 $form->{label} = $locale->text('Bin List');
1396 if ($form->{formname} eq 'sales_quotation') {
1399 $form->{"${inv}date"} = $form->{transdate};
1400 $form->{label} = $locale->text('Quotation');
1401 $numberfld = "sqnumber";
1405 if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1408 $form->{"${inv}date"} = $form->{transdate};
1409 $form->{"invdate"} = $form->{transdate};
1410 $form->{label} = $locale->text('Proforma Invoice');
1411 $numberfld = "sqnumber";
1415 if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'ic_supply') ) {
1418 $form->{"${inv}date"} = $form->{transdate};
1419 $form->{"invdate"} = $form->{transdate};
1420 $form->{invnumber} = $form->{ordnumber};
1421 $form->{label} = $locale->text('Intra-Community supply');
1422 $numberfld = "sonumber";
1426 if ($form->{formname} eq 'request_quotation') {
1429 $form->{"${inv}date"} = $form->{transdate};
1430 $form->{label} = $locale->text('RFQ');
1431 $numberfld = "rfqnumber";
1435 if ($form->{type} =~ /_delivery_order$/) {
1438 $form->{"${inv}date"} = $form->{transdate};
1439 $numberfld = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1440 $form->{label} = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1442 if ($form->{type} =~ /letter/) {
1445 $form->{label} = $locale->text('Letter');
1448 $form->{TEMPLATE_DRIVER_OPTIONS} = { };
1449 if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice invoice_for_advance_payment final_invoice request_quotation purchase_order purchase_delivery_order credit_note)) {
1450 $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = $form->get_variable_content_types();
1453 if ($form->{format} =~ m{pdf}) {
1454 _maybe_attach_zugferd_data($form);
1457 $form->isblank("email", $locale->text('E-mail address missing!'))
1458 if ($form->{media} eq 'email');
1459 $form->isblank("${inv}date",
1460 $locale->text($form->{label})
1462 . $locale->text(' Date missing!'));
1464 # $locale->text('Invoice Number missing!')
1465 # $locale->text('Invoice Date missing!')
1466 # $locale->text('Order Number missing!')
1467 # $locale->text('Order Date missing!')
1468 # $locale->text('Quotation Number missing!')
1469 # $locale->text('Quotation Date missing!')
1471 $form->{what_done} = $form->{formname};
1475 # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1476 my ($saved_email, $saved_cc, $saved_bcc) =
1477 ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1479 my $language_saved = $form->{language_id};
1480 my $payment_id_saved = $form->{payment_id};
1481 my $delivery_term_id_saved = $form->{delivery_term_id};
1482 my $salesman_id_saved = $form->{salesman_id};
1483 my $cp_id_saved = $form->{cp_id};
1484 my $taxzone_id_saved = $form->{taxzone_id};
1485 my $currency_saved = $form->{currency};
1487 call_sub("$form->{vc}_details") if ($form->{vc});
1489 $form->{language_id} = $language_saved;
1490 $form->{payment_id} = $payment_id_saved;
1491 $form->{delivery_term_id} = $delivery_term_id_saved;
1492 $form->{taxzone_id} = $taxzone_id_saved;
1493 $form->{currency} = $currency_saved;
1495 $form->{"email"} = $saved_email if ($saved_email);
1496 $form->{"cc"} = $saved_cc if ($saved_cc);
1497 $form->{"bcc"} = $saved_bcc if ($saved_bcc);
1499 if (!$cp_id_saved) {
1500 # No contact was selected. Delete all contact variables because
1501 # IS->customer_details() and IR->vendor_details() get the default
1503 map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1506 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1507 if ($form->{"language_id"}) {
1508 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1509 AM->get_language_details(\%myconfig, $form, $form->{language_id});
1511 $output_dateformat = $myconfig{"dateformat"};
1512 $output_numberformat = $myconfig{"numberformat"};
1513 $output_longdates = 1;
1516 # Store the output number format so that the template modules know
1517 # how to parse the amounts back if requested.
1518 $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
1520 ($form->{employee}) = split /--/, $form->{employee};
1522 # create the form variables
1523 if ($form->{type} =~ /_delivery_order$/) {
1524 DO->order_details(\%myconfig, \%$form);
1526 OE->order_details(\%myconfig, \%$form);
1527 } elsif ($form->{type} eq 'letter') {
1528 # right now, no details are needed
1529 # but i do not want to break the bad default (invoice)
1531 IS->invoice_details(\%myconfig, \%$form, $locale);
1534 $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
1535 $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
1537 if ($form->{shipto_id}) {
1538 $form->get_shipto(\%myconfig);
1541 $form->set_addition_billing_address_print_variables;
1543 $form->{notes} =~ s/^\s+//g;
1545 delete $form->{printer_command};
1547 $form->{language} = $form->get_template_language(\%myconfig);
1550 if ($form->{media} ne 'email') {
1551 $printer_code = $form->get_printer_code(\%myconfig);
1552 if ($printer_code ne "") {
1553 $printer_code = "_" . $printer_code;
1557 if ($form->{language} ne "") {
1558 my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
1559 map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
1561 $form->{language} = "_" . $form->{language};
1565 format_dates($output_dateformat, $output_longdates,
1566 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point
1567 shippingdate deliverydate validitydate paymentdate
1568 datepaid transdate_oe transdate_do transdate_quo deliverydate_oe dodate
1569 employee_startdate employee_enddate
1571 grep({ /^datepaid_\d+$/ ||
1572 /^transdate_oe_\d+$/ ||
1573 /^transdate_do_\d+$/ ||
1574 /^transdate_quo_\d+$/ ||
1575 /^deliverydate_oe_\d+$/ ||
1577 /^deliverydate_\d+$/ ||
1581 reformat_numbers($output_numberformat, 2,
1582 qw(invtotal ordtotal quototal subtotal linetotal
1583 listprice sellprice netprice discount
1584 tax taxbase total paid payment),
1585 grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
1587 reformat_numbers($output_numberformat, undef,
1588 qw(qty price_factor),
1592 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1594 if (scalar @{ $cvar_date_fields }) {
1595 format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1598 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1599 reformat_numbers($output_numberformat, $precision, @{ $field_list });
1602 my $extension = 'html';
1603 if ($form->{format} eq 'postscript') {
1604 $form->{postscript} = 1;
1607 } elsif ($form->{"format"} =~ /pdf/) {
1609 $extension = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
1611 } elsif ($form->{"format"} =~ /opendocument/) {
1612 $form->{opendocument} = 1;
1614 } elsif ($form->{"format"} =~ /excel/) {
1619 # search for the template
1620 my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1621 name => $form->{formname},
1622 email => $form->{media} eq 'email',
1623 language_id => $form->{language_id},
1624 printer_id => $form->{printer_id},
1625 extension => $extension,
1628 if (!defined $template_file) {
1629 $::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));
1632 $form->{IN} = $template_file;
1634 delete $form->{OUT};
1636 if ($form->{media} eq 'printer') {
1637 $form->{OUT} = $form->{printer_command};
1638 $form->{OUT_MODE} = '|-';
1639 $form->{printed} .= " $form->{formname}";
1640 $form->{printed} =~ s/^ //;
1642 my $printed = $form->{printed};
1644 if ($form->{media} eq 'email') {
1645 $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1646 unless $form->{subject};
1648 $form->{emailed} .= " $form->{formname}";
1649 $form->{emailed} =~ s/^ //;
1650 $form->{addition} = "MAILED";
1652 my $emailed = $form->{emailed};
1654 if ($form->{media} eq 'queue') {
1655 my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
1658 my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
1659 if ($filename = $queued{ $form->{formname} }) {
1660 unlink $::lx_office_conf{paths}->{spool} . "/$filename";
1661 delete $queued{ $form->{formname} };
1663 $form->{queued} = join ' ', %queued;
1664 $filename =~ s/\..*$//g;
1665 $filename .= $suffix;
1666 $form->{OUT} = $::lx_office_conf{paths}->{spool} . "/$filename";
1667 $form->{OUT_MODE} = '>';
1671 ($temp_fh, $filename) = File::Temp::tempfile(
1672 'kivitendo-spoolXXXXXX',
1673 SUFFIX => "$suffix",
1674 DIR => $::lx_office_conf{paths}->{spool},
1678 $form->{OUT} = "$filename";
1679 # use >> for OUT_MODE because file is already created by File::Temp
1680 $form->{OUT_MODE} = '>>';
1681 # strip directory so that only filename is stored in table status
1682 ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
1686 $form->{queued} .= " $form->{formname} $filename";
1687 $form->{queued} =~ s/^ //;
1689 my $queued = $form->{queued};
1691 # saving the history
1692 if(!exists $form->{addition}) {
1693 $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1694 if($form->{media} =~ /printer/) {
1695 $form->{addition} = "PRINTED";
1697 elsif($form->{media} =~ /email/) {
1698 $form->{addition} = "MAILED";
1700 elsif($form->{media} =~ /queue/) {
1701 $form->{addition} = "QUEUED";
1703 elsif($form->{media} =~ /screen/) {
1704 $form->{addition} = "SCREENED";
1706 $form->save_history;
1708 # /saving the history
1710 # prepare meta information for template introspection
1711 $form->{template_meta} = {
1712 formname => $form->{formname},
1713 language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
1714 format => $form->{format},
1715 media => $form->{media},
1716 extension => $extension,
1717 printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
1718 today => DateTime->today,
1721 if ($defaults->print_interpolate_variables_in_positions) {
1722 $form->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
1725 $form->parse_template(\%myconfig);
1727 $form->{callback} = "";
1729 if ($form->{media} eq 'email') {
1730 $form->{message} = $locale->text('sent') unless $form->{message};
1732 my $message = $form->{message};
1734 # if we got back here restore the previous form
1735 if ($form->{media} =~ /(printer|email|queue)/) {
1737 $form->update_status(\%myconfig)
1738 if ($form->{media} eq 'queue' && $form->{id});
1740 return $main::lxdebug->leave_sub() if ($old_form eq "return");
1744 $old_form->{"${inv}number"} = $form->{"${inv}number"};
1746 # restore and display form
1747 map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1749 $form->{queued} = $queued;
1750 $form->{printed} = $printed;
1751 $form->{emailed} = $emailed;
1752 $form->{message} = $message;
1754 $form->{rowcount}--;
1755 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1756 qw(exchangerate creditlimit creditremaining);
1758 for my $i (1 .. $form->{paidaccounts}) {
1760 $form->{"${_}_$i"} =
1761 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1762 } qw(paid exchangerate);
1765 call_sub($display_form);
1766 $::dispatcher->end_request;
1770 ($form->{media} eq 'printer')
1771 ? $locale->text('sent to printer')
1772 : $locale->text('emailed to') . " $form->{email}";
1774 if (!$params{no_redirect}) {
1775 $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1778 if ($form->{printing}) {
1779 call_sub($display_form);
1780 $::dispatcher->end_request;
1783 $main::lxdebug->leave_sub();
1786 sub customer_details {
1787 $main::lxdebug->enter_sub();
1789 my $form = $main::form;
1790 my %myconfig = %main::myconfig;
1792 IS->customer_details(\%myconfig, \%$form, @_);
1794 $main::lxdebug->leave_sub();
1797 sub vendor_details {
1798 $main::lxdebug->enter_sub();
1800 my $form = $main::form;
1801 my %myconfig = %main::myconfig;
1803 IR->vendor_details(\%myconfig, \%$form, @_);
1805 $main::lxdebug->leave_sub();
1808 sub relink_accounts {
1809 $main::lxdebug->enter_sub();
1811 my $form = $main::form;
1812 my %myconfig = %main::myconfig;
1814 $form->{"taxaccounts"} =~ s/\s*$//;
1815 $form->{"taxaccounts"} =~ s/^\s*//;
1816 foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1817 map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber tax_id)); # add tax_id ?
1819 $form->{"taxaccounts"} = "";
1821 IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1823 $main::lxdebug->leave_sub();
1826 sub get_payment_terms_for_invoice {
1827 my $terms = $::form->{payment_id} ? SL::DB::PaymentTerm->new(id => $::form->{payment_id}) ->load
1828 : $::form->{customer_id} ? SL::DB::Customer ->new(id => $::form->{customer_id})->load->payment
1829 : $::form->{vendor_id} ? SL::DB::Vendor ->new(id => $::form->{vendor_id}) ->load->payment
1838 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
1839 my $terms = get_payment_terms_for_invoice();
1840 my $invdate = $::form->{invdate} eq 'undefined' ? DateTime->today_local : DateTime->from_kivitendo($::form->{invdate});
1841 my $duedate = $terms ? $terms->calc_date(reference_date => $invdate, due_date => $::form->{duedate})->to_kivitendo : ($::form->{duedate} || $invdate->to_kivitendo);
1843 if ($terms && $terms->auto_calculation) {
1844 $js->hide('#duedate_container')
1845 ->show('#duedate_fixed')
1846 ->html('#duedate_fixed', $duedate);
1849 $js->show('#duedate_container')
1850 ->hide('#duedate_fixed');
1853 $js->val('#duedate', $duedate)
1857 sub _update_part_information {
1858 $main::lxdebug->enter_sub();
1860 my $form = $main::form;
1862 my %part_information = IC->get_basic_part_info('id' => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ]);
1864 $form->{PART_INFORMATION} = \%part_information;
1866 foreach my $i (1..$form->{rowcount}) {
1867 next unless ($form->{"id_${i}"});
1869 my $info = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
1870 $form->{"partunit_${i}"} = $info->{unit};
1871 $form->{"weight_$i"} = $info->{weight};
1872 $form->{"part_type_$i"} = $info->{part_type};
1873 $form->{"classification_id_$i"} = $info->{classification_id};
1874 $form->{"has_sernumber_$i"} = $info->{has_sernumber};
1877 $main::lxdebug->leave_sub();
1881 return unless $::form->{id};
1882 my $helper = SL::Helper::ShippedQty->new->calculate($::form->{id});
1884 for my $i (1..$::form->{rowcount}) {
1885 if (my $oid = $::form->{"orderitems_id_$i"}) {
1886 $::form->{"ship_$i"} = $helper->shipped_qty->{$oid};
1891 sub _update_custom_variables {
1892 $main::lxdebug->enter_sub();
1894 my $form = $main::form;
1896 $form->{CVAR_CONFIGS} = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
1897 $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
1899 $main::lxdebug->leave_sub();
1902 sub _render_custom_variables_inputs {
1903 $main::lxdebug->enter_sub(2);
1905 my $form = $main::form;
1909 if (!$form->{CVAR_CONFIGS}->{IC}) {
1910 $main::lxdebug->leave_sub();
1914 my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
1916 # get partsgroup_id from part
1918 if ($params{part_id}) {
1919 $partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id;
1922 my $num_visible_cvars = 0;
1923 foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
1924 $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
1926 # set partsgroup filter
1927 my $partsgroup_filtered = 0;
1928 if ($cvar->{flag_partsgroup_filter}) {
1929 if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) {
1930 $partsgroup_filtered = 1;
1934 my $hide_non_editable = 1;
1937 my $description = '';
1938 if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) {
1939 $num_visible_cvars++;
1940 $description = $cvar->{description} . ' ';
1944 my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
1946 push @{ $params{ROW2} }, {
1947 line_break => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)),
1948 description => $description,
1951 hide_non_editable => $hide_non_editable,
1953 name_prefix => 'ic_',
1954 name_postfix => "_$params{row}",
1955 valid => $cvar->{valid},
1956 value => CVar->parse($::form->{$form_key}, $cvar),
1957 partsgroup_filtered => $partsgroup_filtered,
1962 $main::lxdebug->leave_sub(2);
1965 sub _remove_billed_or_delivered_rows {
1968 croak "Missing parameter 'quantities'" if !$params{quantities};
1970 my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
1973 my $make_key = sub {
1975 return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
1976 my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
1977 return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
1980 my $removed_rows = 0;
1982 while ($row < $::form->{rowcount}) {
1984 next unless $::form->{"id_$row"};
1986 my $parts_id = $::form->{"id_$row"};
1987 my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
1989 my $key = $make_key->($row);
1990 my $sub_qty = min($base_qty, $params{quantities}->{$key});
1991 $params{quantities}->{$key} -= $sub_qty;
1993 if (!$sub_qty || ($sub_qty != $base_qty)) {
1994 $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
1995 push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
2002 $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
2003 $::form->{rowcount} -= $removed_rows;
2006 # TODO: both of these are makeshift so that price sources can operate on rdbo objects. if
2007 # this ever gets rewritten in controller style, throw this out
2008 sub _make_record_item {
2009 my ($row, %params) = @_;
2012 sales_order => 'OrderItem',
2013 purchase_order => 'OrderItem',
2014 sales_quotation => 'OrderItem',
2015 request_quotation => 'OrderItem',
2016 invoice => 'InvoiceItem',
2017 invoice_for_advance_payment => 'InvoiceItem',
2018 final_invoice => 'InvoiceItem',
2019 credit_note => 'InvoiceItem',
2020 purchase_invoice => 'InvoiceItem',
2021 purchase_delivery_order => 'DeliveryOrderItem',
2022 sales_delivery_order => 'DeliveryOrderItem',
2023 }->{$::form->{type}};
2025 return unless $class;
2027 $class = 'SL::DB::' . $class;
2029 my %translated_methods = (
2030 'SL::DB::OrderItem' => {
2032 orderitems_id => 'id',
2034 'SL::DB::DeliveryOrderItem' => {
2036 delivery_order_items_id => 'id',
2038 'SL::DB::InvoiceItem' => {
2044 eval "require $class";
2046 my $obj = $::form->{"orderitems_id_$row"}
2047 ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{"orderitems_id_$row"})
2050 for my $key (grep { /_$row$/ } keys %$::form) {
2052 $method =~ s/_$row$//;
2053 $method = $translated_methods{$class}{$method} // $method;
2054 my $value = $::form->{$key};
2055 if ($obj->meta->column($method)) {
2056 if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
2057 $obj->${\"$method\_as_date"}($value);
2058 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
2059 $obj->${\"$method\_as_number"}(($value // '') eq '' ? undef : $value);
2060 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
2061 $obj->$method(!!$value);
2062 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
2063 $obj->$method(($value // '') eq '' ? undef : $value * 1);
2065 $obj->$method($value);
2068 if ($method eq 'discount') {
2069 $obj->discount($obj->discount / 100.0);
2073 $obj->{__additional_form_attributes}{$method} = $value;
2077 if ($::form->{"id_$row"}) {
2078 $obj->part(SL::DB::Part->load_cached($::form->{"id_$row"}));
2081 if ($obj->can('qty')) {
2082 $obj->qty( $obj->qty * $params{factor});
2083 $obj->base_qty($obj->base_qty * $params{factor});
2091 sales_order => 'Order',
2092 purchase_order => 'Order',
2093 sales_quotation => 'Order',
2094 request_quotation => 'Order',
2095 purchase_delivery_order => 'DeliveryOrder',
2096 sales_delivery_order => 'DeliveryOrder',
2097 }->{$::form->{type}};
2099 if ($::form->{type} =~ /invoice|credit_note/) {
2100 $class = $::form->{vc} eq 'customer' ? 'Invoice'
2101 : $::form->{vc} eq 'vendor' ? 'PurchaseInvoice'
2102 : do { die 'unknown invoice type' };
2105 my $factor = $::form->{type} =~ m{credit_note} ? -1 : 1;
2107 return unless $class;
2109 $class = 'SL::DB::' . $class;
2111 eval "require $class";
2113 my $obj = $::form->{id}
2114 ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{id})
2117 for my $method (keys %$::form) {
2118 next unless $obj->can($method);
2119 next unless $obj->meta->column($method);
2121 if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
2122 $obj->${\"$method\_as_date"}($::form->{$method});
2123 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
2124 $obj->${\"$method\_as_number"}(($::form->{$method} // '') eq '' ? undef : $::form->{$method});
2125 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
2126 $obj->$method(!!$::form->{$method});
2127 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
2128 $obj->$method(($::form->{$method} // '') eq '' ? undef : $::form->{$method} * 1);
2130 $obj->$method($::form->{$method});
2135 for my $i (1 .. $::form->{rowcount}) {
2136 next unless $::form->{"id_$i"};
2137 push @items, _make_record_item($i, factor => $factor);
2140 $obj->items(@items) if @items;
2142 if ($class eq 'SL::DB::DeliveryOrder' && !$obj->record_type) {
2143 $obj->record_type(SL::DB::DeliveryOrder::TypeData::validate_type($::form->{type}));
2146 if ($class eq 'SL::DB::Order' && !$obj->record_type) {
2147 $obj->record_type(SL::DB::Order::TypeData::validate_type($::form->{type}));
2150 if ($class eq 'SL::DB::Invoice') {
2151 my $paid = $factor *
2153 map { $::form->parse_amount(\%::myconfig, $::form->{$_}) }
2154 grep { m{^paid_\d+$} }
2162 sub setup_sales_purchase_print_options {
2163 my $print_form = Form->new('');
2164 $print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;
2166 $print_form->{$_} = $::form->{$_} for qw(type media printer_id storno storno_id formname groupitems);
2168 return SL::Helper::PrintOptions->get_print_options(
2169 form => $print_form,
2176 sub _get_files_for_email_dialog {
2177 my %files = map { ($_ => []) } qw(versions files vc_files part_files project_files);
2179 return %files if !$::instance_conf->get_doc_storage;
2181 if ($::form->{id}) {
2182 $files{versions} = [ SL::File->get_all_versions(object_id => $::form->{id}, object_type => $::form->{type}, file_type => 'document') ];
2183 $files{files} = [ SL::File->get_all( object_id => $::form->{id}, object_type => $::form->{type}, file_type => 'attachment') ];
2184 $files{vc_files} = [ SL::File->get_all( object_id => $::form->{vc_id}, object_type => $::form->{vc}, file_type => 'attachment') ]
2185 if $::form->{vc} && $::form->{"vc_id"};
2186 $files{project_files} = [ SL::File->get_all(object_id => $::form->{project_id}, object_type => 'project',file_type => 'attachment') ]
2187 if $::form->{project_id};
2191 uniq_by { $_->{id} }
2194 +{ id => $::form->{"id_$_"},
2195 partnumber => $::form->{"partnumber_$_"},
2197 } (1 .. $::form->{rowcount});
2199 foreach my $part (@parts) {
2200 my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
2201 push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
2204 foreach my $key (keys %files) {
2205 $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
2211 sub show_sales_purchase_email_dialog {
2216 my $is_invoice_mail = $::form->{type} =~ m{final_invoice|credit_note|invoice_for_advance_payment|invoice};
2218 if ($::form->{cp_id}) {
2219 $email = SL::DB::Contact->load_cached($::form->{cp_id})->cp_email;
2221 # write a dispatch table if a third type enters
2222 # check record mail for sales_invoice
2223 if ($is_invoice_mail && (!$email || $::instance_conf->get_invoice_mail_settings ne 'cp')) {
2224 # check for invoice_mail if defined (vc.invoice_email)
2225 $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->invoice_mail;
2226 if ($record_email) {
2227 # check if cc for contact is also wanted
2228 $email_cc = $email if ($::instance_conf->get_invoice_mail_settings eq 'invoice_mail_cc_cp');
2229 $email = $record_email;
2232 # check record mail for sales_delivery_order
2233 if ($::form->{type} eq 'sales_delivery_order') {
2234 # check for deliver_order_mail if defined (vc.delivery_order_mail)
2235 $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->delivery_order_mail;
2236 if ($record_email) {
2237 # check if cc for contact is also wanted
2238 $email_cc = $email; # always cc to cp
2239 $email = $record_email;
2242 # still no email? use general mail (vc.email)
2243 if (!$email && $::form->{vc} && $::form->{vc_id}) {
2244 $email = SL::DB::Customer->load_cached($::form->{vc_id})->email if 'customer' eq $::form->{vc};
2245 $email = SL::DB::Vendor ->load_cached($::form->{vc_id})->email if 'vendor' eq $::form->{vc};
2248 $email = '' if $::form->{type} eq 'purchase_delivery_order';
2250 $::form->{language} = $::form->get_template_language(\%::myconfig);
2251 $::form->{language} = "_" . $::form->{language};
2253 my %body_params = (record_email => $record_email);
2254 if (($::form->{type} eq 'invoice') && $::form->{direct_debit}) {
2255 $body_params{translation_type} = "preset_text_invoice_direct_debit";
2256 $body_params{fallback_translation_type} = "preset_text_invoice";
2259 my @employees_with_email = grep {
2260 my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
2261 $user && !!trim($user->get_config_value('email'));
2262 } @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
2267 subject => $::form->generate_email_subject,
2268 message => $::form->generate_email_body(%body_params),
2269 attachment_filename => $::form->generate_attachment_filename,
2270 js_send_function => 'kivi.SalesPurchase.send_email()',
2273 my %files = _get_files_for_email_dialog();
2275 my $all_partner_email_addresses;
2276 $all_partner_email_addresses = SL::DB::Customer->load_cached($::form->{vc_id})->get_all_email_addresses() if 'customer' eq $::form->{vc};
2277 $all_partner_email_addresses = SL::DB::Vendor ->load_cached($::form->{vc_id})->get_all_email_addresses() if 'vendor' eq $::form->{vc};
2279 my $html = $::form->parse_html_template("common/_send_email_dialog", {
2280 email_form => $email_form,
2281 show_bcc => $::auth->assert('email_bcc', 'may fail'),
2283 is_customer => $::form->{vc} eq 'customer',
2284 is_invoice_mail => ($record_email && $is_invoice_mail),
2285 ALL_EMPLOYEES => \@employees_with_email,
2286 ALL_PARTNER_EMAIL_ADDRESSES => $all_partner_email_addresses,
2289 print $::form->ajax_response_header, $html;
2292 sub send_sales_purchase_email {
2293 my $type = $::form->{type};
2294 my $id = $::form->{id};
2295 my $script = $type =~ m{sales_order|purchase_order|quotation} ? 'oe.pl'
2296 : $type =~ m{delivery_} ? 'do.pl'
2299 my $email_form = delete $::form->{email_form};
2301 if ($email_form->{additional_to}) {
2302 $email_form->{to} = join ', ', grep { $_ } $email_form->{to}, @{$email_form->{additional_to}};
2303 delete $email_form->{additional_to};
2306 my %field_names = (to => 'email');
2308 $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
2310 $::form->{media} = 'email';
2312 $::form->{attachment_policy} //= '';
2314 # Is an old file version available?
2316 if ($::form->{attachment_policy} eq 'old_file') {
2317 $attfile = SL::File->get_all(object_id => $id,
2318 object_type => $type,
2319 file_type => 'document',
2320 print_variant => $::form->{formname},);
2323 if ($::form->{attachment_policy} eq 'no_file' || ($::form->{attachment_policy} eq 'old_file' && $attfile)) {
2324 $::form->send_email(\%::myconfig, 'pdf');
2327 print_form("return");
2328 Common->save_email_status(\%::myconfig, $::form) unless ($::instance_conf->get_email_journal);
2331 flash_later('info', $::locale->text('The email has been sent.'));
2333 print $::form->redirect_header($script . '?action=edit&id=' . $::form->escape($id) . '&type=' . $::form->escape($type));
2336 sub _maybe_attach_zugferd_data {
2339 my $record = _make_record();
2342 || !$record->can('customer')
2343 || !$record->customer
2344 || !$record->can('create_pdf_a_print_options')
2345 || !$record->can('create_zugferd_data')
2346 || !$record->customer->create_zugferd_invoices_for_this_customer;
2349 my $xmlfile = File::Temp->new;
2350 $xmlfile->print($record->create_zugferd_data);
2353 $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_a} = $record->create_pdf_a_print_options(zugferd_xmp_data => $record->create_zugferd_xmp_data);
2354 $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_attachments} = [
2355 { source => $xmlfile,
2356 name => 'factur-x.xml',
2357 description => $::locale->text('Factur-X/ZUGFeRD invoice'),
2358 relationship => '/Alternative',
2359 mime_type => 'text/xml',
2364 if (my $e = SL::X::ZUGFeRDValidation->caught) {
2365 $::form->error($e->message);
2369 sub download_factur_x_xml {
2372 my $record = _make_record();
2375 || !$record->can('customer')
2376 || !$record->customer
2377 || !$record->can('create_pdf_a_print_options')
2378 || !$record->can('create_zugferd_data')
2379 || !$record->customer->create_zugferd_invoices_for_this_customer;
2381 my $xml_content = eval { $record->create_zugferd_data };
2383 if (my $e = SL::X::ZUGFeRDValidation->caught) {
2384 $::form->error($e->message);
2387 my $attachment_filename = "factur-x_" . $::form->generate_attachment_filename;
2388 $attachment_filename =~ s{\.[^.]+$}{.xml};
2390 '-type' => 'application/xml',
2391 '-connection' => 'close',
2392 '-attachment' => $attachment_filename,
2393 '-content-length' => length($xml_content),
2396 print $::request->cgi->header(%headers);
2398 $::locale->with_raw_io(\*STDOUT, sub { print $xml_content });
2401 sub get_taxes_dropdown {
2402 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
2403 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
2404 my $item_deliverydate = $::form->{item_deliverydate} ? DateTime->from_kivitendo($::form->{item_deliverydate}) : undef;
2406 my @taxes = IO->get_active_taxes_for_chart($::form->{chart_id},
2407 $item_deliverydate // $deliverydate // $transdate);
2408 my $html = $::form->parse_html_template("ir/update_taxes", { TAXES => \@taxes });
2410 print $::form->ajax_response_header, $html;