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;
65 use SL::Helper::CreatePDF;
66 use SL::Helper::Flash;
67 use SL::Helper::PrintOptions;
68 use SL::Helper::ShippedQty;
70 require "bin/mozilla/common.pl";
74 # any custom scripts for this one
75 if (-f "bin/mozilla/custom_io.pl") {
76 eval { require "bin/mozilla/custom_io.pl"; };
78 if (-f "bin/mozilla/$::myconfig{login}_io.pl") {
79 eval { require "bin/mozilla/$::myconfig{login}_io.pl"; };
86 # this is for our long dates
87 # $locale->text('January')
88 # $locale->text('February')
89 # $locale->text('March')
90 # $locale->text('April')
91 # $locale->text('May ')
92 # $locale->text('June')
93 # $locale->text('July')
94 # $locale->text('August')
95 # $locale->text('September')
96 # $locale->text('October')
97 # $locale->text('November')
98 # $locale->text('December')
100 # this is for our short month
101 # $locale->text('Jan')
102 # $locale->text('Feb')
103 # $locale->text('Mar')
104 # $locale->text('Apr')
105 # $locale->text('May')
106 # $locale->text('Jun')
107 # $locale->text('Jul')
108 # $locale->text('Aug')
109 # $locale->text('Sep')
110 # $locale->text('Oct')
111 # $locale->text('Nov')
112 # $locale->text('Dec')
118 $main::auth->assert('part_service_assembly_edit | vendor_invoice_edit | sales_order_edit | invoice_edit |' .
119 'request_quotation_edit | sales_quotation_edit | purchase_order_edit | ' .
120 'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details');
123 ########################################
124 # Eintrag fuer Version 2.2.0 geaendert #
125 # neue Optik im Rechnungsformular #
126 ########################################
128 $main::lxdebug->enter_sub();
130 my $form = $main::form;
131 my %myconfig = %main::myconfig;
132 my $locale = $main::locale;
133 my $cgi = $::request->{cgi};
137 my ($stock_in_out, $stock_in_out_title);
139 my $defaults = AM->get_defaults();
140 $form->{show_weight} = $defaults->{show_weight};
141 $form->{weightunit} = $defaults->{weightunit};
143 my $is_purchase = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
144 my $is_delivery_order = $form->{type} =~ /_delivery_order$/;
145 my $is_quotation = $form->{type} =~ /_quotation$/;
146 my $is_invoice = $form->{type} =~ /invoice/;
147 my $is_credit_note = $form->{type} =~ /credit_note/;
148 my $is_s_p_order = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
149 my $show_ship_missing = $is_s_p_order && $::instance_conf->get_sales_purchase_order_ship_missing_column;
150 my $show_marge = (!$is_purchase || $is_invoice || $is_credit_note) && !$is_delivery_order;
152 if ($is_delivery_order) {
153 if ($form->{type} eq 'sales_delivery_order') {
154 $stock_in_out_title = $locale->text('Release From Stock');
155 $stock_in_out = 'out';
157 $stock_in_out_title = $locale->text('Transfer To Stock');
158 $stock_in_out = 'in';
161 retrieve_partunits();
165 my @header_sort = qw(
166 runningnumber partnumber type_and_classific description ship ship_missing qty price_factor
167 unit weight price_source sellprice discount linetotal
171 serialnr projectnr reqdate subtotal marge listprice lastcost onhand
173 # serialnr is important for delivery_orders
174 if ($form->{type} eq 'sales_delivery_order') {
175 splice @row2_sort, 0, 1;
176 splice @header_sort, 4, 0, "serialnr";
180 runningnumber => { width => 5, value => $locale->text('No.'), display => 1, },
181 partnumber => { width => 8, value => $locale->text('Number'), display => 1, },
183 => { width => 2, value => $locale->text('Type'), display => 1, },
184 description => { width => 30, value => $locale->text('Part Description'), display => 1, },
185 ship => { width => 5, value => $locale->text('Delivered'), display => $is_s_p_order, },
186 ship_missing => { width => 5, value => $locale->text('Not delivered'), display => $show_ship_missing, },
187 qty => { width => 5, value => $locale->text('Qty'), display => 1, },
188 price_factor => { width => 5, value => $locale->text('Price Factor'), display => !$is_delivery_order, },
189 unit => { width => 5, value => $locale->text('Unit'), display => 1, },
190 weight => { width => 5, value => $locale->text('Weight'), display => $defaults->{show_weight}, },
191 serialnr => { width => 10, value => $locale->text('Serial No.'), display => !$is_quotation },
192 projectnr => { width => 10, value => $locale->text('Project'), display => 1, },
193 price_source => { width => 5, value => $locale->text('Price Source'), display => !$is_delivery_order, },
194 sellprice => { width => 15, value => $locale->text('Price'), display => !$is_delivery_order, },
195 discount => { width => 5, value => $locale->text('Discount'), display => !$is_delivery_order, },
196 linetotal => { width => 10, value => $locale->text('Extended'), display => !$is_delivery_order, },
197 bin => { width => 10, value => $locale->text('Bin'), display => 0, },
198 stock_in_out => { width => 10, value => $stock_in_out_title, display => $is_delivery_order, },
199 reqdate => { value => $locale->text('Reqdate'), display => $is_s_p_order || $is_delivery_order || $is_invoice, },
200 subtotal => { value => $locale->text('Subtotal'), display => 1, },
201 marge => { value => $locale->text('Ertrag'), display => $show_marge, },
202 listprice => { value => $locale->text('LP'), display => $show_marge, },
203 lastcost => { value => $locale->text('EK'), display => $show_marge, },
204 onhand => { value => $locale->text('On Hand'), display => 1, },
206 my @HEADER = map { $column_def{$_} } @header_sort;
209 my $all_units = AM->retrieve_units(\%myconfig, $form);
211 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
214 $form->{invsubtotal} = 0;
215 map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));
218 $myconfig{show_form_details} = 1 unless (defined($myconfig{show_form_details}));
219 $form->{show_details} = $myconfig{show_form_details} unless (defined($form->{show_details}));
222 # translations, unused commented out
223 my $deliverydate = $locale->text('Required by');
226 my %align = map { $_ => 'right' } qw(qty ship right discount linetotal stock_in_out weight ship_missing);
227 my %nowrap = map { $_ => 1 } qw(description unit price_source);
229 $form->{marge_total} = 0;
230 $form->{sellprice_total} = 0;
231 $form->{lastcost_total} = 0;
232 $form->{totalweight} = 0;
233 my %projectnumber_labels = ();
234 my @projectnumber_values = ("");
236 foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
237 push(@projectnumber_values, $item->{"id"});
238 $projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
241 _update_part_information();
242 _update_ship() if ($is_s_p_order);
243 _update_custom_variables();
247 my $record = _make_record();
251 for my $i (1 .. $numrows) {
252 my %column_data = ();
254 my $record_item = $record->id && $record->items ? $record->items->[$i-1] : _make_record_item($i);
257 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
258 qw(qty discount sellprice lastcost price_new price_old)
259 unless ($form->{simple_save});
261 if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
262 $form->{"sellprice_$i"} = $form->{"price_new_$i"};
266 $form->{"unit_old_$i"} ||= $form->{"unit_$i"};
267 $form->{"selected_unit_$i"} ||= $form->{"unit_$i"};
269 if ( !$all_units->{$form->{"selected_unit_$i"}} # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
270 || !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
271 $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"}; # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
274 $form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
275 $form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
276 $form->{"unit_old_$i"} = $form->{"selected_unit_$i"};
278 my $this_unit = $form->{"unit_$i"};
279 $this_unit = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);
281 if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
282 my @values = ('', map { $_->{id} } @{ $form->{ALL_PRICE_FACTORS} });
283 my %labels = map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };
285 $column_data{price_factor} =
286 NTI($cgi->popup_menu('-name' => "price_factor_id_$i",
287 '-default' => $form->{"price_factor_id_$i"},
288 '-values' => \@values,
289 '-labels' => \%labels,
290 '-style' => 'width:90px'));
292 $column_data{price_factor} = ' ';
294 $form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
296 $column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
299 #count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
300 #is shown for lastcost and sellprice.
301 my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
302 $decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
304 my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || 1;
305 my $discount = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * $form->{"discount_$i"} / 100 / $price_factor, 2);
306 my $linetotal = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
307 my $rows = $form->numtextrows($form->{"description_$i"}, 30, 6);
309 # quick delete single row
310 $column_data{runningnumber} = q|<a onclick= "$('#partnumber_| . $i . q|').val(''); $('#update_button').click();">| .
311 q|<img height="10px" width="10px" src="image/cross.png" alt="| . $locale->text('Remove') . q|"></a> |;
312 $column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5, -value => $i); # HuT
315 $column_data{partnumber} = $cgi->textfield(-name => "partnumber_$i", -id => "partnumber_$i", -size => 12, -value => $form->{"partnumber_$i"});
316 $column_data{type_and_classific} = SL::Presenter::Part::type_abbreviation($form->{"part_type_$i"}).
317 SL::Presenter::Part::classification_abbreviation($form->{"classification_id_$i"}) if $form->{"id_$i"};
318 $column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
319 ? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
320 : $cgi->textfield(-name => "description_$i", -id => "description_$i", -value => $form->{"description_$i"}, -size => 30))
321 . $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
323 my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
325 $column_data{qty} = $cgi->textfield(-name => "qty_$i", -size => 5, -class => "numeric", -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
326 $column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_dialog('qty_$i', '', 'formel_$i', '')", -value => $locale->text('*/'))
327 . $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"})
328 if $form->{"formel_$i"};
330 $column_data{ship} = '';
331 if ($form->{"id_$i"}) {
332 my $ship_qty = $form->{"ship_$i"} * 1;
333 $ship_qty *= $all_units->{$form->{"partunit_$i"}}->{factor};
334 $ship_qty /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
336 $column_data{ship} = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"}
337 . $cgi->hidden(-name => "ship_$i", -value => $form->{"ship_$i"}, $qty_dec);
339 my $ship_missing_qty = $form->{"qty_$i"} - $ship_qty;
340 my $ship_missing_amount = $form->round_amount($ship_missing_qty * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
342 $column_data{ship_missing} = $form->format_amount(\%myconfig, $ship_missing_qty) . ' ' . $form->{"unit_$i"} . '; ' . $form->format_amount(\%myconfig, $ship_missing_amount, $decimalplaces);
345 $column_data{linetotal} = $form->format_amount(\%myconfig, $linetotal, 2);
346 $column_data{bin} = $form->{"bin_$i"};
348 $column_data{weight} = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
350 my $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
351 my $discount_value = $form->format_amount(\%myconfig, $form->{"discount_$i"});
354 if ($form->{"id_${i}"} && !$is_delivery_order) {
355 my $price_source = SL::PriceSource->new(record_item => $record_item, record => $record);
356 $price = $price_source->price_from_source($::form->{"active_price_source_$i"});
357 my $discount = $price_source->discount_from_source($::form->{"active_discount_source_$i"});
358 my $best_price = $price_source->best_price;
359 my $best_discount = $price_source->best_discount;
360 $column_data{price_source} .= $cgi->button(-value => $price->source_description, -onClick => "kivi.io.price_chooser($i)");
361 if ($price->source) {
362 $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->invalid, title => $price->invalid }) if $price->invalid;
363 $column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->missing, title => $price->missing }) if $price->missing;
364 if (!$price->missing && !$price->invalid) {
365 $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;
366 $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;
367 $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;
370 if ($discount->source) {
371 $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->invalid, title => $discount->invalid }) if $discount->invalid;
372 $column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->missing, title => $discount->missing }) if $discount->missing;
373 if (!$discount->missing && !$discount->invalid) {
374 $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;
375 $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;
376 $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;
381 my $right_to_edit_prices = (!$is_purchase && $main::auth->assert('sales_edit_prices', 1)) || ($is_purchase && $main::auth->assert('purchase_edit_prices', 1));
382 my $edit_prices = $right_to_edit_prices && (!$::form->{"active_price_source_$i"} || !$price || $price->editable);
383 my $edit_discounts = $right_to_edit_prices && !$::form->{"active_discount_source_$i"};
384 $column_data{sellprice} = (!$edit_prices)
385 ? $cgi->hidden( -name => "sellprice_$i", -id => "sellprice_$i", -value => $sellprice_value) . $sellprice_value
386 : $cgi->textfield(-name => "sellprice_$i", -id => "sellprice_$i", -size => 10, -class => "numeric", -value => $sellprice_value);
387 $column_data{discount} = (!$edit_discounts)
388 ? $cgi->hidden( -name => "discount_$i", -id => "discount_$i", -value => $discount_value) . $discount_value . ' %'
389 : $cgi->textfield(-name => "discount_$i", -id => "discount_$i", -size => 3, -"data-validate" => "number", -class => "numeric", -value => $discount_value);
391 if ($is_delivery_order) {
392 $column_data{stock_in_out} = calculate_stock_in_out($i);
395 $column_data{serialnr} = qq|<input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}">|;
396 $column_data{projectnr} = NTI($cgi->popup_menu(
397 '-name' => "project_id_$i",
398 '-values' => \@projectnumber_values,
399 '-labels' => \%projectnumber_labels,
400 '-default' => $form->{"project_id_$i"}
402 $column_data{reqdate} = qq|<input name="reqdate_$i" size="11" data-validate="date" value="$form->{"reqdate_$i"}">|;
403 $column_data{subtotal} = sprintf qq|<input type="checkbox" name="subtotal_$i" value="1" %s>|, $form->{"subtotal_$i"} ? 'checked' : '';
405 # begin marge calculations
406 $form->{"lastcost_$i"} *= 1;
407 $form->{"marge_percent_$i"} = 0;
411 if ( $form->{taxincluded} and $form->{"qty_$i"} * 1 and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
412 # if we use taxincluded we need to calculate the marge from the net_value
413 # all the marge calculations are based on linetotal which we need to
414 # convert to net first
416 # there is no direct form value for the tax_rate of the item, but
417 # form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
418 # gives the tax percentage (e.g. 0.19)
419 $real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
421 $real_sellprice = $linetotal;
423 my $real_lastcost = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"} / $price_factor, 2);
424 my $marge_percent_warn = $myconfig{marge_percent_warn} * 1 || 15;
425 my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;
427 if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
428 $form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
429 $marge_color = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
432 $form->{"marge_absolut_$i"} = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
433 $form->{"marge_total"} += $form->{"marge_absolut_$i"};
434 $form->{"lastcost_total"} += $real_lastcost;
435 $form->{"sellprice_total"} += $real_sellprice;
437 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);
439 $column_data{marge} = sprintf qq|<font %s>%s %s%%</font>|,
440 $marge_color, $form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"};
441 $column_data{listprice} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2);
442 $column_data{lastcost} = sprintf qq|<input size="5" name="lastcost_$i" value="%s">|, $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
443 # / marge calculations ending
445 # Calculate total weight
446 $totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});
449 if ($form->{"id_$i"}) {
450 my $part = IC->get_basic_part_info(id => $form->{"id_$i"});
451 my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
452 $column_data{onhand} = sprintf "<font %s>%s %s</font>",
454 $form->format_amount(\%myconfig, $part->{onhand}, 2),
459 my @ROW1 = map { { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} } } grep { $column_def{$_}{display} } @header_sort;
460 my @ROW2 = map { { value => sprintf "<b>%s</b> %s", $column_def{$_}{value}, $column_data{$_} } } grep { $column_def{$_}{display} } @row2_sort;
463 # add hidden ids for persistent (item|invoice)_ids and previous (converted_from*) ids
465 push @hidden_vars, qw(orderitems_id converted_from_orderitems_id);
468 push @hidden_vars, qw(orderitems_id converted_from_orderitems_id converted_from_invoice_id);
471 push @hidden_vars, qw(invoice_id converted_from_orderitems_id converted_from_delivery_order_items_id converted_from_invoice_id);
473 if ($::form->{type} =~ /credit_note/) {
474 push @hidden_vars, qw(invoice_id converted_from_invoice_id);
476 if ($is_delivery_order) {
477 map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
478 push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost);
479 push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
480 push @hidden_vars, qw(delivery_order_items_id converted_from_orderitems_id converted_from_delivery_order_items_id has_sernumber);
483 my @HIDDENS = map { value => $_}, (
484 $cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
485 $cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
486 map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
487 (qw(bo price_old id inventory_accno bin partsgroup partnotes active_price_source active_discount_source
488 income_accno expense_accno listprice part_type taxaccounts ordnumber donumber transdate cusordnumber
489 longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
492 map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));
494 $form->{invsubtotal} += $linetotal;
496 # Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
497 _render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
499 my $colspan = scalar @ROW1;
500 push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, obj => $record_item };
503 $form->{totalweight} = $totalweight;
505 print $form->parse_html_template('oe/sales_order', { ROWS => \@ROWS,
509 if (abs($form->{sellprice_total} * 1) >= 0.01) {
510 $form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
513 $main::lxdebug->leave_sub();
516 sub setup_io_select_item_action_bar {
519 for my $bar ($::request->layout->get('actionbar')) {
523 submit => [ '#form' ],
524 accesskey => 'enter',
531 $main::lxdebug->enter_sub();
534 my $mode = $params{mode} || croak "Missing parameter 'mode'";
535 my $pre_entered_qty = $params{pre_entered_qty} || 1;
538 setup_io_select_item_action_bar();
540 my $previous_form = $::auth->save_form_in_session(form => $::form);
541 $::form->{title} = $::myconfig{item_multiselect} ?
542 $::locale->text('Set count for one or more of the items to select them'):
543 $::locale->text('Select from one of the items below');
546 my @item_list = map {
547 # maybe there is a better backend function or way to calc
548 $_->{display_sellprice} = ($_->{price_factor}) ? $_->{sellprice} / $_->{price_factor} : $_->{sellprice};
550 } @{ $::form->{item_list} };
552 # delete action variable
553 delete @{$::form}{qw(action item_list)};
555 print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
557 ITEM_LIST => \@item_list,
558 IS_ASSEMBLY => $mode eq 'IC',
559 IS_PURCHASE => $mode eq 'IS',
560 PRE_ENTERED_QTY => $pre_entered_qty, });
562 $main::lxdebug->leave_sub();
567 # this function is used for adding parts to records (mode = IR/IS)
568 # and to assemblies (mode = IC)
570 $main::lxdebug->enter_sub();
572 my $form = $main::form;
573 my %myconfig = %main::myconfig;
577 $::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
579 my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
580 my $row_key = $mode eq 'IC' ? 'assembly_rows' : 'rowcount';
581 my $curr_row = $form->{ $row_key };
585 if ($myconfig{item_multiselect}) {
588 next unless $form->{$_};
589 next unless /^select_qty_(\d+)/;
590 $multi_items{"id_${row}"} = $1;
591 $multi_items{"qty_${row}"} = $form->{$_};
594 $form->{$_} = $multi_items{$_} for keys %multi_items;
596 $form->{"id_${row}"} = delete($form->{select_item_id}) || croak 'Missing item selection ID';
600 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
601 qw(sellprice weight);
603 if ( $mode eq 'IC' ) {
605 # the qty variables of the existing assembly items are all still formatted, so we parse them here
606 # including the qty of the just added part
607 $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for (1 .. $row - 1);
609 if ($myconfig{item_multiselect}) {
610 # other modes and multiselection:
611 # parse all newly entered qtys
612 $form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for ($curr_row .. $row - 1);
616 for my $i ($curr_row .. $row - 1) {
617 $form->{ $row_key } = $i;
619 my $id = $form->{"id_${i}"};
621 delete $form->{item_list};
624 IS->retrieve_item(\%myconfig, \%$form);
625 } elsif ($mode eq 'IR') {
626 IR->retrieve_item(\%myconfig, \%$form);
627 } elsif ($mode eq 'IC') {
628 IC->assembly_item(\%myconfig, \%$form);
630 croak "Invalid item selection mode '${mode}'";
633 my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
635 # if there was a price entered, override it
637 unless ( $mode eq 'IC' ) {
638 $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
642 qw(id partnumber description sellprice listprice inventory_accno
643 income_accno expense_accno bin unit weight part_type taxaccounts
644 partsgroup formel longdescription not_discountable partnotes lastcost
645 price_factor_id price_factor);
647 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
648 push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
650 map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
652 if (my $record = _make_record()) {
653 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
654 my $best_price = $price_source->best_price;
657 $::form->{"sellprice_$i"} = $best_price->price;
658 $::form->{"active_price_source_$i"} = $best_price->source;
661 my $best_discount = $price_source->best_discount;
663 if ($best_discount) {
664 $::form->{"discount_$i"} = $best_discount->discount;
665 $::form->{"active_discount_source_$i"} = $best_discount->source;
669 $form->{"marge_price_factor_$i"} = $new_item->{price_factor};
671 if ($form->{"part_payment_id_$i"} ne "") {
672 $form->{payment_id} = $form->{"part_payment_id_$i"};
675 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
677 my $decimalplaces = ($dec > 2) ? $dec : 2;
680 $form->{"sellprice_$i"} = $sellprice;
683 # if there is an exchange rate adjust sellprice
684 if (($form->{exchangerate} * 1) != 0) {
685 $form->{"sellprice_$i"} /= $form->{exchangerate};
686 $form->{"sellprice_$i"} =
687 $form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
691 # at this stage qty of newly added part needs to be have been parsed
692 $form->{weight} += ($form->{"weight_$i"} * $form->{"qty_$i"});
694 if ($form->{"not_discountable_$i"}) {
695 $form->{"discount_$i"} = 0;
699 $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"}) * $form->{"qty_$i"};
700 map { $form->{"${_}_base"} += $amount } (split / /, $form->{"taxaccounts_$i"});
701 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
703 $form->{creditremaining} -= $amount;
704 $form->{"runningnumber_$i"} = $i;
709 $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
710 } qw(sellprice lastcost qty) if $form->{part_type} ne 'assembly';
711 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0) if $form->{part_type} ne 'assembly';
713 delete $form->{nextsub};
719 $main::lxdebug->leave_sub();
725 my $price = $::form->{vc} eq 'customer' ? 'sellprice_as_number' : 'lastcost_as_number';
726 my $previousform = $::auth->save_form_in_session;
727 my $callback = build_std_url("action=return_from_new_item", "previousform=$previousform");
728 my $i = $::form->{rowcount};
730 my $parts_classification_type = $::form->{vc} eq 'customer' ? 'sales' : 'purchases';
733 push @HIDDENS, { 'name' => 'callback', 'value' => $callback };
734 push @HIDDENS, map +{ 'name' => $_, 'value' => $::form->{$_} }, qw(rowcount vc);
735 push @HIDDENS, map +{ 'name' => "part.$_", 'value' => $::form->{"${_}_$i"} }, qw(partnumber description unit price_factor_id);
736 push @HIDDENS, { 'name' => "part.$price", 'value' => $::form->{"sellprice_$i"} };
737 push @HIDDENS, { 'name' => "part.notes", 'value' => $::form->{"longdescription_$i"} };
739 push @HIDDENS, { 'name' => "parts_classification_type", 'value' => $parts_classification_type };
742 print $::form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
745 sub return_from_new_item {
748 my $part = SL::DB::Manager::Part->find_by(id => delete $::form->{new_parts_id}) or die 'can not find part that was just saved!';
750 $::auth->restore_form_from_session(delete $::form->{previousform}, form => $::form);
752 $::form->{"id_$::form->{rowcount}"} = $part->id;
754 my $url = build_std_url("script=$::form->{script}", "RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session);
755 print $::request->{cgi}->redirect($url);
759 $main::lxdebug->enter_sub();
761 my $form = $main::form;
762 my %myconfig = %main::myconfig;
769 # remove any makes or model rows
770 if ($form->{part_type} eq 'assembly') {
772 # fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
773 #$form->{sellprice} = 0;
775 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
776 qw(sellprice rop stock);
778 my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
780 for my $i (1 .. ($form->{assembly_rows} - 1)) {
781 if ($form->{"qty_$i"}) {
785 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
787 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
789 #($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
791 # fuer assemblies auskommentiert. siehe oben
792 # $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
793 $form->{weight} += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
797 # kann das hier auch weg? s.o. jb
798 $form->{sellprice} = $form->round_amount($form->{sellprice}, 2);
800 $form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
801 $form->{assembly_rows} = $count;
803 } elsif ($form->{part_type} !~ m{^(?:part|service)$}) {
804 remove_emptied_rows(1);
806 $form->{creditremaining} -= &invoicetotal;
811 $main::lxdebug->leave_sub();
814 sub remove_emptied_rows {
815 my $dont_add_empty = shift;
818 return unless $form->{rowcount};
820 my @flds = qw(id partnumber description qty ship sellprice unit
821 discount inventory_accno income_accno expense_accno listprice
822 taxaccounts bin assembly weight projectnumber project_id
823 oldprojectnumber runningnumber serialnumber partsgroup payment_id
824 not_discountable shop ve gv buchungsgruppen_id language_values
825 price_old price_new unit_old ordnumber donumber
826 transdate longdescription basefactor marge_total marge_percent
827 marge_price_factor lastcost price_factor_id partnotes
828 stock_out stock_in has_sernumber reqdate orderitems_id
829 active_price_source active_discount_source delivery_order_items_id
830 invoice_id converted_from_orderitems_id
831 converted_from_delivery_order_items_id converted_from_invoice_id);
833 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
834 push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
837 for my $i (1 .. $form->{rowcount} - 1) {
838 next unless $form->{"partnumber_$i"};
840 push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
843 my $new_rowcount = scalar @new_rows;
844 $form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
845 $form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
849 $main::lxdebug->enter_sub();
851 my $form = $main::form;
852 my %myconfig = %main::myconfig;
856 $form->{oldinvtotal} = 0;
858 # add all parts and deduct paid
859 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
861 my ($amount, $sellprice, $discount, $qty);
863 for my $i (1 .. $form->{rowcount}) {
864 $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
865 $discount = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
866 $qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
868 #($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};
870 $amount = $sellprice * (1 - $discount / 100) * $qty;
871 map { $form->{"${_}_base"} += $amount }
872 (split (/ /, $form->{"taxaccounts_$i"}));
873 $form->{oldinvtotal} += $amount;
876 map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
877 split(/ /, $form->{taxaccounts})
878 if !$form->{taxincluded};
880 $form->{oldtotalpaid} = 0;
881 for my $i (1 .. $form->{paidaccounts}) {
882 $form->{oldtotalpaid} += $form->{"paid_$i"};
885 $main::lxdebug->leave_sub();
888 return ($form->{oldinvtotal} - $form->{oldtotalpaid});
892 $main::lxdebug->enter_sub();
894 my $form = $main::form;
895 my $locale = $main::locale;
899 # check if items are valid
900 if ($form->{rowcount} == 1) {
901 flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
903 $::dispatcher->end_request;
906 for my $i (1 .. $form->{rowcount} - 1) {
907 $form->isblank("partnumber_$i",
908 $locale->text('Number missing in Row') . " $i");
911 $main::lxdebug->leave_sub();
915 $main::lxdebug->enter_sub();
919 if ($::instance_conf->get_feature_experimental_order) {
921 # At this point, the record is saved and the exchangerate contains
922 # an unformatted value. _make_record uses RDBO attributes (i.e. _as_number)
923 # to assign values and thus expects an formatted value.
924 $::form->{exchangerate} = $::form->format_amount(\%::myconfig, $::form->{exchangerate});
926 my $order = _make_record();
928 $order->currency(SL::DB::Currency->new(name => $::form->{currency})->load) if $::form->{currency};
929 $order->globalproject_id(undef) if !$order->globalproject_id;
930 $order->payment_id(undef) if !$order->payment_id;
933 foreach my $item (@{$order->items_sorted}) {
934 $item->custom_variables([]);
936 $item->price_factor_id(undef) if !$item->price_factor_id;
937 $item->project_id(undef) if !$item->project_id;
939 # autovivify all cvars that are not in the form (cvars_by_config can do it).
940 # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
941 foreach my $var (@{ $item->cvars_by_config }) {
942 my $key = 'ic_cvar_' . $var->config->name . '_' . $row;
943 $var->unparsed_value($::form->{$key});
944 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
946 $item->parse_custom_variable_values;
951 require SL::Controller::Order;
952 my $c = SL::Controller::Order->new(order => $order);
953 $c->setup_custom_shipto_from_form($order, $::form);
956 $main::lxdebug->leave_sub();
957 $::dispatcher->end_request;
962 $main::lxdebug->leave_sub();
966 my $form = $main::form;
967 my %myconfig = %main::myconfig;
968 my $locale = $main::locale;
972 if ($form->{second_run}) {
973 $form->{print_and_post} = 0;
975 $form->{ordnumber} = $form->{invnumber};
977 $form->{old_employee_id} = $form->{employee_id};
978 $form->{old_salesman_id} = $form->{salesman_id};
980 delete $form->{$_} foreach (qw(id printed emailed queued));
982 # When creating a new sales order from a saved sales invoice, reset id,
983 # ordnumber, transdate and deliverydate as we are creating a new order. This
984 # workflow is probably mainly used as a template mechanism for creating new
985 # orders from existing invoices, so we probably don't want to link the items.
986 # Is this order function called anywhere else?
987 # The worksflows in oe already call sales_order and purchase_order in oe, not
988 # this general function which now only seems to be called from saved sales
990 # Why is ordnumber set to invnumber above, does this ever make sense?
992 if ( $form->{script} eq 'is.pl' && $form->{type} eq 'invoice' ) {
993 delete $form->{$_} foreach (qw(ordnumber id transdate deliverydate));
997 if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
998 $form->{title} = $locale->text('Add Purchase Order');
999 $form->{vc} = 'vendor';
1000 $form->{type} = 'purchase_order';
1003 if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
1004 $form->{title} = $locale->text('Add Sales Order');
1005 $form->{vc} = 'customer';
1006 $form->{type} = 'sales_order';
1009 $form->{script} = 'oe.pl';
1011 $form->{rowcount}--;
1013 $form->{cp_id} *= 1;
1015 require "bin/mozilla/$form->{script}";
1016 my $script = $form->{"script"};
1018 $script =~ s|.pl$||;
1019 $locale = Locale->new($::lx_office_conf{system}->{language}, $script);
1021 map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1023 my $currency = $form->{currency};
1027 $form->{currency} = $currency;
1028 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
1029 $form->{exchangerate} = $form->{forex} || '';
1031 for my $i (1 .. $form->{rowcount}) {
1032 map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
1033 if ($form->{"${_}_${i}"}) }
1034 qw(ship qty sellprice basefactor discount));
1035 $form->{"converted_from_invoice_id_$i"} = delete $form->{"invoice_id_$i"};
1042 $main::lxdebug->enter_sub();
1044 my $form = $main::form;
1045 my %myconfig = %main::myconfig;
1046 my $locale = $main::locale;
1050 # we are coming from *_order and convert to quotation
1051 # it seems that quotation is only called if we have a existing order
1052 if ($form->{type} =~ /(sales|purchase)_order/) {
1053 $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1055 if ($form->{second_run}) {
1056 $form->{print_and_post} = 0;
1058 delete $form->{$_} foreach (qw(id printed emailed queued quonumber transaction_description));
1061 if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
1062 $form->{title} = $locale->text('Add Request for Quotation');
1063 $form->{vc} = 'vendor';
1064 $form->{type} = 'request_quotation';
1067 if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
1068 $form->{title} = $locale->text('Add Quotation');
1069 $form->{vc} = 'customer';
1070 $form->{type} = 'sales_quotation';
1074 $form->{cp_id} *= 1;
1076 $form->{script} = 'oe.pl';
1078 $form->{rowcount}--;
1080 require "bin/mozilla/$form->{script}";
1082 map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1084 my $currency = $form->{currency};
1088 $form->{currency} = $currency;
1089 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
1090 $form->{exchangerate} = $form->{forex} || '';
1092 for my $i (1 .. $form->{rowcount}) {
1093 map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
1094 $form->{"${_}_${i}"})
1095 if ($form->{"${_}_${i}"}) }
1096 qw(ship qty sellprice basefactor discount lastcost));
1102 $main::lxdebug->leave_sub();
1105 sub request_for_quotation {
1110 $::lxdebug->enter_sub();
1116 my $inline = delete $options{inline};
1118 require SL::Helper::PrintOptions;
1119 my $print_options = SL::Helper::PrintOptions->get_print_options(
1121 myconfig => \%::myconfig,
1122 locale => $::locale,
1123 options => \%options);
1126 $::lxdebug->leave_sub();
1127 return $print_options;
1130 print $print_options;
1131 $::lxdebug->leave_sub();
1136 $main::lxdebug->enter_sub();
1138 my $form = $main::form;
1139 my $locale = $main::locale;
1143 if ($form->{print_nextsub}) {
1144 call_sub($form->{print_nextsub});
1145 $main::lxdebug->leave_sub();
1149 # if this goes to the printer pass through
1151 if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
1152 $form->error($locale->text('Select postscript or PDF!'))
1153 if ($form->{format} !~ /(postscript|pdf)/);
1155 $old_form = Form->new;
1156 map { $old_form->{$_} = $form->{$_} } keys %$form;
1159 if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
1160 if ($form->{formname} eq "proforma") {
1161 $form->{proforma} = 1;
1163 $form->{print_and_save} = 1;
1164 my $formname = $form->{formname};
1166 $form->{formname} = $formname;
1168 $::lxdebug->leave_sub();
1169 $::dispatcher->end_request;
1172 &print_form($old_form);
1174 $main::lxdebug->leave_sub();
1178 $main::lxdebug->enter_sub();
1180 my $form = $main::form;
1181 my %myconfig = %main::myconfig;
1182 my $locale = $main::locale;
1186 my $defaults = SL::DB::Default->get;
1187 $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
1188 $form->{templates} = $defaults->templates;
1190 my ($old_form, %params) = @_;
1194 my $numberfld = "invnumber";
1198 ($form->{display_form}) ? $form->{display_form} : "display_form";
1200 # $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
1201 $form->{ $form->{"formname"} . "notes" } = $form->{"notes"};
1203 if ($form->{formname} eq "invoice") {
1204 $form->{label} = $locale->text('Invoice');
1206 if ($form->{formname} eq 'sales_order') {
1209 $form->{"${inv}date"} = $form->{transdate};
1210 $form->{label} = $locale->text('Confirmation');
1211 $numberfld = "sonumber";
1215 if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
1218 $form->{"${inv}date"} = $form->{invdate};
1219 $form->{label} = $locale->text('Proforma Invoice');
1220 $numberfld = "sonumber";
1224 if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
1227 $form->{"${inv}date"} = $form->{transdate};
1228 $form->{"invdate"} = $form->{transdate};
1229 $form->{invnumber} = $form->{ordnumber};
1230 $form->{label} = $locale->text('Proforma Invoice');
1231 $numberfld = "sonumber";
1235 if ($form->{formname} eq 'purchase_order') {
1238 $form->{"${inv}date"} = $form->{transdate};
1239 $form->{label} = $locale->text('Purchase Order');
1240 $numberfld = "ponumber";
1243 if ($form->{formname} eq 'bin_list') {
1246 $form->{"${inv}date"} = $form->{transdate};
1247 $form->{label} = $locale->text('Bin List');
1250 if ($form->{formname} eq 'sales_quotation') {
1253 $form->{"${inv}date"} = $form->{transdate};
1254 $form->{label} = $locale->text('Quotation');
1255 $numberfld = "sqnumber";
1259 if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
1262 $form->{"${inv}date"} = $form->{transdate};
1263 $form->{"invdate"} = $form->{transdate};
1264 $form->{label} = $locale->text('Proforma Invoice');
1265 $numberfld = "sqnumber";
1269 if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'ic_supply') ) {
1272 $form->{"${inv}date"} = $form->{transdate};
1273 $form->{"invdate"} = $form->{transdate};
1274 $form->{invnumber} = $form->{ordnumber};
1275 $form->{label} = $locale->text('Intra-Community supply');
1276 $numberfld = "sonumber";
1280 if ($form->{formname} eq 'request_quotation') {
1283 $form->{"${inv}date"} = $form->{transdate};
1284 $form->{label} = $locale->text('RFQ');
1285 $numberfld = "rfqnumber";
1289 if ($form->{type} =~ /_delivery_order$/) {
1292 $form->{"${inv}date"} = $form->{transdate};
1293 $numberfld = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
1294 $form->{label} = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
1296 if ($form->{type} =~ /letter/) {
1299 $form->{label} = $locale->text('Letter');
1302 $form->{TEMPLATE_DRIVER_OPTIONS} = { };
1303 if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice request_quotation purchase_order purchase_delivery_order credit_note)) {
1304 $form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = $form->get_variable_content_types();
1307 if ($form->{format} =~ m{pdf}) {
1308 _maybe_attach_zugferd_data($form);
1311 $form->isblank("email", $locale->text('E-mail address missing!'))
1312 if ($form->{media} eq 'email');
1313 $form->isblank("${inv}date",
1314 $locale->text($form->{label})
1316 . $locale->text(' Date missing!'));
1318 # $locale->text('Invoice Number missing!')
1319 # $locale->text('Invoice Date missing!')
1320 # $locale->text('Order Number missing!')
1321 # $locale->text('Order Date missing!')
1322 # $locale->text('Quotation Number missing!')
1323 # $locale->text('Quotation Date missing!')
1325 $form->{what_done} = $form->{formname};
1329 # Save the email address given in the form because it should override the setting saved for the customer/vendor.
1330 my ($saved_email, $saved_cc, $saved_bcc) =
1331 ($form->{"email"}, $form->{"cc"}, $form->{"bcc"});
1333 my $language_saved = $form->{language_id};
1334 my $payment_id_saved = $form->{payment_id};
1335 my $delivery_term_id_saved = $form->{delivery_term_id};
1336 my $salesman_id_saved = $form->{salesman_id};
1337 my $cp_id_saved = $form->{cp_id};
1338 my $taxzone_id_saved = $form->{taxzone_id};
1339 my $currency_saved = $form->{currency};
1341 call_sub("$form->{vc}_details") if ($form->{vc});
1343 $form->{language_id} = $language_saved;
1344 $form->{payment_id} = $payment_id_saved;
1345 $form->{delivery_term_id} = $delivery_term_id_saved;
1346 $form->{taxzone_id} = $taxzone_id_saved;
1347 $form->{currency} = $currency_saved;
1349 $form->{"email"} = $saved_email if ($saved_email);
1350 $form->{"cc"} = $saved_cc if ($saved_cc);
1351 $form->{"bcc"} = $saved_bcc if ($saved_bcc);
1353 if (!$cp_id_saved) {
1354 # No contact was selected. Delete all contact variables because
1355 # IS->customer_details() and IR->vendor_details() get the default
1357 map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
1360 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
1361 if ($form->{"language_id"}) {
1362 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
1363 AM->get_language_details(\%myconfig, $form, $form->{language_id});
1365 $output_dateformat = $myconfig{"dateformat"};
1366 $output_numberformat = $myconfig{"numberformat"};
1367 $output_longdates = 1;
1370 # Store the output number format so that the template modules know
1371 # how to parse the amounts back if requested.
1372 $myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
1374 ($form->{employee}) = split /--/, $form->{employee};
1376 # create the form variables
1377 if ($form->{type} =~ /_delivery_order$/) {
1378 DO->order_details(\%myconfig, \%$form);
1380 OE->order_details(\%myconfig, \%$form);
1381 } elsif ($form->{type} eq 'letter') {
1382 # right now, no details are needed
1383 # but i do not want to break the bad default (invoice)
1385 IS->invoice_details(\%myconfig, \%$form, $locale);
1388 $form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
1389 $form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
1391 if ($form->{shipto_id}) {
1392 $form->get_shipto(\%myconfig);
1395 $form->{notes} =~ s/^\s+//g;
1397 delete $form->{printer_command};
1399 $form->{language} = $form->get_template_language(\%myconfig);
1402 if ($form->{media} ne 'email') {
1403 $printer_code = $form->get_printer_code(\%myconfig);
1404 if ($printer_code ne "") {
1405 $printer_code = "_" . $printer_code;
1409 if ($form->{language} ne "") {
1410 my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
1411 map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);
1413 $form->{language} = "_" . $form->{language};
1417 format_dates($output_dateformat, $output_longdates,
1418 qw(invdate orddate quodate pldate duedate reqdate transdate tax_point
1419 shippingdate deliverydate validitydate paymentdate
1420 datepaid transdate_oe transdate_do transdate_quo deliverydate_oe dodate
1421 employee_startdate employee_enddate
1423 grep({ /^datepaid_\d+$/ ||
1424 /^transdate_oe_\d+$/ ||
1425 /^transdate_do_\d+$/ ||
1426 /^transdate_quo_\d+$/ ||
1427 /^deliverydate_oe_\d+$/ ||
1429 /^deliverydate_\d+$/ ||
1433 reformat_numbers($output_numberformat, 2,
1434 qw(invtotal ordtotal quototal subtotal linetotal
1435 listprice sellprice netprice discount
1436 tax taxbase total paid payment),
1437 grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
1439 reformat_numbers($output_numberformat, undef,
1440 qw(qty price_factor),
1444 my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
1446 if (scalar @{ $cvar_date_fields }) {
1447 format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
1450 while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
1451 reformat_numbers($output_numberformat, $precision, @{ $field_list });
1454 my $extension = 'html';
1455 if ($form->{format} eq 'postscript') {
1456 $form->{postscript} = 1;
1459 } elsif ($form->{"format"} =~ /pdf/) {
1461 $extension = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
1463 } elsif ($form->{"format"} =~ /opendocument/) {
1464 $form->{opendocument} = 1;
1466 } elsif ($form->{"format"} =~ /excel/) {
1471 # search for the template
1472 my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1473 name => $form->{formname},
1474 email => $form->{media} eq 'email',
1475 language_id => $form->{language_id},
1476 printer_id => $form->{printer_id},
1477 extension => $extension,
1480 if (!defined $template_file) {
1481 $::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));
1484 $form->{IN} = $template_file;
1486 delete $form->{OUT};
1488 if ($form->{media} eq 'printer') {
1489 $form->{OUT} = $form->{printer_command};
1490 $form->{OUT_MODE} = '|-';
1491 $form->{printed} .= " $form->{formname}";
1492 $form->{printed} =~ s/^ //;
1494 my $printed = $form->{printed};
1496 if ($form->{media} eq 'email') {
1497 $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
1498 unless $form->{subject};
1500 $form->{emailed} .= " $form->{formname}";
1501 $form->{emailed} =~ s/^ //;
1502 $form->{addition} = "MAILED";
1504 my $emailed = $form->{emailed};
1506 if ($form->{media} eq 'queue') {
1507 my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
1510 my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
1511 if ($filename = $queued{ $form->{formname} }) {
1512 unlink $::lx_office_conf{paths}->{spool} . "/$filename";
1513 delete $queued{ $form->{formname} };
1515 $form->{queued} = join ' ', %queued;
1516 $filename =~ s/\..*$//g;
1517 $filename .= $suffix;
1518 $form->{OUT} = $::lx_office_conf{paths}->{spool} . "/$filename";
1519 $form->{OUT_MODE} = '>';
1523 ($temp_fh, $filename) = File::Temp::tempfile(
1524 'kivitendo-spoolXXXXXX',
1525 SUFFIX => "$suffix",
1526 DIR => $::lx_office_conf{paths}->{spool},
1530 $form->{OUT} = "$filename";
1531 # use >> for OUT_MODE because file is already created by File::Temp
1532 $form->{OUT_MODE} = '>>';
1533 # strip directory so that only filename is stored in table status
1534 ($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
1538 $form->{queued} .= " $form->{formname} $filename";
1539 $form->{queued} =~ s/^ //;
1541 my $queued = $form->{queued};
1543 # saving the history
1544 if(!exists $form->{addition}) {
1545 $form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
1546 if($form->{media} =~ /printer/) {
1547 $form->{addition} = "PRINTED";
1549 elsif($form->{media} =~ /email/) {
1550 $form->{addition} = "MAILED";
1552 elsif($form->{media} =~ /queue/) {
1553 $form->{addition} = "QUEUED";
1555 elsif($form->{media} =~ /screen/) {
1556 $form->{addition} = "SCREENED";
1558 $form->save_history;
1560 # /saving the history
1562 # prepare meta information for template introspection
1563 $form->{template_meta} = {
1564 formname => $form->{formname},
1565 language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
1566 format => $form->{format},
1567 media => $form->{media},
1568 extension => $extension,
1569 printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
1570 today => DateTime->today,
1573 $form->parse_template(\%myconfig);
1575 $form->{callback} = "";
1577 if ($form->{media} eq 'email') {
1578 $form->{message} = $locale->text('sent') unless $form->{message};
1580 my $message = $form->{message};
1582 # if we got back here restore the previous form
1583 if ($form->{media} =~ /(printer|email|queue)/) {
1585 $form->update_status(\%myconfig)
1586 if ($form->{media} eq 'queue' && $form->{id});
1588 return $main::lxdebug->leave_sub() if ($old_form eq "return");
1592 $old_form->{"${inv}number"} = $form->{"${inv}number"};
1594 # restore and display form
1595 map { $form->{$_} = $old_form->{$_} } keys %$old_form;
1597 $form->{queued} = $queued;
1598 $form->{printed} = $printed;
1599 $form->{emailed} = $emailed;
1600 $form->{message} = $message;
1602 $form->{rowcount}--;
1603 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1604 qw(exchangerate creditlimit creditremaining);
1606 for my $i (1 .. $form->{paidaccounts}) {
1608 $form->{"${_}_$i"} =
1609 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
1610 } qw(paid exchangerate);
1613 call_sub($display_form);
1614 $::dispatcher->end_request;
1618 ($form->{media} eq 'printer')
1619 ? $locale->text('sent to printer')
1620 : $locale->text('emailed to') . " $form->{email}";
1622 if (!$params{no_redirect}) {
1623 $form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
1626 if ($form->{printing}) {
1627 call_sub($display_form);
1628 $::dispatcher->end_request;
1631 $main::lxdebug->leave_sub();
1634 sub customer_details {
1635 $main::lxdebug->enter_sub();
1637 my $form = $main::form;
1638 my %myconfig = %main::myconfig;
1640 IS->customer_details(\%myconfig, \%$form, @_);
1642 $main::lxdebug->leave_sub();
1645 sub vendor_details {
1646 $main::lxdebug->enter_sub();
1648 my $form = $main::form;
1649 my %myconfig = %main::myconfig;
1651 IR->vendor_details(\%myconfig, \%$form, @_);
1653 $main::lxdebug->leave_sub();
1657 $main::lxdebug->enter_sub();
1659 my $form = $main::form;
1663 $form->{postasnew} = 1;
1664 map { delete $form->{$_} } qw(printed emailed queued);
1668 $main::lxdebug->leave_sub();
1671 sub relink_accounts {
1672 $main::lxdebug->enter_sub();
1674 my $form = $main::form;
1675 my %myconfig = %main::myconfig;
1677 $form->{"taxaccounts"} =~ s/\s*$//;
1678 $form->{"taxaccounts"} =~ s/^\s*//;
1679 foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1680 map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber tax_id)); # add tax_id ?
1682 $form->{"taxaccounts"} = "";
1684 IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1686 $main::lxdebug->leave_sub();
1689 sub get_payment_terms_for_invoice {
1690 my $terms = $::form->{payment_id} ? SL::DB::PaymentTerm->new(id => $::form->{payment_id}) ->load
1691 : $::form->{customer_id} ? SL::DB::Customer ->new(id => $::form->{customer_id})->load->payment
1692 : $::form->{vendor_id} ? SL::DB::Vendor ->new(id => $::form->{vendor_id}) ->load->payment
1701 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
1702 my $terms = get_payment_terms_for_invoice();
1703 my $invdate = $::form->{invdate} eq 'undefined' ? DateTime->today_local : DateTime->from_kivitendo($::form->{invdate});
1704 my $duedate = $terms ? $terms->calc_date(reference_date => $invdate, due_date => $::form->{duedate})->to_kivitendo : ($::form->{duedate} || $invdate->to_kivitendo);
1706 if ($terms && $terms->auto_calculation) {
1707 $js->hide('#duedate_container')
1708 ->show('#duedate_fixed')
1709 ->html('#duedate_fixed', $duedate);
1712 $js->show('#duedate_container')
1713 ->hide('#duedate_fixed');
1716 $js->val('#duedate', $duedate)
1720 sub _update_part_information {
1721 $main::lxdebug->enter_sub();
1723 my $form = $main::form;
1725 my %part_information = IC->get_basic_part_info('id' => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ]);
1727 $form->{PART_INFORMATION} = \%part_information;
1729 foreach my $i (1..$form->{rowcount}) {
1730 next unless ($form->{"id_${i}"});
1732 my $info = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
1733 $form->{"partunit_${i}"} = $info->{unit};
1734 $form->{"weight_$i"} = $info->{weight};
1735 $form->{"part_type_$i"} = $info->{part_type};
1736 $form->{"classification_id_$i"} = $info->{classification_id};
1737 $form->{"has_sernumber_$i"} = $info->{has_sernumber};
1740 $main::lxdebug->leave_sub();
1744 return unless $::form->{id};
1745 my $helper = SL::Helper::ShippedQty->new->calculate($::form->{id});
1747 for my $i (1..$::form->{rowcount}) {
1748 if (my $oid = $::form->{"orderitems_id_$i"}) {
1749 $::form->{"ship_$i"} = $helper->shipped_qty->{$oid};
1754 sub _update_custom_variables {
1755 $main::lxdebug->enter_sub();
1757 my $form = $main::form;
1759 $form->{CVAR_CONFIGS} = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
1760 $form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
1762 $main::lxdebug->leave_sub();
1765 sub _render_custom_variables_inputs {
1766 $main::lxdebug->enter_sub(2);
1768 my $form = $main::form;
1772 if (!$form->{CVAR_CONFIGS}->{IC}) {
1773 $main::lxdebug->leave_sub();
1777 my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});
1779 # get partsgroup_id from part
1781 if ($params{part_id}) {
1782 $partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id;
1785 my $num_visible_cvars = 0;
1786 foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
1787 $cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
1789 # set partsgroup filter
1790 my $partsgroup_filtered = 0;
1791 if ($cvar->{flag_partsgroup_filter}) {
1792 if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) {
1793 $partsgroup_filtered = 1;
1797 my $hide_non_editable = 1;
1800 my $description = '';
1801 if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) {
1802 $num_visible_cvars++;
1803 $description = $cvar->{description} . ' ';
1807 my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";
1809 push @{ $params{ROW2} }, {
1810 line_break => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)),
1811 description => $description,
1814 hide_non_editable => $hide_non_editable,
1816 name_prefix => 'ic_',
1817 name_postfix => "_$params{row}",
1818 valid => $cvar->{valid},
1819 value => CVar->parse($::form->{$form_key}, $cvar),
1820 partsgroup_filtered => $partsgroup_filtered,
1825 $main::lxdebug->leave_sub(2);
1828 sub _remove_billed_or_delivered_rows {
1831 croak "Missing parameter 'quantities'" if !$params{quantities};
1833 my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
1836 my $make_key = sub {
1838 return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
1839 my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
1840 return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
1843 my $removed_rows = 0;
1845 while ($row < $::form->{rowcount}) {
1847 next unless $::form->{"id_$row"};
1849 my $parts_id = $::form->{"id_$row"};
1850 my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
1852 my $key = $make_key->($row);
1853 my $sub_qty = min($base_qty, $params{quantities}->{$key});
1854 $params{quantities}->{$key} -= $sub_qty;
1856 if (!$sub_qty || ($sub_qty != $base_qty)) {
1857 $::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
1858 push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
1865 $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
1866 $::form->{rowcount} -= $removed_rows;
1869 # TODO: both of these are makeshift so that price sources can operate on rdbo objects. if
1870 # this ever gets rewritten in controller style, throw this out
1871 sub _make_record_item {
1872 my ($row, %params) = @_;
1875 sales_order => 'OrderItem',
1876 purchase_order => 'OrderItem',
1877 sales_quotation => 'OrderItem',
1878 request_quotation => 'OrderItem',
1879 invoice => 'InvoiceItem',
1880 credit_note => 'InvoiceItem',
1881 purchase_invoice => 'InvoiceItem',
1882 purchase_delivery_order => 'DeliveryOrderItem',
1883 sales_delivery_order => 'DeliveryOrderItem',
1884 }->{$::form->{type}};
1886 return unless $class;
1888 $class = 'SL::DB::' . $class;
1890 my %translated_methods = (
1891 'SL::DB::OrderItem' => {
1893 orderitems_id => 'id',
1895 'SL::DB::DeliveryOrderItem' => {
1897 delivery_order_items_id => 'id',
1899 'SL::DB::InvoiceItem' => {
1905 eval "require $class";
1907 my $obj = $::form->{"orderitems_id_$row"}
1908 ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{"orderitems_id_$row"})
1911 for my $key (grep { /_$row$/ } keys %$::form) {
1913 $method =~ s/_$row$//;
1914 $method = $translated_methods{$class}{$method} // $method;
1915 my $value = $::form->{$key};
1916 if ($obj->meta->column($method)) {
1917 if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
1918 $obj->${\"$method\_as_date"}($value);
1919 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
1920 $obj->${\"$method\_as_number"}(($value // '') eq '' ? undef : $value);
1921 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
1922 $obj->$method(!!$value);
1923 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
1924 $obj->$method(($value // '') eq '' ? undef : $value * 1);
1926 $obj->$method($value);
1929 if ($method eq 'discount') {
1930 $obj->discount($obj->discount / 100.0);
1934 $obj->{__additional_form_attributes}{$method} = $value;
1938 if ($::form->{"id_$row"}) {
1939 $obj->part(SL::DB::Part->load_cached($::form->{"id_$row"}));
1942 if ($obj->can('qty')) {
1943 $obj->qty( $obj->qty * $params{factor});
1944 $obj->base_qty($obj->base_qty * $params{factor});
1952 sales_order => 'Order',
1953 purchase_order => 'Order',
1954 sales_quotation => 'Order',
1955 request_quotation => 'Order',
1956 purchase_delivery_order => 'DeliveryOrder',
1957 sales_delivery_order => 'DeliveryOrder',
1958 }->{$::form->{type}};
1960 if ($::form->{type} =~ /invoice|credit_note/) {
1961 $class = $::form->{vc} eq 'customer' ? 'Invoice'
1962 : $::form->{vc} eq 'vendor' ? 'PurchaseInvoice'
1963 : do { die 'unknown invoice type' };
1966 my $factor = $::form->{type} =~ m{credit_note} ? -1 : 1;
1968 return unless $class;
1970 $class = 'SL::DB::' . $class;
1972 eval "require $class";
1974 my $obj = $::form->{id}
1975 ? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{id})
1978 for my $method (keys %$::form) {
1979 next unless $obj->can($method);
1980 next unless $obj->meta->column($method);
1982 if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
1983 $obj->${\"$method\_as_date"}($::form->{$method});
1984 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
1985 $obj->${\"$method\_as_number"}(($::form->{$method} // '') eq '' ? undef : $::form->{$method});
1986 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
1987 $obj->$method(!!$::form->{$method});
1988 } elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
1989 $obj->$method(($::form->{$method} // '') eq '' ? undef : $::form->{$method} * 1);
1991 $obj->$method($::form->{$method});
1996 for my $i (1 .. $::form->{rowcount}) {
1997 next unless $::form->{"id_$i"};
1998 push @items, _make_record_item($i, factor => $factor);
2001 $obj->items(@items) if @items;
2002 $obj->is_sales(!!$obj->customer_id) if $class eq 'SL::DB::DeliveryOrder';
2004 if ($class eq 'SL::DB::Invoice') {
2005 my $paid = $factor *
2007 map { $::form->parse_amount(\%::myconfig, $::form->{$_}) }
2008 grep { m{^paid_\d+$} }
2016 sub setup_sales_purchase_print_options {
2017 my $print_form = Form->new('');
2018 $print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;
2020 $print_form->{$_} = $::form->{$_} for qw(type media printer_id storno formname groupitems);
2022 return SL::Helper::PrintOptions->get_print_options(
2023 form => $print_form,
2030 sub _get_files_for_email_dialog {
2031 my %files = map { ($_ => []) } qw(versions files vc_files part_files project_files);
2033 return %files if !$::instance_conf->get_doc_storage;
2035 if ($::form->{id}) {
2036 $files{versions} = [ SL::File->get_all_versions(object_id => $::form->{id}, object_type => $::form->{type}, file_type => 'document') ];
2037 $files{files} = [ SL::File->get_all( object_id => $::form->{id}, object_type => $::form->{type}, file_type => 'attachment') ];
2038 $files{vc_files} = [ SL::File->get_all( object_id => $::form->{vc_id}, object_type => $::form->{vc}, file_type => 'attachment') ]
2039 if $::form->{vc} && $::form->{"vc_id"};
2040 $files{project_files} = [ SL::File->get_all(object_id => $::form->{project_id}, object_type => 'project',file_type => 'attachment') ]
2041 if $::form->{project_id};
2045 uniq_by { $_->{id} }
2048 +{ id => $::form->{"id_$_"},
2049 partnumber => $::form->{"partnumber_$_"},
2051 } (1 .. $::form->{rowcount});
2053 foreach my $part (@parts) {
2054 my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
2055 push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
2058 foreach my $key (keys %files) {
2059 $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
2065 sub show_sales_purchase_email_dialog {
2069 if ($::form->{cp_id}) {
2070 $email = SL::DB::Contact->load_cached($::form->{cp_id})->cp_email;
2072 # write a dispatch table if a third type enters
2073 # check record mail for sales_invoice
2074 if ($::form->{type} eq 'invoice' && (!$email || $::instance_conf->get_invoice_mail_settings ne 'cp')) {
2075 # check for invoice_mail if defined (vc.invoice_email)
2076 $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->invoice_mail;
2077 if ($record_email) {
2078 # check if cc for contact is also wanted
2079 $email_cc = $email if ($::instance_conf->get_invoice_mail_settings eq 'invoice_mail_cc_cp');
2080 $email = $record_email;
2083 # check record mail for sales_delivery_order
2084 if ($::form->{type} eq 'sales_delivery_order') {
2085 # check for deliver_order_mail if defined (vc.delivery_order_mail)
2086 $record_email = SL::DB::Customer->load_cached($::form->{vc_id})->delivery_order_mail;
2087 if ($record_email) {
2088 # check if cc for contact is also wanted
2089 $email_cc = $email; # always cc to cp
2090 $email = $record_email;
2093 # still no email? use general mail (vc.email)
2094 if (!$email && $::form->{vc} && $::form->{vc_id}) {
2095 $email = SL::DB::Customer->load_cached($::form->{vc_id})->email if 'customer' eq $::form->{vc};
2096 $email = SL::DB::Vendor ->load_cached($::form->{vc_id})->email if 'vendor' eq $::form->{vc};
2099 $email = '' if $::form->{type} eq 'purchase_delivery_order';
2101 $::form->{language} = $::form->get_template_language(\%::myconfig);
2102 $::form->{language} = "_" . $::form->{language};
2104 my %body_params = (record_email => $record_email);
2105 if (($::form->{type} eq 'invoice') && $::form->{direct_debit}) {
2106 $body_params{translation_type} = "preset_text_invoice_direct_debit";
2107 $body_params{fallback_translation_type} = "preset_text_invoice";
2110 $::form->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
2114 subject => $::form->generate_email_subject,
2115 message => $::form->generate_email_body(%body_params),
2116 attachment_filename => $::form->generate_attachment_filename,
2117 js_send_function => 'kivi.SalesPurchase.send_email()',
2120 my %files = _get_files_for_email_dialog();
2121 my $html = $::form->parse_html_template("common/_send_email_dialog", {
2122 email_form => $email_form,
2123 show_bcc => $::auth->assert('email_bcc', 'may fail'),
2125 is_customer => $::form->{vc} eq 'customer',
2126 is_invoice_mail => ($record_email && $::form->{type} eq 'invoice'),
2127 ALL_EMPLOYEES => $::form->{all_employees},
2130 print $::form->ajax_response_header, $html;
2133 sub send_sales_purchase_email {
2134 my $type = $::form->{type};
2135 my $id = $::form->{id};
2136 my $script = $type =~ m{sales_order|purchase_order|quotation} ? 'oe.pl'
2137 : $type =~ m{delivery_} ? 'do.pl'
2140 my $email_form = delete $::form->{email_form};
2141 my %field_names = (to => 'email');
2143 $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
2145 $::form->{media} = 'email';
2147 if (($::form->{attachment_policy} // '') =~ m{^(?:old_file|no_file)$}) {
2148 $::form->send_email(\%::myconfig, 'pdf');
2151 print_form("return");
2152 Common->save_email_status(\%::myconfig, $::form);
2155 flash_later('info', $::locale->text('The email has been sent.'));
2157 print $::form->redirect_header($script . '?action=edit&id=' . $::form->escape($id) . '&type=' . $::form->escape($type));
2160 sub _maybe_attach_zugferd_data {
2163 my $record = _make_record();
2166 || !$record->can('customer')
2167 || !$record->customer
2168 || !$record->can('create_pdf_a_print_options')
2169 || !$record->can('create_zugferd_data')
2170 || !$record->customer->create_zugferd_invoices_for_this_customer;
2173 my $xmlfile = File::Temp->new;
2174 $xmlfile->print($record->create_zugferd_data);
2177 $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_a} = $record->create_pdf_a_print_options(zugferd_xmp_data => $record->create_zugferd_xmp_data);
2178 $form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_attachments} = [
2179 { source => $xmlfile,
2180 name => 'factur-x.xml',
2181 description => $::locale->text('Factur-X/ZUGFeRD invoice'),
2182 relationship => '/Alternative',
2183 mime_type => 'text/xml',
2188 if (my $e = SL::X::ZUGFeRDValidation->caught) {
2189 $::form->error($e->message);