1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 1998-2003
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
29 #======================================================================
33 #======================================================================
37 use POSIX qw(strftime);
45 use SL::MoreCommon qw(ary_diff restore_form save_form);
46 use SL::ReportGenerator;
47 use List::MoreUtils qw(uniq any none);
48 use List::Util qw(min max reduce sum);
53 use SL::DB::PaymentTerm;
55 require "bin/mozilla/io.pl";
56 require "bin/mozilla/arap.pl";
57 require "bin/mozilla/reportgenerator.pl";
68 # $locale->text('Edit the purchase_order');
69 # $locale->text('Edit the sales_order');
70 # $locale->text('Edit the request_quotation');
71 # $locale->text('Edit the sales_quotation');
73 # $locale->text('Workflow purchase_order');
74 # $locale->text('Workflow sales_order');
75 # $locale->text('Workflow request_quotation');
76 # $locale->text('Workflow sales_quotation');
79 'sales_order' => 'sales_order_edit',
80 'purchase_order' => 'purchase_order_edit',
81 'request_quotation' => 'request_quotation_edit',
82 'sales_quotation' => 'sales_quotation_edit',
86 my $form = $main::form;
88 my $right = $oe_access_map->{$form->{type}};
89 $right ||= 'DOES_NOT_EXIST';
91 $main::auth->assert($right);
94 sub check_oe_conversion_to_sales_invoice_allowed {
95 return 1 if $::form->{type} !~ m/^sales/;
96 return 1 if ($::form->{type} =~ m/quotation/) && $::instance_conf->get_allow_sales_invoice_from_sales_quotation;
97 return 1 if ($::form->{type} =~ m/order/) && $::instance_conf->get_allow_sales_invoice_from_sales_order;
99 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
105 $main::lxdebug->enter_sub();
107 my $form = $main::form;
108 my $locale = $main::locale;
114 if ($form->{type} eq 'purchase_order') {
115 $form->{title} = $action eq "edit" ?
116 $locale->text('Edit Purchase Order') :
117 $locale->text('Add Purchase Order');
118 $form->{heading} = $locale->text('Purchase Order');
119 $form->{vc} = 'vendor';
121 if ($form->{type} eq 'sales_order') {
122 $form->{title} = $action eq "edit" ?
123 $locale->text('Edit Sales Order') :
124 $locale->text('Add Sales Order');
125 $form->{heading} = $locale->text('Sales Order');
126 $form->{vc} = 'customer';
128 if ($form->{type} eq 'request_quotation') {
129 $form->{title} = $action eq "edit" ?
130 $locale->text('Edit Request for Quotation') :
131 $locale->text('Add Request for Quotation');
132 $form->{heading} = $locale->text('Request for Quotation');
133 $form->{vc} = 'vendor';
135 if ($form->{type} eq 'sales_quotation') {
136 $form->{title} = $action eq "edit" ?
137 $locale->text('Edit Quotation') :
138 $locale->text('Add Quotation');
139 $form->{heading} = $locale->text('Quotation');
140 $form->{vc} = 'customer';
143 $main::lxdebug->leave_sub();
147 $main::lxdebug->enter_sub();
149 my $form = $main::form;
156 "$form->{script}?action=add&type=$form->{type}&vc=$form->{vc}"
157 unless $form->{callback};
159 $form->{show_details} = $::myconfig{show_form_details};
165 $main::lxdebug->leave_sub();
169 $main::lxdebug->enter_sub();
171 my $form = $main::form;
175 $form->{show_details} = $::myconfig{show_form_details};
176 $form->{taxincluded_changed_by_user} = 1;
178 # show history button
179 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
180 #/show hhistory button
182 $form->{simple_save} = 0;
184 set_headings("edit");
186 # editing without stuff to edit? try adding it first
187 if ($form->{rowcount} && !$form->{print_and_save}) {
189 map { $id++ if $form->{"multi_id_$_"} } (1 .. $form->{rowcount});
193 undef $form->{rowcount};
195 $main::lxdebug->leave_sub();
198 } elsif (!$form->{id}) {
200 $main::lxdebug->leave_sub();
204 my ($language_id, $printer_id);
205 if ($form->{print_and_save}) {
206 $form->{action} = "dispatcher";
207 $form->{action_print} = "1";
208 $form->{resubmit} = 1;
209 $language_id = $form->{language_id};
210 $printer_id = $form->{printer_id};
213 set_headings("edit");
217 $form->{rowcount} = 0;
218 foreach my $ref (@{ $form->{form_details} }) {
220 map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{$ref};
225 if ($form->{print_and_save}) {
226 $form->{language_id} = $language_id;
227 $form->{printer_id} = $printer_id;
232 $main::lxdebug->leave_sub();
236 $main::lxdebug->enter_sub();
238 my $form = $main::form;
239 my %myconfig = %main::myconfig;
240 my $locale = $main::locale;
244 # get customer/vendor
245 $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
247 # retrieve order/quotation
248 my $editing = $form->{id};
250 OE->retrieve(\%myconfig, \%$form);
252 # if multiple rowcounts (== collective order) then check if the
253 # there were more than one customer (in that case OE::retrieve removes
254 # the content from the field)
255 $form->error($locale->text('Collective Orders only work for orders from one customer!'))
256 if $form->{rowcount} && $form->{type} eq 'sales_order'
257 && defined $form->{customer} && $form->{customer} eq '';
259 $form->{"$form->{vc}_id"} ||= $form->{"all_$form->{vc}"}->[0]->{id} if $form->{"all_$form->{vc}"};
261 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes shipto_id delivery_term_id currency));
263 # get customer / vendor
264 IR->get_vendor(\%myconfig, \%$form) if $form->{type} =~ /(purchase_order|request_quotation)/;
265 IS->get_customer(\%myconfig, \%$form) if $form->{type} =~ /sales_(order|quotation)/;
267 $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id shipto_id delivery_term_id));
268 $form->restore_vars(qw(currency)) if $form->{id};
269 $form->restore_vars(qw(taxincluded)) if $form->{id};
270 $form->restore_vars(qw(salesman_id)) if $editing;
271 $form->{forex} = $form->{exchangerate};
272 $form->{employee} = "$form->{employee}--$form->{employee_id}";
274 # build vendor/customer drop down comatibility... don't ask
275 if (@{ $form->{"all_$form->{vc}"} || [] }) {
276 $form->{"select$form->{vc}"} = 1;
277 $form->{$form->{vc}} = qq|$form->{$form->{vc}}--$form->{"$form->{vc}_id"}|;
280 $form->{"old$form->{vc}"} = $form->{$form->{vc}};
282 if ($form->{"old$form->{vc}"} !~ m/--\d+$/ && $form->{"$form->{vc}_id"}) {
283 $form->{"old$form->{vc}"} .= qq|--$form->{"$form->{vc}_id"}|
286 $main::lxdebug->leave_sub();
290 $main::lxdebug->enter_sub();
292 my $form = $main::form;
293 my %myconfig = %main::myconfig;
297 $form->{formname} ||= $form->{type};
299 # format discounts if values come from db. either as single id, or as a collective order
300 my $format_discounts = $form->{id} || $form->{convert_from_oe_ids};
302 for my $i (1 .. $form->{rowcount}) {
303 $form->{"reqdate_$i"} ||= $form->{"deliverydate_$i"};
304 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * ($format_discounts ? 100 : 1));
305 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
306 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
307 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
310 $main::lxdebug->leave_sub();
314 $main::lxdebug->enter_sub();
317 my $form = $main::form;
318 my %myconfig = %main::myconfig;
319 my $locale = $main::locale;
320 my $cgi = $::request->{cgi};
324 # Container for template variables. Unfortunately this has to be
325 # visible in form_footer too, so package local level and not my here.
328 my $obj = SL::DB::Order->new(id => $form->{id})->load;
329 $TMPL_VAR{warn_save_active_periodic_invoice} =
330 $obj->is_type('sales_order')
331 && $obj->periodic_invoices_config
332 && $obj->periodic_invoices_config->active
333 && ( !$obj->periodic_invoices_config->end_date
334 || ($obj->periodic_invoices_config->end_date > DateTime->today_local))
335 && $obj->periodic_invoices_config->get_previous_billed_period_start_date;
337 $TMPL_VAR{oe_obj} = $obj;
340 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
342 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
343 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
345 # openclosed checkboxes
347 push @tmp, sprintf qq|<input name="delivered" id="delivered" type="checkbox" class="checkbox" value="1" %s><label for="delivered">%s</label>|,
348 $form->{"delivered"} ? "checked" : "", $locale->text('Delivery Order(s) for full qty created') if $form->{"type"} =~ /_order$/;
349 push @tmp, sprintf qq|<input name="closed" id="closed" type="checkbox" class="checkbox" value="1" %s><label for="closed">%s</label>|,
350 $form->{"closed"} ? "checked" : "", $locale->text('Closed') if $form->{id};
351 $TMPL_VAR{openclosed} = sprintf qq|<tr><td colspan=%d align=center>%s</td></tr>\n|, 2 * scalar @tmp, join "\n", @tmp if @tmp;
353 my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
355 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
356 "currencies" => "ALL_CURRENCIES",
357 $vc => { key => "ALL_" . uc($vc),
358 limit => $myconfig{vclimit} + 1 },
359 "price_factors" => "ALL_PRICE_FACTORS");
360 $form->{ALL_PAYMENTS} = SL::DB::Manager::PaymentTerm->get_all( where => [ or => [ obsolete => 0, id => $form->{payment_id} || undef ] ]);
362 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
365 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
366 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
368 if (($vc eq 'customers') && $::instance_conf->get_customer_projects_only_in_sales) {
371 customer_id => $::form->{customer_id},
372 billable_customer_id => $::form->{customer_id},
377 and => [ active => 1, @customer_cond ],
381 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
382 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
385 my $employee_list_query_gen = sub { $::form->{$_[0]} ? [ or => [ id => $::form->{$_[0]}, deleted => 0 ] ] : [ deleted => 0 ] };
386 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => $employee_list_query_gen->('employee_id'));
387 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => $employee_list_query_gen->('salesman_id'));
388 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
389 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
391 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
393 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
396 cp_id => $::form->{cp_id} * 1
400 $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
403 $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
404 $TMPL_VAR{vclimit} = $myconfig{vclimit};
405 $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('$form->{vc}', '', @{[ $form->{vc} eq 'vendor' ? 1 : 0 ]}, 0)";
406 push @custom_hiddens, "$form->{vc}_id";
407 push @custom_hiddens, "old$form->{vc}";
408 push @custom_hiddens, "select$form->{vc}";
410 # currencies and exchangerate
411 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
412 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
413 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
414 $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
415 $TMPL_VAR{currencies} = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
416 '-values' => \@values, '-labels' => \%labels,
417 '-onchange' => "document.getElementById('update_button').click();"
418 )) if scalar @values;
419 push @custom_hiddens, "forex";
420 push @custom_hiddens, "exchangerate" if $form->{forex};
423 my $creditwarning = (($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update}) ? 1 : 0;
424 $TMPL_VAR{is_credit_remaining_negativ} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
427 $TMPL_VAR{business_label} = ($form->{vc} eq "customer" ? $locale->text('Customer type') : $locale->text('Vendor type'));
429 push @custom_hiddens, "customer_pricegroup_id" if $form->{vc} eq 'customer';
431 my $credittext = $locale->text('Credit Limit exceeded!!!');
433 my $follow_up_vc = $form->{ $form->{vc} eq 'customer' ? 'customer' : 'vendor' };
434 $follow_up_vc =~ s/--\d*\s*$//;
435 $TMPL_VAR{follow_up_trans_info} = ($form->{type} =~ /_quotation$/ ? $form->{quonumber} : $form->{ordnumber}) . " ($follow_up_vc)";
438 my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
440 if (scalar @{ $follow_ups }) {
441 $TMPL_VAR{num_follow_ups} = scalar @{ $follow_ups };
442 $TMPL_VAR{num_due_follow_ups} = sum map { $_->{due} * 1 } @{ $follow_ups };
446 my $dispatch_to_popup = '';
447 if ($form->{resubmit} && ($form->{format} eq "html")) {
448 $dispatch_to_popup = "window.open('about:blank','Beleg'); document.oe.target = 'Beleg';";
449 $dispatch_to_popup .= "document.do.submit();";
450 } elsif ($form->{resubmit}) {
451 # emulate click for resubmitting actions
452 $dispatch_to_popup = "document.oe.${_}.click(); " for grep { /^action_/ } keys %$form;
453 } elsif ($creditwarning) {
454 $::request->{layout}->add_javascripts_inline("alert('$credittext');");
457 $::request->{layout}->add_javascripts_inline("\$(function(){$dispatch_to_popup});");
458 $TMPL_VAR{dateformat} = $myconfig{dateformat};
459 $TMPL_VAR{numberformat} = $myconfig{numberformat};
461 if ($form->{type} eq 'sales_order') {
462 if (!$form->{periodic_invoices_config}) {
463 $form->{periodic_invoices_status} = $locale->text('not configured');
466 my $config = YAML::Load($form->{periodic_invoices_config});
467 $form->{periodic_invoices_status} = $config->{active} ? $locale->text('active') : $locale->text('inactive');
471 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase show_form_details show_history show_vc_details ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part));
474 if ($form->{CFDD_shipto} && $form->{CFDD_shipto_id} ) {
475 $form->{shipto_id} = $form->{CFDD_shipto_id};
478 push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
480 $TMPL_VAR{HIDDENS} = [ map { name => $_, value => $form->{$_} },
481 qw(id action type vc formname media format proforma queued printed emailed
482 title creditlimit creditremaining tradediscount business
483 max_dunning_level dunning_amount shiptoname shiptostreet shiptozipcode
484 CFDD_shipto CFDD_shipto_id shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
485 shiptodepartment_1 shiptodepartment_2 shiptoemail shiptocp_gender
486 message email subject cc bcc taxpart taxservice taxaccounts cursor_fokus
487 show_details useasnew),
489 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts} ]; # deleted: discount
493 is_sales => scalar ($form->{type} =~ /^sales_/), # these vars are exported, so that the template
494 is_order => scalar ($form->{type} =~ /_order$/), # may determine what to show
495 is_sales_quo => scalar ($form->{type} =~ /sales_quotation$/),
496 is_req_quo => scalar ($form->{type} =~ /request_quotation$/),
497 is_sales_ord => scalar ($form->{type} =~ /sales_order$/),
498 is_pur_ord => scalar ($form->{type} =~ /purchase_order$/),
501 $TMPL_VAR{ORDER_PROBABILITIES} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
503 print $form->parse_html_template("oe/form_header", { %TMPL_VAR });
505 $main::lxdebug->leave_sub();
509 $main::lxdebug->enter_sub();
511 my $form = $main::form;
512 my %myconfig = %main::myconfig;
513 my $locale = $main::locale;
517 $form->{invtotal} = $form->{invsubtotal};
519 my $introws = max 5, $form->numtextrows($form->{intnotes}, 35, 8);
521 $TMPL_VAR{notes} = qq|<textarea name="notes" class="texteditor" wrap="soft" style="width: 350px; height: 150px">| . H($form->{notes}) . qq|</textarea>|;
522 $TMPL_VAR{intnotes} = qq|<textarea name=intnotes rows="$introws" cols="35">| . H($form->{intnotes}) . qq|</textarea>|;
524 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
525 my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
526 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
529 if (!$form->{taxincluded}) {
531 foreach my $item (split / /, $form->{taxaccounts}) {
532 if ($form->{"${item}_base"}) {
533 $form->{invtotal} += $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
534 $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
536 $TMPL_VAR{tax} .= qq|
538 <th align=right>$form->{"${item}_description"} | . $form->{"${item}_rate"} * 100 .qq|%</th>
539 <td align=right>$form->{"${item}_total"}</td>
544 foreach my $item (split / /, $form->{taxaccounts}) {
545 if ($form->{"${item}_base"}) {
546 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"} / (1 + $form->{"${item}_rate"})), 2);
547 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
548 $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
549 $form->{"${item}_netto"} = $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
551 $TMPL_VAR{tax} .= qq|
553 <th align=right>Enthaltene $form->{"${item}_description"} | . $form->{"${item}_rate"} * 100 .qq|%</th>
554 <td align=right>$form->{"${item}_total"}</td>
557 <th align=right>Nettobetrag</th>
558 <td align=right>$form->{"${item}_netto"}</td>
564 my $grossamount = $form->{invtotal};
565 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1);
566 $form->{rounding} = $form->round_amount(
567 $form->{invtotal} - $form->round_amount($grossamount, 2),
570 $form->{oldinvtotal} = $form->{invtotal};
572 $TMPL_VAR{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
575 $tpca_reminder = check_transport_cost_reminder_article_number() if $::instance_conf->get_transport_cost_reminder_article_number_id;
576 print $form->parse_html_template("oe/form_footer", {
578 tpca_reminder => $tpca_reminder,
579 print_options => print_options(inline => 1),
580 label_edit => $locale->text("Edit the $form->{type}"),
581 label_workflow => $locale->text("Workflow $form->{type}"),
582 is_sales => scalar ($form->{type} =~ /^sales_/), # these vars are exported, so that the template
583 is_order => scalar ($form->{type} =~ /_order$/), # may determine what to show
584 is_sales_quo => scalar ($form->{type} =~ /sales_quotation$/),
585 is_req_quo => scalar ($form->{type} =~ /request_quotation$/),
586 is_sales_ord => scalar ($form->{type} =~ /sales_order$/),
587 is_pur_ord => scalar ($form->{type} =~ /purchase_order$/),
590 $main::lxdebug->leave_sub();
594 $main::lxdebug->enter_sub();
596 my ($recursive_call) = @_;
598 my $form = $main::form;
599 my %myconfig = %main::myconfig;
603 set_headings($form->{"id"} ? "edit" : "add");
607 &check_name($form->{vc});
609 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
610 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate) unless $recursive_call;
613 $buysell = 'sell' if ($form->{vc} eq 'vendor');
614 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
615 $form->{exchangerate} = $form->{forex} if $form->{forex};
617 my $exchangerate = $form->{exchangerate} || 1;
619 ##################### process items ######################################
621 my $i = $form->{rowcount};
622 if ( ($form->{"partnumber_$i"} eq "")
623 && ($form->{"description_$i"} eq "")
624 && ($form->{"partsgroup_$i"} eq "")) {
626 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
632 if ($form->{type} =~ /^sales/) {
633 IS->retrieve_item(\%myconfig, \%$form);
636 IR->retrieve_item(\%myconfig, \%$form);
640 my $rows = scalar @{ $form->{item_list} };
642 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
643 $form->{"discount_$i"} ||= $form->{"$form->{vc}_discount"};
645 $form->{"lastcost_$i"} = $form->parse_amount(\%myconfig, $form->{"lastcost_$i"});
649 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
650 if( !$form->{"qty_$i"} ) {
651 $form->{"qty_$i"} = 1;
656 select_item(mode => $mode, pre_entered_qty => $form->{"qty_$i"});
657 $::dispatcher->end_request;
661 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
662 # hier werden parts (Artikeleigenschaften) aus item_list (retrieve_item aus IS.pm)
663 # (item wahrscheinlich synonym für parts) entsprechend in die form geschrieben ...
665 # Wäre dieses Mapping nicht besser in retrieve_items aufgehoben?
666 #(Eine Funktion bekommt Daten -> ARBEIT -> Rückgabe DATEN)
667 # Das quot sieht doch auch nach Überarbeitung aus ... (hmm retrieve_items gibt es in IS und IR)
668 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
669 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
671 # ... deswegen muss die prüfung, ob es sich um einen nicht rabattierfähigen artikel handelt später erfolgen (Bug 1136)
672 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
673 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
675 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
677 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
678 my $dec_qty = length $1;
679 my $decimalplaces = max 2, $dec_qty;
682 $form->{"sellprice_$i"} = $sellprice;
684 my $record = _make_record();
685 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
686 my $best_price = $price_source->best_price;
687 my $best_discount = $price_source->best_discount;
690 $::form->{"sellprice_$i"} = $best_price->price;
691 $::form->{"active_price_source_$i"} = $best_price->source;
693 if ($best_discount) {
694 $::form->{"discount_$i"} = $best_discount->discount;
695 $::form->{"active_discount_source_$i"} = $best_discount->source;
698 $form->{"sellprice_$i"} /= $exchangerate; # if there is an exchange rate adjust sellprice
701 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
702 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
703 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
704 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{taxaccounts} if !$form->{taxincluded};
706 $form->{creditremaining} -= $amount;
708 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
709 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
710 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
711 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
717 # ok, so this is a new part
718 # ask if it is a part or service item
720 if ( $form->{"partsgroup_$i"}
721 && ($form->{"partsnumber_$i"} eq "")
722 && ($form->{"description_$i"} eq "")) {
724 $form->{"discount_$i"} = "";
728 $form->{"id_$i"} = 0;
733 ##################### process items ######################################
736 $main::lxdebug->leave_sub();
740 $main::lxdebug->enter_sub();
742 my $form = $main::form;
743 my %myconfig = %main::myconfig;
744 my $locale = $main::locale;
748 if ($form->{type} eq 'purchase_order') {
749 $form->{vc} = 'vendor';
750 $form->{ordnrname} = 'ordnumber';
751 $form->{title} = $locale->text('Purchase Orders');
752 $form->{ordlabel} = $locale->text('Order Number');
754 } elsif ($form->{type} eq 'request_quotation') {
755 $form->{vc} = 'vendor';
756 $form->{ordnrname} = 'quonumber';
757 $form->{title} = $locale->text('Request for Quotations');
758 $form->{ordlabel} = $locale->text('RFQ Number');
760 } elsif ($form->{type} eq 'sales_order') {
761 $form->{vc} = 'customer';
762 $form->{ordnrname} = 'ordnumber';
763 $form->{title} = $locale->text('Sales Orders');
764 $form->{ordlabel} = $locale->text('Order Number');
766 } elsif ($form->{type} eq 'sales_quotation') {
767 $form->{vc} = 'customer';
768 $form->{ordnrname} = 'quonumber';
769 $form->{title} = $locale->text('Quotations');
770 $form->{ordlabel} = $locale->text('Quotation Number');
773 $form->show_generic_error($locale->text('oe.pl::search called with unknown type'), back_button => 1);
776 # setup vendor / customer data
777 $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
778 $form->get_lists("projects" => { "key" => "ALL_PROJECTS", "all" => 1 },
779 "$form->{vc}s" => "ALL_VC",
780 "taxzones" => "ALL_TAXZONES",
781 "business_types" => "ALL_BUSINESS_TYPES",);
782 $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
783 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
785 $form->{CT_CUSTOM_VARIABLES} = CVar->get_configs('module' => 'CT');
786 ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
787 $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables' => $form->{CT_CUSTOM_VARIABLES},
788 'include_prefix' => 'l_',
789 'include_value' => 'Y');
791 # constants and subs for template
792 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
794 $form->{ORDER_PROBABILITIES} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
798 print $form->parse_html_template('oe/search', {
799 is_order => scalar($form->{type} =~ /_order/),
802 $main::lxdebug->leave_sub();
805 sub create_subtotal_row {
806 $main::lxdebug->enter_sub();
808 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
810 my $form = $main::form;
811 my %myconfig = %main::myconfig;
813 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
815 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
817 $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
819 map { $totals->{$_} = 0 } @{ $subtotal_columns };
821 $main::lxdebug->leave_sub();
827 $main::lxdebug->enter_sub();
829 my $form = $main::form;
830 my %myconfig = %main::myconfig;
831 my $locale = $main::locale;
832 my $cgi = $::request->{cgi};
836 my $ordnumber = ($form->{type} =~ /_order$/) ? "ordnumber" : "quonumber";
838 ($form->{ $form->{vc} }, $form->{"$form->{vc}_id"}) = split(/--/, $form->{ $form->{vc} });
840 report_generator_set_default_sort('transdate', 1);
842 OE->transactions(\%myconfig, \%$form);
844 $form->{rowcount} = scalar @{ $form->{OE} };
847 "transdate", "reqdate",
848 "id", $ordnumber, "edit_exp",
849 "cusordnumber", "customernumber",
852 "remaining_netamount", "remaining_amount",
855 "shipvia", "globalprojectnumber",
856 "transaction_description", "open",
857 "delivered", "periodic_invoices",
858 "marge_total", "marge_percent",
860 "country", "shippingpoint",
861 "taxzone", "insertdate",
862 "order_probability", "expected_billing_date", "expected_netamount",
866 # only show checkboxes if gotten here via sales_order form.
867 my $allow_multiple_orders = $form->{type} eq 'sales_order';
868 if ($allow_multiple_orders) {
869 unshift @columns, "ids";
872 $form->{l_open} = $form->{l_closed} = "Y" if ($form->{open} && $form->{closed});
873 $form->{l_delivered} = "Y" if ($form->{delivered} && $form->{notdelivered});
874 $form->{l_periodic_invoices} = "Y" if ($form->{periodic_invoices_active} && $form->{periodic_invoices_inactive});
875 $form->{l_edit_exp} = "Y" if (any { $form->{type} eq $_ } qw(sales_order purchase_order));
876 map { $form->{"l_${_}"} = 'Y' } qw(order_probability expected_billing_date expected_netamount) if $form->{l_order_probability_expected_billing_date};
878 my $attachment_basename;
879 if ($form->{vc} eq 'vendor') {
880 if ($form->{type} eq 'purchase_order') {
881 $form->{title} = $locale->text('Purchase Orders');
882 $attachment_basename = $locale->text('purchase_order_list');
884 $form->{title} = $locale->text('Request for Quotations');
885 $attachment_basename = $locale->text('rfq_list');
889 if ($form->{type} eq 'sales_order') {
890 $form->{title} = $locale->text('Sales Orders');
891 $attachment_basename = $locale->text('sales_order_list');
893 $form->{title} = $locale->text('Quotations');
894 $attachment_basename = $locale->text('quotation_list');
898 my $report = SL::ReportGenerator->new(\%myconfig, $form);
900 my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
901 my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
902 my @ct_searchable_custom_variables = grep { $_->{searchable} } @{ $ct_cvar_configs };
904 my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
905 push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
907 my @hidden_variables = map { "l_${_}" } @columns;
908 push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber cusordnumber
909 transaction_description transdatefrom transdateto type vc employee_id salesman_id
910 reqdatefrom reqdateto projectnumber project_id periodic_invoices_active periodic_invoices_inactive
911 business_id shippingpoint taxzone_id reqdate_unset_or_old insertdatefrom insertdateto
912 order_probability_op order_probability_value expected_billing_date_from expected_billing_date_to
913 parts_partnumber parts_description all department_id);
914 push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
916 my @keys_for_url = grep { $form->{$_} } @hidden_variables;
917 push @keys_for_url, 'taxzone_id' if $form->{taxzone_id} ne ''; # taxzone_id could be 0
919 my $href = build_std_url('action=orders', @keys_for_url);
922 'ids' => { 'text' => '', },
923 'transdate' => { 'text' => $locale->text('Date'), },
924 'reqdate' => { 'text' => $form->{type} =~ /_order/ ? $locale->text('Required by') : $locale->text('Valid until') },
925 'id' => { 'text' => $locale->text('ID'), },
926 'ordnumber' => { 'text' => $locale->text('Order'), },
927 'quonumber' => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
928 'cusordnumber' => { 'text' => $locale->text('Customer Order Number'), },
929 'name' => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
930 'customernumber' => { 'text' => $locale->text('Customer Number'), },
931 'netamount' => { 'text' => $locale->text('Amount'), },
932 'tax' => { 'text' => $locale->text('Tax'), },
933 'amount' => { 'text' => $locale->text('Total'), },
934 'remaining_amount' => { 'text' => $locale->text('Remaining Amount'), },
935 'remaining_netamount' => { 'text' => $locale->text('Remaining Net Amount'), },
936 'curr' => { 'text' => $locale->text('Curr'), },
937 'employee' => { 'text' => $locale->text('Employee'), },
938 'salesman' => { 'text' => $locale->text('Salesman'), },
939 'shipvia' => { 'text' => $locale->text('Ship via'), },
940 'globalprojectnumber' => { 'text' => $locale->text('Project Number'), },
941 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
942 'open' => { 'text' => $locale->text('Open'), },
943 'delivered' => { 'text' => $locale->text('Delivery Order created'), },
944 'marge_total' => { 'text' => $locale->text('Ertrag'), },
945 'marge_percent' => { 'text' => $locale->text('Ertrag prozentual'), },
946 'vcnumber' => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer Number') : $locale->text('Vendor Number'), },
947 'country' => { 'text' => $locale->text('Country'), },
948 'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
949 'periodic_invoices' => { 'text' => $locale->text('Per. Inv.'), },
950 'shippingpoint' => { 'text' => $locale->text('Shipping Point'), },
951 'taxzone' => { 'text' => $locale->text('Steuersatz'), },
952 'insertdate' => { 'text' => $locale->text('Insert Date'), },
953 'order_probability' => { 'text' => $locale->text('Order probability'), },
954 'expected_billing_date' => { 'text' => $locale->text('Exp. bill. date'), },
955 'expected_netamount' => { 'text' => $locale->text('Exp. netamount'), },
956 'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
957 'edit_exp' => { 'text' => $locale->text('Edit (experimental)'), },
961 foreach my $name (qw(id transdate reqdate quonumber ordnumber cusordnumber name employee salesman shipvia transaction_description shippingpoint taxzone insertdate payment_terms)) {
962 my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
963 $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
966 my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr remaining_amount remaining_netamount order_probability expected_billing_date expected_netamount);
968 $form->{"l_type"} = "Y";
969 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
970 $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
972 $report->set_columns(%column_defs);
973 $report->set_column_order(@columns);
974 $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
975 $report->set_sort_indicator($form->{sort}, $form->{sortdir});
977 CVar->add_custom_variables_to_report('module' => 'CT',
978 'trans_id_field' => "$form->{vc}_id",
979 'configs' => $ct_cvar_configs,
980 'column_defs' => \%column_defs,
981 'data' => $form->{OE});
985 push @options, $locale->text('Customer') . " : $form->{customer}" if $form->{customer};
986 push @options, $locale->text('Vendor') . " : $form->{vendor}" if $form->{vendor};
987 push @options, $locale->text('Contact Person') . " : $form->{cp_name}" if $form->{cp_name};
988 push @options, $locale->text('Department') . " : $form->{department}" if $form->{department};
989 push @options, $locale->text('Order Number') . " : $form->{ordnumber}" if $form->{ordnumber};
990 push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}" if $form->{cusordnumber};
991 push @options, $locale->text('Notes') . " : $form->{notes}" if $form->{notes};
992 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if $form->{transaction_description};
993 push @options, $locale->text('Quick Search') . " : $form->{all}" if $form->{all};
994 push @options, $locale->text('Shipping Point') . " : $form->{shippingpoint}" if $form->{shippingpoint};
995 push @options, $locale->text('Part Description') . " : $form->{parts_description}" if $form->{parts_description};
996 push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}" if $form->{parts_partnumber};
997 if ( $form->{transdatefrom} or $form->{transdateto} ) {
998 push @options, $locale->text('Order Date');
999 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1) if $form->{transdatefrom};
1000 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1) if $form->{transdateto};
1002 if ( $form->{reqdatefrom} or $form->{reqdateto} ) {
1003 push @options, $locale->text('Delivery Date');
1004 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{reqdatefrom}, 1) if $form->{reqdatefrom};
1005 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{reqdateto}, 1) if $form->{reqdateto};
1007 if ( $form->{insertdatefrom} or $form->{insertdateto} ) {
1008 push @options, $locale->text('Insert Date');
1009 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1) if $form->{insertdatefrom};
1010 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{insertdateto}, 1) if $form->{insertdateto};
1012 push @options, $locale->text('Open') if $form->{open};
1013 push @options, $locale->text('Closed') if $form->{closed};
1014 push @options, $locale->text('Delivery Order created') if $form->{delivered};
1015 push @options, $locale->text('Not delivered') if $form->{notdelivered};
1016 push @options, $locale->text('Periodic invoices active') if $form->{periodic_invoices_active};
1017 push @options, $locale->text('Reqdate not set or before current month') if $form->{reqdate_unset_or_old};
1019 if ($form->{business_id}) {
1020 my $vc_type_label = $form->{vc} eq 'customer' ? $locale->text('Customer type') : $locale->text('Vendor type');
1021 push @options, $vc_type_label . " : " . SL::DB::Business->new(id => $form->{business_id})->load->description;
1023 if ($form->{taxzone_id} ne '') { # taxzone_id could be 0
1024 push @options, $locale->text('Steuersatz') . " : " . SL::DB::TaxZone->new(id => $form->{taxzone_id})->load->description;
1027 if ($form->{department_id}) {
1028 push @options, $locale->text('Department') . " : " . SL::DB::Department->new(id => $form->{department_id})->load->description;
1031 if (($form->{order_probability_value} || '') ne '') {
1032 push @options, $::locale->text('Order probability') . ' ' . ($form->{order_probability_op} eq 'le' ? '<=' : '>=') . ' ' . $form->{order_probability_value} . '%';
1035 if ($form->{expected_billing_date_from} or $form->{expected_billing_date_to}) {
1036 push @options, $locale->text('Expected billing date');
1037 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{expected_billing_date_from}, 1) if $form->{expected_billing_date_from};
1038 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{expected_billing_date_to}, 1) if $form->{expected_billing_date_to};
1041 $report->set_options('top_info_text' => join("\n", @options),
1042 'raw_top_info_text' => $form->parse_html_template('oe/orders_top'),
1043 'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
1044 'output_format' => 'HTML',
1045 'title' => $form->{title},
1046 'attachment_basename' => $attachment_basename . strftime('_%Y%m%d', localtime time),
1048 $report->set_options_from_form();
1049 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1051 # add sort and escape callback, this one we use for the add sub
1052 $form->{callback} = $href .= "&sort=$form->{sort}";
1054 # escape callback for href
1055 my $callback = $form->escape($href);
1057 my @subtotal_columns = qw(netamount amount marge_total marge_percent remaining_amount remaining_netamount);
1058 push @subtotal_columns, 'expected_netamount' if $form->{l_order_probability_expected_billing_date};
1060 my %totals = map { $_ => 0 } @subtotal_columns;
1061 my %subtotals = map { $_ => 0 } @subtotal_columns;
1065 my $edit_url = build_std_url('action=edit', 'type', 'vc');
1067 foreach my $oe (@{ $form->{OE} }) {
1068 map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1070 $oe->{tax} = $oe->{amount} - $oe->{netamount};
1071 $oe->{open} = $oe->{closed} ? $locale->text('No') : $locale->text('Yes');
1072 $oe->{delivered} = $oe->{delivered} ? $locale->text('Yes') : $locale->text('No');
1073 $oe->{periodic_invoices} = $oe->{periodic_invoices} ? $locale->text('On') : $locale->text('Off');
1075 map { $subtotals{$_} += $oe->{$_};
1076 $totals{$_} += $oe->{$_} } @subtotal_columns;
1078 $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1079 $totals{marge_percent} = $totals{netamount} ? ($totals{marge_total} * 100 / $totals{netamount} ) : 0;
1081 map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent remaining_amount remaining_netamount expected_netamount);
1083 $oe->{order_probability} = ($oe->{order_probability} || 0) . '%';
1087 foreach my $column (@columns) {
1088 next if ($column eq 'ids');
1089 next if ($column eq 'edit_exp');
1091 'data' => $oe->{$column},
1092 'align' => $column_alignment{$column},
1097 'raw_data' => $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1098 . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1099 'valign' => 'center',
1100 'align' => 'center',
1103 $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1105 $row->{edit_exp}->{data} = $oe->{ordnumber};
1106 $row->{edit_exp}->{link} = build_std_url('script=controller.pl', 'action=Order/edit', "type=$form->{type}", 'id=' . E($oe->{id}));
1108 my $row_set = [ $row ];
1110 if (($form->{l_subtotal} eq 'Y')
1111 && (($idx == (scalar @{ $form->{OE} }))
1112 || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx]->{ $form->{sort} }))) {
1113 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1116 $report->add_data($row_set);
1121 $report->add_separator();
1122 $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1124 $report->generate_with_headers();
1126 $main::lxdebug->leave_sub();
1129 sub check_delivered_flag {
1130 $main::lxdebug->enter_sub();
1132 my $form = $main::form;
1133 my %myconfig = %main::myconfig;
1137 if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1138 return $main::lxdebug->leave_sub();
1141 my $all_delivered = 0;
1143 foreach my $i (1 .. $form->{rowcount}) {
1144 next if (!$form->{"id_$i"});
1146 if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1155 $form->{delivered} = 1 if $all_delivered;
1157 $main::lxdebug->leave_sub();
1160 sub save_and_close {
1161 $main::lxdebug->enter_sub();
1163 my $form = $main::form;
1164 my %myconfig = %main::myconfig;
1165 my $locale = $main::locale;
1168 $form->mtime_ischanged('oe');
1170 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1172 if ($form->{type} =~ /_order$/) {
1173 $form->isblank("transdate", $locale->text('Order Date missing!'));
1175 $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1178 my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1179 $form->{$idx} =~ s/^\s*//g;
1180 $form->{$idx} =~ s/\s*$//g;
1182 my $msg = ucfirst $form->{vc};
1183 $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1185 # $locale->text('Customer missing!');
1186 # $locale->text('Vendor missing!');
1188 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1189 if ($form->{currency} ne $form->{defaultcurrency});
1194 if($form->{payment_id}) {
1195 $payment_id = $form->{payment_id};
1198 # if the name changed get new values
1199 if (&check_name($form->{vc})) {
1200 if($form->{payment_id} eq "") {
1201 $form->{payment_id} = $payment_id;
1204 $::dispatcher->end_request;
1207 $form->{id} = 0 if $form->{saveasnew};
1209 my ($numberfld, $ordnumber, $err);
1210 # this is for the internal notes section for the [email] Subject
1211 if ($form->{type} =~ /_order$/) {
1212 if ($form->{type} eq 'sales_order') {
1213 $form->{label} = $locale->text('Sales Order');
1215 $numberfld = "sonumber";
1216 $ordnumber = "ordnumber";
1218 $form->{label} = $locale->text('Purchase Order');
1220 $numberfld = "ponumber";
1221 $ordnumber = "ordnumber";
1224 $err = $locale->text('Cannot save order!');
1226 check_delivered_flag();
1229 if ($form->{type} eq 'sales_quotation') {
1230 $form->{label} = $locale->text('Quotation');
1232 $numberfld = "sqnumber";
1233 $ordnumber = "quonumber";
1235 $form->{label} = $locale->text('Request for Quotation');
1237 $numberfld = "rfqnumber";
1238 $ordnumber = "quonumber";
1241 $err = $locale->text('Cannot save quotation!');
1245 # get new number in sequence if saveasnew was requested
1246 delete $form->{$ordnumber} if $form->{saveasnew};
1250 $form->error($err) if (!OE->save(\%myconfig, \%$form));
1252 # saving the history
1253 if(!exists $form->{addition}) {
1254 $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1255 $form->{addition} = "SAVED";
1256 $form->save_history;
1258 # /saving the history
1260 $form->redirect($form->{label} . " $form->{$ordnumber} " .
1261 $locale->text('saved!'));
1263 $main::lxdebug->leave_sub();
1267 $main::lxdebug->enter_sub();
1269 my $form = $main::form;
1270 my %myconfig = %main::myconfig;
1271 my $locale = $main::locale;
1275 $form->mtime_ischanged('oe');
1276 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1279 if ($form->{type} =~ /_order$/) {
1280 $form->isblank("transdate", $locale->text('Order Date missing!'));
1282 $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1285 my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1286 $form->{$idx} =~ s/^\s*//g;
1287 $form->{$idx} =~ s/\s*$//g;
1289 my $msg = ucfirst $form->{vc};
1290 $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1292 # $locale->text('Customer missing!');
1293 # $locale->text('Vendor missing!');
1295 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1296 if ($form->{currency} ne $form->{defaultcurrency});
1298 remove_emptied_rows();
1302 if($form->{payment_id}) {
1303 $payment_id = $form->{payment_id};
1306 # if the name changed get new values
1307 if (&check_name($form->{vc})) {
1308 if($form->{payment_id} eq "") {
1309 $form->{payment_id} = $payment_id;
1312 $::dispatcher->end_request;
1315 $form->{id} = 0 if $form->{saveasnew};
1317 my ($numberfld, $ordnumber, $err);
1319 # this is for the internal notes section for the [email] Subject
1320 if ($form->{type} =~ /_order$/) {
1321 if ($form->{type} eq 'sales_order') {
1322 $form->{label} = $locale->text('Sales Order');
1324 $numberfld = "sonumber";
1325 $ordnumber = "ordnumber";
1327 $form->{label} = $locale->text('Purchase Order');
1329 $numberfld = "ponumber";
1330 $ordnumber = "ordnumber";
1333 $err = $locale->text('Cannot save order!');
1335 check_delivered_flag();
1338 if ($form->{type} eq 'sales_quotation') {
1339 $form->{label} = $locale->text('Quotation');
1341 $numberfld = "sqnumber";
1342 $ordnumber = "quonumber";
1344 $form->{label} = $locale->text('Request for Quotation');
1346 $numberfld = "rfqnumber";
1347 $ordnumber = "quonumber";
1350 $err = $locale->text('Cannot save quotation!');
1356 OE->save(\%myconfig, \%$form);
1358 # saving the history
1359 if(!exists $form->{addition}) {
1360 if ( $form->{formname} eq 'sales_quotation' or $form->{formname} eq 'request_quotation' ) {
1361 $form->{snumbers} = qq|quonumber_| . $form->{quonumber};
1362 } elsif ( $form->{formname} eq 'sales_order' or $form->{formname} eq 'purchase_order') {
1363 $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1365 $form->{what_done} = $form->{formname};
1366 $form->{addition} = "SAVED";
1367 $form->save_history;
1369 # /saving the history
1371 $form->{simple_save} = 1;
1372 if(!$form->{print_and_save}) {
1373 delete @{$form}{ary_diff([keys %{ $form }], [qw(login id script type cursor_fokus)])};
1375 $::dispatcher->end_request;
1377 $main::lxdebug->leave_sub();
1381 $main::lxdebug->enter_sub();
1383 my $form = $main::form;
1384 my %myconfig = %main::myconfig;
1385 my $locale = $main::locale;
1390 if ($form->{type} =~ /_order$/) {
1391 $msg = $locale->text('Order deleted!');
1392 $err = $locale->text('Cannot delete order!');
1394 $msg = $locale->text('Quotation deleted!');
1395 $err = $locale->text('Cannot delete quotation!');
1397 if (OE->delete(\%myconfig, \%$form)){
1398 # saving the history
1399 if(!exists $form->{addition}) {
1400 if ( $form->{formname} eq 'sales_quotation' or $form->{formname} eq 'request_quotation' ) {
1401 $form->{snumbers} = qq|quonumber_| . $form->{quonumber};
1402 } elsif ( $form->{formname} eq 'sales_order' or $form->{formname} eq 'purchase_order') {
1403 $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1405 $form->{what_done} = $form->{formname};
1406 $form->{addition} = "DELETED";
1407 $form->save_history;
1409 # /saving the history
1411 $::dispatcher->end_request;
1415 $main::lxdebug->leave_sub();
1419 $main::lxdebug->enter_sub();
1421 my $form = $main::form;
1422 my %myconfig = %main::myconfig;
1423 my $locale = $main::locale;
1426 check_oe_conversion_to_sales_invoice_allowed();
1427 $form->mtime_ischanged('oe');
1429 $main::auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
1431 $form->{old_salesman_id} = $form->{salesman_id};
1432 $form->get_employee();
1435 if ($form->{type} =~ /_order$/) {
1437 # these checks only apply if the items don't bring their own ordnumbers/transdates.
1438 # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
1439 $form->isblank("ordnumber", $locale->text('Order Number missing!'))
1440 if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1441 $form->isblank("transdate", $locale->text('Order Date missing!'))
1442 if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1444 # also copy deliverydate from the order
1445 $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
1446 $form->{orddate} = $form->{transdate};
1448 $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
1449 $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1450 $form->{ordnumber} = "";
1451 $form->{quodate} = $form->{transdate};
1455 if ($form->{payment_id}) {
1456 $payment_id = $form->{payment_id};
1459 # if the name changed get new values
1460 if (&check_name($form->{vc})) {
1461 $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
1463 $::dispatcher->end_request;
1466 _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'billed');
1468 $form->{cp_id} *= 1;
1470 for my $i (1 .. $form->{rowcount}) {
1471 for (qw(ship qty sellprice basefactor discount)) {
1472 $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
1474 $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
1477 my ($buysell, $orddate, $exchangerate);
1478 if ( $form->{type} =~ /_order/
1479 && $form->{currency} ne $form->{defaultcurrency}) {
1481 # check if we need a new exchangerate
1482 $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
1484 $orddate = $form->current_date(\%myconfig);
1485 $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
1487 if (!$exchangerate) {
1492 $form->{convert_from_oe_ids} = $form->{id};
1493 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1494 $form->{duedate} = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1495 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1497 delete @{$form}{qw(id closed)};
1498 $form->{rowcount}--;
1501 if ( $form->{type} eq 'purchase_order'
1502 || $form->{type} eq 'request_quotation') {
1503 $form->{title} = $locale->text('Add Vendor Invoice');
1504 $form->{script} = 'ir.pl';
1509 if ( $form->{type} eq 'sales_order'
1510 || $form->{type} eq 'sales_quotation') {
1511 $form->{title} = $locale->text('Add Sales Invoice');
1512 $form->{script} = 'is.pl';
1517 # bo creates the id, reset it
1518 map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1519 $form->{ $form->{vc} } =~ s/--.*//g;
1520 $form->{type} = "invoice";
1523 $main::locale = Locale->new("$myconfig{countrycode}", "$script");
1524 $locale = $main::locale;
1526 require "bin/mozilla/$form->{script}";
1528 map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1530 my $currency = $form->{currency};
1533 $form->{currency} = $currency;
1534 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1535 $form->{exchangerate} = $form->{forex} || '';
1537 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1542 for my $i (1 .. $form->{rowcount}) {
1543 $form->{"discount_$i"} =
1544 $form->format_amount(\%myconfig, $form->{"discount_$i"});
1546 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1548 my $decimalplaces = ($dec > 2) ? $dec : 2;
1550 # copy delivery date from reqdate for order -> invoice conversion
1551 $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1552 unless $form->{"deliverydate_$i"};
1554 $form->{"sellprice_$i"} =
1555 $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1558 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1559 $dec_qty = length $dec_qty;
1561 $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1566 $main::lxdebug->leave_sub();
1569 sub save_exchangerate {
1570 $main::lxdebug->enter_sub();
1572 my $form = $main::form;
1573 my %myconfig = %main::myconfig;
1574 my $locale = $main::locale;
1576 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1577 $form->{exchangerate} =
1578 $form->parse_amount(\%myconfig, $form->{exchangerate});
1579 $form->save_exchangerate(\%myconfig, $form->{currency},
1580 $form->{exchangeratedate},
1581 $form->{exchangerate}, $form->{buysell});
1585 $main::lxdebug->leave_sub();
1589 $main::lxdebug->enter_sub();
1591 my $form = $main::form;
1595 $form->{saveasnew} = 1;
1596 map { delete $form->{$_} } qw(printed emailed queued delivered closed);
1597 $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1599 # Let kivitendo assign a new order number if the user hasn't changed the
1600 # previous one. If it has been changed manually then use it as-is.
1601 my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1602 $form->{$idx} =~ s/^\s*//g;
1603 $form->{$idx} =~ s/\s*$//g;
1604 if ($form->{saved_xyznumber} &&
1605 ($form->{saved_xyznumber} eq $form->{$idx})) {
1606 delete($form->{$idx});
1609 # clear reqdate and transdate unless changed
1610 if ( $form->{reqdate} && $form->{id} ) {
1611 my $saved_order = OE->retrieve_simple(id => $form->{id});
1612 if ( $saved_order && $saved_order->{reqdate} eq $form->{reqdate} && $saved_order->{transdate} eq $form->{transdate} ) {
1613 my $extra_days = $form->{type} eq 'sales_quotation' ? $::instance_conf->get_reqdate_interval : 1;
1614 $form->{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days)->to_kivitendo;
1615 $form->{transdate} = DateTime->today_local->to_kivitendo;
1620 $form->get_employee();
1624 $main::lxdebug->leave_sub();
1627 sub check_for_direct_delivery_yes {
1628 $main::lxdebug->enter_sub();
1630 my $form = $main::form;
1634 $form->{direct_delivery_checked} = 1;
1635 delete @{$form}{grep /^shipto/, keys %{ $form }};
1636 map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
1637 $form->{CFDD_shipto} = 1;
1639 $main::lxdebug->leave_sub();
1642 sub check_for_direct_delivery_no {
1643 $main::lxdebug->enter_sub();
1645 my $form = $main::form;
1649 $form->{direct_delivery_checked} = 1;
1650 delete @{$form}{grep /^shipto/, keys %{ $form }};
1651 $form->{CFDD_shipto} = 0;
1654 $main::lxdebug->leave_sub();
1657 sub check_for_direct_delivery {
1658 $main::lxdebug->enter_sub();
1660 my $form = $main::form;
1661 my %myconfig = %main::myconfig;
1665 if ($form->{direct_delivery_checked}
1666 || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
1667 $main::lxdebug->leave_sub();
1671 my $cvars = SL::DB::Shipto->new->cvars_by_config;
1673 if ($form->{shipto_id}) {
1674 Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
1677 map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
1680 $_->value($::form->{"CFDD_shiptocvar_" . $_->config->name}) for @{ $cvars };
1682 delete $form->{action};
1683 $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ($_ ne 'login') && ($_ ne 'password') && (ref $_ eq "") } keys %{ $form } ];
1686 print $form->parse_html_template("oe/check_for_direct_delivery", { cvars => $cvars });
1688 $main::lxdebug->leave_sub();
1690 $::dispatcher->end_request;
1693 sub purchase_order {
1694 $main::lxdebug->enter_sub();
1696 my $form = $main::form;
1697 my $locale = $main::locale;
1700 $form->mtime_ischanged('oe');
1702 $main::auth->assert('purchase_order_edit');
1704 $form->{sales_order_to_purchase_order} = 0;
1705 if ($form->{type} eq 'sales_order') {
1706 $form->{sales_order_to_purchase_order} = 1;
1707 check_for_direct_delivery();
1710 if ($form->{type} =~ /^sales_/) {
1711 delete($form->{ordnumber});
1712 delete($form->{payment_id});
1713 delete($form->{delivery_term_id});
1716 $form->{cp_id} *= 1;
1718 my $source_type = $form->{type};
1719 $form->{title} = $locale->text('Add Purchase Order');
1720 $form->{vc} = "vendor";
1721 $form->{type} = "purchase_order";
1723 $form->get_employee();
1725 poso(source_type => $form->{type});
1727 delete $form->{sales_order_to_purchase_order};
1729 $main::lxdebug->leave_sub();
1733 $main::lxdebug->enter_sub();
1735 my $form = $main::form;
1736 my $locale = $main::locale;
1739 $main::auth->assert('sales_order_edit');
1740 $form->mtime_ischanged('oe');
1742 if ($form->{type} eq "purchase_order") {
1743 delete($form->{ordnumber});
1744 $form->{"lastcost_$_"} = $form->{"sellprice_$_"} for (1..$form->{rowcount});
1747 $form->{cp_id} *= 1;
1749 my $source_type = $form->{type};
1750 $form->{title} = $locale->text('Add Sales Order');
1751 $form->{vc} = "customer";
1752 $form->{type} = "sales_order";
1754 $form->get_employee();
1756 poso(source_type => $source_type);
1758 $main::lxdebug->leave_sub();
1762 $main::lxdebug->enter_sub();
1765 my $form = $main::form;
1766 my %myconfig = %main::myconfig;
1769 $main::auth->assert('purchase_order_edit | sales_order_edit');
1771 $form->{transdate} = $form->current_date(\%myconfig);
1772 delete $form->{duedate};
1774 # "reqdate" is the validity date for a quotation and the delivery
1775 # date for an order. Therefore it makes no sense to keep the value
1776 # when converting from one into the other.
1777 delete $form->{reqdate} if ($param{source_type} =~ /_quotation$/) == ($form->{type} =~ /_quotation$/);
1779 $form->{convert_from_oe_ids} = $form->{id};
1780 $form->{closed} = 0;
1782 $form->{old_employee_id} = $form->{employee_id};
1783 $form->{old_salesman_id} = $form->{salesman_id};
1786 map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal delivered ordnumber);
1787 # this converted variable is also used for sales_order to purchase order and vice versa
1788 $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1790 # if purchase_order was generated from sales_order, use lastcost_$i as sellprice_$i
1791 # also reset discounts
1792 if ( $form->{sales_order_to_purchase_order} ) {
1793 for my $i (1 .. $form->{rowcount}) {
1794 $form->{"sellprice_${i}"} = $form->{"lastcost_${i}"};
1795 $form->{"discount_${i}"} = 0;
1799 for my $i (1 .. $form->{rowcount}) {
1800 map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice basefactor discount lastcost);
1803 my %saved_vars = map { $_ => $form->{$_} } grep { $form->{$_} } qw(currency);
1807 map { $form->{$_} = $saved_vars{$_} } keys %saved_vars;
1809 # prepare_order assumes that the discount is in db-notation (0.05) and not user-notation (5)
1810 # and therefore multiplies the values by 100 in the case of reading from db or making an order
1811 # from several quotation, so we convert this back into percent-notation for the user interface by multiplying with 0.01
1812 # ergänzung 03.10.2010 muss vor prepare_order passieren (s.a. Svens Kommentar zu Bug 1017)
1813 # das parse_amount wird oben schon ausgeführt, deswegen an dieser stelle raus (wichtig: kommawerte bei discount testen)
1814 for my $i (1 .. $form->{rowcount}) {
1815 $form->{"discount_$i"} /=100;
1821 $main::lxdebug->leave_sub();
1824 sub delivery_order {
1825 $main::lxdebug->enter_sub();
1827 my $form = $main::form;
1828 my %myconfig = %main::myconfig;
1830 $form->mtime_ischanged('oe');
1832 if ($form->{type} =~ /^sales/) {
1833 $main::auth->assert('sales_delivery_order_edit');
1835 $form->{vc} = 'customer';
1836 $form->{type} = 'sales_delivery_order';
1839 $main::auth->assert('purchase_delivery_order_edit');
1841 $form->{vc} = 'vendor';
1842 $form->{type} = 'purchase_delivery_order';
1845 $form->get_employee();
1847 require "bin/mozilla/do.pl";
1849 $form->{script} = 'do.pl';
1850 $form->{cp_id} *= 1;
1851 $form->{convert_from_oe_ids} = $form->{id};
1852 $form->{transdate} = $form->current_date(\%myconfig);
1853 delete $form->{duedate};
1855 $form->{old_employee_id} = $form->{employee_id};
1856 $form->{old_salesman_id} = $form->{salesman_id};
1858 _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'delivered');
1861 delete @{$form}{qw(id subject message cc bcc printed emailed queued creditlimit creditremaining discount tradediscount oldinvtotal closed delivered)};
1863 for my $i (1 .. $form->{rowcount}) {
1864 map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice lastcost basefactor discount);
1865 $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
1868 my %old_values = map { $_ => $form->{$_} } qw(customer_id oldcustomer customer vendor_id oldvendor vendor shipto_id);
1874 map { $form->{$_} = $old_values{$_} if ($old_values{$_}) } keys %old_values;
1876 for my $i (1 .. $form->{rowcount}) {
1877 (my $dummy, $form->{"pricegroup_id_$i"}) = split /--/, $form->{"sellprice_pg_$i"};
1881 $main::lxdebug->leave_sub();
1884 sub oe_delivery_order_from_order {
1886 return if !$::form->{id};
1888 my $order = SL::DB::Order->new(id => $::form->{id})->load;
1889 $order->flatten_to_form($::form, format_amounts => 1);
1891 # fake last empty row
1892 $::form->{rowcount}++;
1898 $main::lxdebug->enter_sub();
1900 my $form = $main::form;
1904 $form->mtime_ischanged('oe','mail');
1905 $form->{print_and_save} = 1;
1907 my $saved_form = save_form();
1911 restore_form($saved_form, 0, qw(id ordnumber quonumber));
1915 $main::lxdebug->leave_sub();
1919 call_sub($main::form->{yes_nextsub});
1923 call_sub($main::form->{no_nextsub});
1926 ######################################################################################################
1928 # ###############################################################################################
1930 $main::lxdebug->enter_sub();
1932 my $form = $main::form;
1933 my %myconfig = %main::myconfig;
1937 retrieve_partunits() if ($form->{type} =~ /_delivery_order$/);
1939 $form->{"taxaccounts"} =~ s/\s*$//;
1940 $form->{"taxaccounts"} =~ s/^\s*//;
1941 foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1942 map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1944 $form->{"taxaccounts"} = "";
1946 IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1948 $form->{rowcount}++;
1949 $form->{"project_id_$form->{rowcount}"} = $form->{globalproject_id};
1951 $form->language_payment(\%myconfig);
1953 Common::webdav_folder($form);
1958 display_row($form->{rowcount}) if $form->{rowcount};
1962 $main::lxdebug->leave_sub();
1965 sub report_for_todo_list {
1966 $main::lxdebug->enter_sub();
1968 my $form = $main::form;
1970 my $quotations = OE->transactions_for_todo_list();
1973 if (@{ $quotations }) {
1974 my $edit_url = build_std_url('script=oe.pl', 'action=edit');
1976 $content = $form->parse_html_template('oe/report_for_todo_list', { 'QUOTATIONS' => $quotations,
1977 'edit_url' => $edit_url });
1980 $main::lxdebug->leave_sub();
1985 sub edit_periodic_invoices_config {
1986 $::lxdebug->enter_sub();
1988 $::form->{type} = 'sales_order';
1993 $config = YAML::Load($::form->{periodic_invoices_config}) if $::form->{periodic_invoices_config};
1995 if ('HASH' ne ref $config) {
1996 $config = { periodicity => 'm',
1997 order_value_periodicity => 'p', # = same as periodicity
1998 start_date_as_date => $::form->{transdate} || $::form->current_date,
1999 extend_automatically_by => 12,
2004 $config->{periodicity} = 'm' if none { $_ eq $config->{periodicity} } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
2005 $config->{order_value_periodicity} = 'p' if none { $_ eq $config->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
2007 $::form->get_lists(printers => "ALL_PRINTERS",
2008 charts => { key => 'ALL_CHARTS',
2009 transdate => 'current_date' });
2011 $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
2012 $::form->{title} = $::locale->text('Edit the configuration for periodic invoices');
2014 if ($::form->{customer_id}) {
2015 $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
2018 $::form->header(no_layout => 1);
2019 print $::form->parse_html_template('oe/edit_periodic_invoices_config', $config);
2021 $::lxdebug->leave_sub();
2024 sub save_periodic_invoices_config {
2025 $::lxdebug->enter_sub();
2027 $::form->{type} = 'sales_order';
2031 $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
2033 my $config = { active => $::form->{active} ? 1 : 0,
2034 terminated => $::form->{terminated} ? 1 : 0,
2035 direct_debit => $::form->{direct_debit} ? 1 : 0,
2036 periodicity => (any { $_ eq $::form->{periodicity} } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES) ? $::form->{periodicity} : 'm',
2037 order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
2038 start_date_as_date => $::form->{start_date_as_date},
2039 end_date_as_date => $::form->{end_date_as_date},
2040 first_billing_date_as_date => $::form->{first_billing_date_as_date},
2041 print => $::form->{print} ? 1 : 0,
2042 printer_id => $::form->{print} ? $::form->{printer_id} * 1 : undef,
2043 copies => $::form->{copies} * 1 ? $::form->{copies} : 1,
2044 extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
2045 ar_chart_id => $::form->{ar_chart_id} * 1,
2046 send_email => $::form->{send_email} ? 1 : 0,
2047 email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
2048 email_recipient_address => $::form->{email_recipient_address},
2049 email_sender => $::form->{email_sender},
2050 email_subject => $::form->{email_subject},
2051 email_body => $::form->{email_body},
2054 $::form->{periodic_invoices_config} = YAML::Dump($config);
2056 $::form->{title} = $::locale->text('Edit the configuration for periodic invoices');
2058 print $::form->parse_html_template('oe/save_periodic_invoices_config', $config);
2060 $::lxdebug->leave_sub();
2063 sub _remove_full_delivered_rows {
2065 my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
2068 my $removed_rows = 0;
2070 while ($row < $::form->{rowcount}) {
2072 next unless $::form->{"id_$row"};
2073 my $base_factor = SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
2074 my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * $base_factor;
2075 my $ship_qty = $::form->parse_amount(\%::myconfig, $::form->{"ship_$row"}) * $base_factor;
2076 #$main::lxdebug->message(LXDebug->DEBUG2(),"shipto=".$ship_qty." qty=".$base_qty);
2078 if (!$ship_qty || ($ship_qty < $base_qty)) {
2079 $::form->{"qty_$row"} = $::form->format_amount(\%::myconfig, ($base_qty - $ship_qty) / $base_factor );
2080 $::form->{"ship_$row"} = 0;
2081 push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
2087 $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
2088 $::form->{rowcount} -= $removed_rows;
2091 sub _oe_remove_delivered_or_billed_rows {
2094 return if !$params{id} || !$params{type};
2096 my $ord_quot = SL::DB::Order->new(id => $params{id})->load;
2097 return if !$ord_quot;
2099 # Prüfung ob itemlinks existieren, falls ja dann neue Implementierung
2101 if ( $params{type} eq 'delivered' ) {
2102 my $orderitem = SL::DB::Manager::OrderItem->get_first( where => [trans_id => $ord_quot->id]);
2104 my @links = $orderitem->linked_records(to => 'SL::DB::DeliveryOrderItem');
2105 if ( scalar(@links ) > 0 ) {
2106 #$main::lxdebug->message(LXDebug->DEBUG2(),"item recordlinks vorhanden");
2107 return _remove_full_delivered_rows();
2113 to => $params{type} eq 'delivered' ? 'DeliveryOrder' : 'Invoice',
2114 via => [ $params{type} eq 'delivered' ? qw(Order) : qw(Order DeliveryOrder) ],
2117 my %handled_base_qtys;
2118 foreach my $record (@{ $ord_quot->linked_records(%args) }) {
2119 next if $ord_quot->is_sales != $record->is_sales;
2120 next if $record->type eq 'invoice' && $record->storno;
2122 foreach my $item (@{ $record->items }) {
2123 my $key = $item->parts_id;
2124 $key .= ':' . $item->serialnumber if $item->serialnumber;
2125 $handled_base_qtys{$key} += $item->qty * $item->unit_obj->base_factor;
2129 _remove_billed_or_delivered_rows(quantities => \%handled_base_qtys);
2132 # iterate all positions and match articlenumber
2133 sub check_transport_cost_reminder_article_number {
2134 $main::lxdebug->enter_sub();
2136 my $form = $main::form;
2140 my $transport_article_id = $::instance_conf->get_transport_cost_reminder_article_number_id;
2141 for my $i (1 .. $form->{rowcount}) {
2142 return if $form->{"id_${i}"} eq $transport_article_id;
2145 # simply return the name of the part
2146 return SL::DB::Part->new(id => $transport_article_id)->load()->partnumber;
2148 $main::lxdebug->leave_sub();
2151 foreach my $action (qw(delete delivery_order e_mail invoice print purchase_order quotation
2152 request_for_quotation sales_order save save_and_close save_as_new ship_to update)) {
2153 if ($::form->{"action_${action}"}) {
2159 $::form->error($::locale->text('No action defined.'));