1 package SL::Controller::Order;
4 use parent qw(SL::Controller::Base);
6 use SL::Helper::Flash qw(flash_later);
8 use SL::Presenter::Tag qw(select_tag hidden_tag div_tag);
9 use SL::Locale::String qw(t8);
10 use SL::SessionFile::Random;
15 use SL::Util qw(trim);
17 use SL::DB::AdditionalBillingAddress;
24 use SL::DB::PartClassification;
25 use SL::DB::PartsGroup;
28 use SL::DB::RecordLink;
29 use SL::DB::RequirementSpec;
31 use SL::DB::Translation;
33 use SL::Helper::CreatePDF qw(:all);
34 use SL::Helper::PrintOptions;
35 use SL::Helper::ShippedQty;
36 use SL::Helper::UserPreferences::PositionsScrollbar;
37 use SL::Helper::UserPreferences::UpdatePositions;
39 use SL::Controller::Helper::GetModels;
41 use List::Util qw(first sum0);
42 use List::UtilsBy qw(sort_by uniq_by);
43 use List::MoreUtils qw(any none pairwise first_index);
44 use English qw(-no_match_vars);
49 use Rose::Object::MakeMethods::Generic
51 scalar => [ qw(item_ids_to_delete is_custom_shipto_to_delete) ],
52 'scalar --get_set_init' => [ qw(order valid_types type cv p all_price_factors search_cvpartnumber show_update_button part_picker_classification_ids) ],
57 __PACKAGE__->run_before('check_auth');
59 __PACKAGE__->run_before('check_auth_for_edit',
60 except => [ qw(edit show_customer_vendor_details_dialog price_popup load_second_rows) ]);
62 __PACKAGE__->run_before('recalc',
63 only => [ qw(save save_as_new save_and_delivery_order save_and_invoice save_and_invoice_for_advance_payment save_and_final_invoice save_and_ap_transaction
66 __PACKAGE__->run_before('get_unalterable_data',
67 only => [ qw(save save_as_new save_and_delivery_order save_and_invoice save_and_invoice_for_advance_payment save_and_final_invoice save_and_ap_transaction
78 $self->order->transdate(DateTime->now_local());
79 my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval :
80 $self->type eq sales_order_type() ? $::instance_conf->get_delivery_date_interval : 1;
82 if ( ($self->type eq sales_order_type() && $::instance_conf->get_deliverydate_on)
83 || ($self->type eq sales_quotation_type() && $::instance_conf->get_reqdate_on)
84 && (!$self->order->reqdate)) {
85 $self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days));
92 title => $self->get_title_for('add'),
93 %{$self->{template_args}}
97 # edit an existing order
105 # this is to edit an order from an unsaved order object
107 # set item ids to new fake id, to identify them as new items
108 foreach my $item (@{$self->order->items_sorted}) {
109 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
111 # trigger rendering values for second row as hidden, because they
112 # are loaded only on demand. So we need to keep the values from
114 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
121 title => $self->get_title_for('edit'),
122 %{$self->{template_args}}
126 # edit a collective order (consisting of one or more existing orders)
127 sub action_edit_collective {
131 my @multi_ids = map {
132 $_ =~ m{^multi_id_(\d+)$} && $::form->{'multi_id_' . $1} && $::form->{'trans_id_' . $1} && $::form->{'trans_id_' . $1}
133 } grep { $_ =~ m{^multi_id_\d+$} } keys %$::form;
135 # fall back to add if no ids are given
136 if (scalar @multi_ids == 0) {
141 # fall back to save as new if only one id is given
142 if (scalar @multi_ids == 1) {
143 $self->order(SL::DB::Order->new(id => $multi_ids[0])->load);
144 $self->action_save_as_new();
148 # make new order from given orders
149 my @multi_orders = map { SL::DB::Order->new(id => $_)->load } @multi_ids;
150 $self->{converted_from_oe_id} = join ' ', map { $_->id } @multi_orders;
151 $self->order(SL::DB::Order->new_from_multi(\@multi_orders, sort_sources_by => 'transdate'));
153 $self->action_edit();
160 my $errors = $self->delete();
162 if (scalar @{ $errors }) {
163 $self->js->flash('error', $_) foreach @{ $errors };
164 return $self->js->render();
167 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been deleted')
168 : $self->type eq purchase_order_type() ? $::locale->text('The order has been deleted')
169 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been deleted')
170 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been deleted')
172 flash_later('info', $text);
174 my @redirect_params = (
179 $self->redirect_to(@redirect_params);
186 my $errors = $self->save();
188 if (scalar @{ $errors }) {
189 $self->js->flash('error', $_) foreach @{ $errors };
190 return $self->js->render();
193 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
194 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
195 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
196 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
198 flash_later('info', $text);
200 my @redirect_params = (
203 id => $self->order->id,
206 $self->redirect_to(@redirect_params);
209 # save the order as new document an open it for edit
210 sub action_save_as_new {
213 my $order = $self->order;
216 $self->js->flash('error', t8('This object has not been saved yet.'));
217 return $self->js->render();
220 # load order from db to check if values changed
221 my $saved_order = SL::DB::Order->new(id => $order->id)->load;
224 # Lets assign a new number if the user hasn't changed the previous one.
225 # If it has been changed manually then use it as-is.
226 $new_attrs{number} = (trim($order->number) eq $saved_order->number)
228 : trim($order->number);
230 # Clear transdate unless changed
231 $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
232 ? DateTime->today_local
235 # Set new reqdate unless changed if it is enabled in client config
236 if ($order->reqdate == $saved_order->reqdate) {
237 my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval :
238 $self->type eq sales_order_type() ? $::instance_conf->get_delivery_date_interval : 1;
240 if ( ($self->type eq sales_order_type() && !$::instance_conf->get_deliverydate_on)
241 || ($self->type eq sales_quotation_type() && !$::instance_conf->get_reqdate_on)) {
242 $new_attrs{reqdate} = '';
244 $new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
247 $new_attrs{reqdate} = $order->reqdate;
251 $new_attrs{employee} = SL::DB::Manager::Employee->current;
253 # Create new record from current one
254 $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
256 # no linked records on save as new
257 delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
260 $self->action_save();
265 # This is called if "print" is pressed in the print dialog.
266 # If PDF creation was requested and succeeded, the pdf is offered for download
267 # via send_file (which uses ajax in this case).
271 my $errors = $self->save();
273 if (scalar @{ $errors }) {
274 $self->js->flash('error', $_) foreach @{ $errors };
275 return $self->js->render();
278 $self->js_reset_order_and_item_ids_after_save;
280 my $format = $::form->{print_options}->{format};
281 my $media = $::form->{print_options}->{media};
282 my $formname = $::form->{print_options}->{formname};
283 my $copies = $::form->{print_options}->{copies};
284 my $groupitems = $::form->{print_options}->{groupitems};
285 my $printer_id = $::form->{print_options}->{printer_id};
287 # only PDF, OpenDocument & HTML for now
288 if (none { $format eq $_ } qw(pdf opendocument opendocument_pdf html)) {
289 return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
292 # only screen or printer by now
293 if (none { $media eq $_ } qw(screen printer)) {
294 return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
297 # create a form for generate_attachment_filename
298 my $form = Form->new;
299 $form->{$self->nr_key()} = $self->order->number;
300 $form->{type} = $self->type;
301 $form->{format} = $format;
302 $form->{formname} = $formname;
303 $form->{language} = '_' . $self->order->language->template_code if $self->order->language;
304 my $doc_filename = $form->generate_attachment_filename();
307 my @errors = $self->generate_doc(\$doc, { media => $media,
309 formname => $formname,
310 language => $self->order->language,
311 printer_id => $printer_id,
312 groupitems => $groupitems });
313 if (scalar @errors) {
314 return $self->js->flash('error', t8('Generating the document failed: #1', $errors[0]))->render;
317 if ($media eq 'screen') {
319 $self->js->flash('info', t8('The document has been created.'));
322 type => SL::MIME->mime_type_from_ext($doc_filename),
323 name => $doc_filename,
327 } elsif ($media eq 'printer') {
329 my $printer_id = $::form->{print_options}->{printer_id};
330 SL::DB::Printer->new(id => $printer_id)->load->print_document(
335 $self->js->flash('info', t8('The document has been printed.'));
338 my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $doc_filename, $formname);
339 if (scalar @warnings) {
340 $self->js->flash('warning', $_) for @warnings;
343 $self->save_history('PRINTED');
346 ->run('kivi.ActionBar.setEnabled', '#save_and_email_action')
349 sub action_preview_pdf {
352 my $errors = $self->save();
353 if (scalar @{ $errors }) {
354 $self->js->flash('error', $_) foreach @{ $errors };
355 return $self->js->render();
358 $self->js_reset_order_and_item_ids_after_save;
361 my $media = 'screen';
362 my $formname = $self->type;
365 # create a form for generate_attachment_filename
366 my $form = Form->new;
367 $form->{$self->nr_key()} = $self->order->number;
368 $form->{type} = $self->type;
369 $form->{format} = $format;
370 $form->{formname} = $formname;
371 $form->{language} = '_' . $self->order->language->template_code if $self->order->language;
372 my $pdf_filename = $form->generate_attachment_filename();
375 my @errors = $self->generate_doc(\$pdf, { media => $media,
377 formname => $formname,
378 language => $self->order->language,
380 if (scalar @errors) {
381 return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
383 $self->save_history('PREVIEWED');
384 $self->js->flash('info', t8('The PDF has been previewed'));
388 type => SL::MIME->mime_type_from_ext($pdf_filename),
389 name => $pdf_filename,
394 # open the email dialog
395 sub action_save_and_show_email_dialog {
398 my $errors = $self->save();
400 if (scalar @{ $errors }) {
401 $self->js->flash('error', $_) foreach @{ $errors };
402 return $self->js->render();
405 my $cv_method = $self->cv;
407 if (!$self->order->$cv_method) {
408 return $self->js->flash('error', $self->cv eq 'customer' ? t8('Cannot send E-mail without customer given') : t8('Cannot send E-mail without vendor given'))
413 $email_form->{to} = $self->order->contact->cp_email if $self->order->contact;
414 $email_form->{to} ||= $self->order->$cv_method->email;
415 $email_form->{cc} = $self->order->$cv_method->cc;
416 $email_form->{bcc} = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
417 # Todo: get addresses from shipto, if any
419 my $form = Form->new;
420 $form->{$self->nr_key()} = $self->order->number;
421 $form->{cusordnumber} = $self->order->cusordnumber;
422 $form->{formname} = $self->type;
423 $form->{type} = $self->type;
424 $form->{language} = '_' . $self->order->language->template_code if $self->order->language;
425 $form->{language_id} = $self->order->language->id if $self->order->language;
426 $form->{format} = 'pdf';
427 $form->{cp_id} = $self->order->contact->cp_id if $self->order->contact;
429 $email_form->{subject} = $form->generate_email_subject();
430 $email_form->{attachment_filename} = $form->generate_attachment_filename();
431 $email_form->{message} = $form->generate_email_body();
432 $email_form->{js_send_function} = 'kivi.Order.send_email()';
434 my %files = $self->get_files_for_email_dialog();
436 my @employees_with_email = grep {
437 my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
438 $user && !!trim($user->get_config_value('email'));
439 } @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
441 my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
442 email_form => $email_form,
443 show_bcc => $::auth->assert('email_bcc', 'may fail'),
445 is_customer => $self->cv eq 'customer',
446 ALL_EMPLOYEES => \@employees_with_email,
450 ->run('kivi.Order.show_email_dialog', $dialog_html)
457 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
458 sub action_send_email {
461 my $errors = $self->save();
463 if (scalar @{ $errors }) {
464 $self->js->run('kivi.Order.close_email_dialog');
465 $self->js->flash('error', $_) foreach @{ $errors };
466 return $self->js->render();
469 $self->js_reset_order_and_item_ids_after_save;
471 my $email_form = delete $::form->{email_form};
472 my %field_names = (to => 'email');
474 $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
476 # for Form::cleanup which may be called in Form::send_email
477 $::form->{cwd} = getcwd();
478 $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
480 $::form->{$_} = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
481 $::form->{media} = 'email';
483 $::form->{attachment_policy} //= '';
485 # Is an old file version available?
487 if ($::form->{attachment_policy} eq 'old_file') {
488 $attfile = SL::File->get_all(object_id => $self->order->id,
489 object_type => $self->type,
490 file_type => 'document',
491 print_variant => $::form->{formname});
494 if ($::form->{attachment_policy} ne 'no_file' && !($::form->{attachment_policy} eq 'old_file' && $attfile)) {
496 my @errors = $self->generate_doc(\$doc, {media => $::form->{media},
497 format => $::form->{print_options}->{format},
498 formname => $::form->{print_options}->{formname},
499 language => $self->order->language,
500 printer_id => $::form->{print_options}->{printer_id},
501 groupitems => $::form->{print_options}->{groupitems}});
502 if (scalar @errors) {
503 return $self->js->flash('error', t8('Generating the document failed: #1', $errors[0]))->render($self);
506 my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $::form->{attachment_filename}, $::form->{formname});
507 if (scalar @warnings) {
508 flash_later('warning', $_) for @warnings;
511 my $sfile = SL::SessionFile::Random->new(mode => "w");
512 $sfile->fh->print($doc);
515 $::form->{tmpfile} = $sfile->file_name;
516 $::form->{tmpdir} = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
519 $::form->{id} = $self->order->id; # this is used in SL::Mailer to create a linked record to the mail
520 $::form->send_email(\%::myconfig, $::form->{print_options}->{format});
523 my $intnotes = $self->order->intnotes;
524 $intnotes .= "\n\n" if $self->order->intnotes;
525 $intnotes .= t8('[email]') . "\n";
526 $intnotes .= t8('Date') . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
527 $intnotes .= t8('To (email)') . ": " . $::form->{email} . "\n";
528 $intnotes .= t8('Cc') . ": " . $::form->{cc} . "\n" if $::form->{cc};
529 $intnotes .= t8('Bcc') . ": " . $::form->{bcc} . "\n" if $::form->{bcc};
530 $intnotes .= t8('Subject') . ": " . $::form->{subject} . "\n\n";
531 $intnotes .= t8('Message') . ": " . SL::HTML::Util->strip($::form->{message});
533 $self->order->update_attributes(intnotes => $intnotes);
535 $self->save_history('MAILED');
537 flash_later('info', t8('The email has been sent.'));
539 my @redirect_params = (
542 id => $self->order->id,
545 $self->redirect_to(@redirect_params);
548 # open the periodic invoices config dialog
550 # If there are values in the form (i.e. dialog was opened before),
551 # then use this values. Create new ones, else.
552 sub action_show_periodic_invoices_config_dialog {
555 my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
556 $config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
557 $config ||= SL::DB::PeriodicInvoicesConfig->new(periodicity => 'm',
558 order_value_periodicity => 'p', # = same as periodicity
559 start_date_as_date => $::form->{transdate_as_date} || $::form->current_date,
560 extend_automatically_by => 12,
562 email_subject => GenericTranslations->get(
563 language_id => $::form->{language_id},
564 translation_type =>"preset_text_periodic_invoices_email_subject"),
565 email_body => GenericTranslations->get(
566 language_id => $::form->{language_id},
567 translation_type => "salutation_general")
568 . GenericTranslations->get(
569 language_id => $::form->{language_id},
570 translation_type => "salutation_punctuation_mark") . "\n\n"
571 . GenericTranslations->get(
572 language_id => $::form->{language_id},
573 translation_type =>"preset_text_periodic_invoices_email_body"),
575 # for older configs, replace email preset text if not yet set.
576 $config->email_subject(GenericTranslations->get(
577 language_id => $::form->{language_id},
578 translation_type =>"preset_text_periodic_invoices_email_subject")
579 ) unless $config->email_subject;
581 $config->email_body(GenericTranslations->get(
582 language_id => $::form->{language_id},
583 translation_type => "salutation_general")
584 . GenericTranslations->get(
585 language_id => $::form->{language_id},
586 translation_type => "salutation_punctuation_mark") . "\n\n"
587 . GenericTranslations->get(
588 language_id => $::form->{language_id},
589 translation_type =>"preset_text_periodic_invoices_email_body")
590 ) unless $config->email_body;
592 $config->periodicity('m') if none { $_ eq $config->periodicity } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
593 $config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
595 $::form->get_lists(printers => "ALL_PRINTERS",
596 charts => { key => 'ALL_CHARTS',
597 transdate => 'current_date' });
599 $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
601 if ($::form->{customer_id}) {
602 $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
603 my $customer_object = SL::DB::Manager::Customer->find_by(id => $::form->{customer_id});
604 $::form->{postal_invoice} = $customer_object->postal_invoice;
605 $::form->{email_recipient_invoice_address} = $::form->{postal_invoice} ? '' : $customer_object->invoice_mail;
606 $config->send_email(0) if $::form->{postal_invoice};
609 $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
611 popup_js_close_function => 'kivi.Order.close_periodic_invoices_config_dialog()',
612 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
617 # assign the values of the periodic invoices config dialog
618 # as yaml in the hidden tag and set the status.
619 sub action_assign_periodic_invoices_config {
622 $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
624 my $config = { active => $::form->{active} ? 1 : 0,
625 terminated => $::form->{terminated} ? 1 : 0,
626 direct_debit => $::form->{direct_debit} ? 1 : 0,
627 periodicity => (any { $_ eq $::form->{periodicity} } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES) ? $::form->{periodicity} : 'm',
628 order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
629 start_date_as_date => $::form->{start_date_as_date},
630 end_date_as_date => $::form->{end_date_as_date},
631 first_billing_date_as_date => $::form->{first_billing_date_as_date},
632 print => $::form->{print} ? 1 : 0,
633 printer_id => $::form->{print} ? $::form->{printer_id} * 1 : undef,
634 copies => $::form->{copies} * 1 ? $::form->{copies} : 1,
635 extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
636 ar_chart_id => $::form->{ar_chart_id} * 1,
637 send_email => $::form->{send_email} ? 1 : 0,
638 email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
639 email_recipient_address => $::form->{email_recipient_address},
640 email_sender => $::form->{email_sender},
641 email_subject => $::form->{email_subject},
642 email_body => $::form->{email_body},
645 my $periodic_invoices_config = SL::YAML::Dump($config);
647 my $status = $self->get_periodic_invoices_status($config);
650 ->remove('#order_periodic_invoices_config')
651 ->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
652 ->run('kivi.Order.close_periodic_invoices_config_dialog')
653 ->html('#periodic_invoices_status', $status)
654 ->flash('info', t8('The periodic invoices config has been assigned.'))
658 sub action_get_has_active_periodic_invoices {
661 my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
662 $config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
664 my $has_active_periodic_invoices =
665 $self->type eq sales_order_type()
668 && (!$config->end_date || ($config->end_date > DateTime->today_local))
669 && $config->get_previous_billed_period_start_date;
671 $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
674 # save the order and redirect to the frontend subroutine for a new
676 sub action_save_and_delivery_order {
679 $self->save_and_redirect_to(
680 controller => 'oe.pl',
681 action => 'oe_delivery_order_from_order',
685 sub action_save_and_supplier_delivery_order {
688 $self->save_and_redirect_to(
689 controller => 'controller.pl',
690 action => 'DeliveryOrder/add_from_order',
691 type => 'supplier_delivery_order',
695 # save the order and redirect to the frontend subroutine for a new
697 sub action_save_and_invoice {
700 $self->save_and_redirect_to(
701 controller => 'oe.pl',
702 action => 'oe_invoice_from_order',
706 sub action_save_and_invoice_for_advance_payment {
709 $self->save_and_redirect_to(
710 controller => 'oe.pl',
711 action => 'oe_invoice_from_order',
712 new_invoice_type => 'invoice_for_advance_payment',
716 sub action_save_and_final_invoice {
719 $self->save_and_redirect_to(
720 controller => 'oe.pl',
721 action => 'oe_invoice_from_order',
722 new_invoice_type => 'final_invoice',
726 # workflow from sales order to sales quotation
727 sub action_sales_quotation {
728 $_[0]->workflow_sales_or_request_for_quotation();
731 # workflow from sales order to sales quotation
732 sub action_request_for_quotation {
733 $_[0]->workflow_sales_or_request_for_quotation();
736 # workflow from sales quotation to sales order
737 sub action_sales_order {
738 $_[0]->workflow_sales_or_purchase_order();
741 # workflow from rfq to purchase order
742 sub action_purchase_order {
743 $_[0]->workflow_sales_or_purchase_order();
746 # workflow from purchase order to ap transaction
747 sub action_save_and_ap_transaction {
750 $self->save_and_redirect_to(
751 controller => 'ap.pl',
752 action => 'add_from_purchase_order',
756 # set form elements in respect to a changed customer or vendor
758 # This action is called on an change of the customer/vendor picker.
759 sub action_customer_vendor_changed {
762 setup_order_from_cv($self->order);
765 my $cv_method = $self->cv;
767 if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
768 $self->js->show('#cp_row');
770 $self->js->hide('#cp_row');
773 if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
774 $self->js->show('#shipto_selection');
776 $self->js->hide('#shipto_selection');
779 if ($cv_method eq 'customer') {
780 my $show_hide = scalar @{ $self->order->customer->additional_billing_addresses } > 0 ? 'show' : 'hide';
781 $self->js->$show_hide('#billing_address_row');
784 $self->js->val( '#order_salesman_id', $self->order->salesman_id) if $self->order->is_sales;
787 ->replaceWith('#order_cp_id', $self->build_contact_select)
788 ->replaceWith('#order_shipto_id', $self->build_shipto_select)
789 ->replaceWith('#shipto_inputs ', $self->build_shipto_inputs)
790 ->replaceWith('#order_billing_address_id', $self->build_billing_address_select)
791 ->replaceWith('#business_info_row', $self->build_business_info_row)
792 ->val( '#order_taxzone_id', $self->order->taxzone_id)
793 ->val( '#order_taxincluded', $self->order->taxincluded)
794 ->val( '#order_currency_id', $self->order->currency_id)
795 ->val( '#order_payment_id', $self->order->payment_id)
796 ->val( '#order_delivery_term_id', $self->order->delivery_term_id)
797 ->val( '#order_intnotes', $self->order->intnotes)
798 ->val( '#order_language_id', $self->order->$cv_method->language_id)
799 ->focus( '#order_' . $self->cv . '_id')
800 ->run('kivi.Order.update_exchangerate');
802 $self->js_redisplay_amounts_and_taxes;
803 $self->js_redisplay_cvpartnumbers;
807 # open the dialog for customer/vendor details
808 sub action_show_customer_vendor_details_dialog {
811 my $is_customer = 'customer' eq $::form->{vc};
814 $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
816 $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
819 my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
820 $details{discount_as_percent} = $cv->discount_as_percent;
821 $details{creditlimt} = $cv->creditlimit_as_number;
822 $details{business} = $cv->business->description if $cv->business;
823 $details{language} = $cv->language_obj->description if $cv->language_obj;
824 $details{delivery_terms} = $cv->delivery_term->description if $cv->delivery_term;
825 $details{payment_terms} = $cv->payment->description if $cv->payment;
826 $details{pricegroup} = $cv->pricegroup->pricegroup if $is_customer && $cv->pricegroup;
829 foreach my $entry (@{ $cv->additional_billing_addresses }) {
830 push @{ $details{ADDITIONAL_BILLING_ADDRESSES} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
833 foreach my $entry (@{ $cv->shipto }) {
834 push @{ $details{SHIPTO} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
836 foreach my $entry (@{ $cv->contacts }) {
837 push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
840 $_[0]->render('common/show_vc_details', { layout => 0 },
841 is_customer => $is_customer,
846 # called if a unit in an existing item row is changed
847 sub action_unit_changed {
850 my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
851 my $item = $self->order->items_sorted->[$idx];
853 my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
854 $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
859 ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
860 $self->js_redisplay_line_values;
861 $self->js_redisplay_amounts_and_taxes;
865 # add an item row for a new item entered in the input row
866 sub action_add_item {
869 delete $::form->{add_item}->{create_part_type};
871 my $form_attr = $::form->{add_item};
873 return unless $form_attr->{parts_id};
875 my $item = new_item($self->order, $form_attr);
877 $self->order->add_items($item);
881 $self->get_item_cvpartnumber($item);
883 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
884 my $row_as_html = $self->p->render('order/tabs/_row',
890 if ($::form->{insert_before_item_id}) {
892 ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
895 ->append('#row_table_id', $row_as_html);
898 if ( $item->part->is_assortment ) {
899 $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
900 foreach my $assortment_item ( @{$item->part->assortment_items} ) {
901 my $attr = { parts_id => $assortment_item->parts_id,
902 qty => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
903 unit => $assortment_item->unit,
904 description => $assortment_item->part->description,
906 my $item = new_item($self->order, $attr);
908 # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
909 $item->discount(1) unless $assortment_item->charge;
911 $self->order->add_items( $item );
913 $self->get_item_cvpartnumber($item);
914 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
915 my $row_as_html = $self->p->render('order/tabs/_row',
920 if ($::form->{insert_before_item_id}) {
922 ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
925 ->append('#row_table_id', $row_as_html);
931 ->val('.add_item_input', '')
932 ->run('kivi.Order.init_row_handlers')
933 ->run('kivi.Order.renumber_positions')
934 ->focus('#add_item_parts_id_name');
936 $self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};
938 $self->js_redisplay_amounts_and_taxes;
942 # add item rows for multiple items at once
943 sub action_add_multi_items {
946 my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_items} };
947 return $self->js->render() unless scalar @form_attr;
950 foreach my $attr (@form_attr) {
951 my $item = new_item($self->order, $attr);
953 if ( $item->part->is_assortment ) {
954 foreach my $assortment_item ( @{$item->part->assortment_items} ) {
955 my $attr = { parts_id => $assortment_item->parts_id,
956 qty => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
957 unit => $assortment_item->unit,
958 description => $assortment_item->part->description,
960 my $item = new_item($self->order, $attr);
962 # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
963 $item->discount(1) unless $assortment_item->charge;
968 $self->order->add_items(@items);
972 foreach my $item (@items) {
973 $self->get_item_cvpartnumber($item);
974 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
975 my $row_as_html = $self->p->render('order/tabs/_row',
981 if ($::form->{insert_before_item_id}) {
983 ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
986 ->append('#row_table_id', $row_as_html);
991 ->run('kivi.Part.close_picker_dialogs')
992 ->run('kivi.Order.init_row_handlers')
993 ->run('kivi.Order.renumber_positions')
994 ->focus('#add_item_parts_id_name');
996 $self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};
998 $self->js_redisplay_amounts_and_taxes;
1002 # recalculate all linetotals, amounts and taxes and redisplay them
1003 sub action_recalc_amounts_and_taxes {
1008 $self->js_redisplay_line_values;
1009 $self->js_redisplay_amounts_and_taxes;
1010 $self->js->render();
1013 sub action_update_exchangerate {
1017 is_standard => $self->order->currency_id == $::instance_conf->get_currency_id,
1018 currency_name => $self->order->currency->name,
1019 exchangerate => $self->order->daily_exchangerate_as_null_number,
1022 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
1025 # redisplay item rows if they are sorted by an attribute
1026 sub action_reorder_items {
1030 partnumber => sub { $_[0]->part->partnumber },
1031 description => sub { $_[0]->description },
1032 qty => sub { $_[0]->qty },
1033 sellprice => sub { $_[0]->sellprice },
1034 discount => sub { $_[0]->discount },
1035 cvpartnumber => sub { $_[0]->{cvpartnumber} },
1038 $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
1040 my $method = $sort_keys{$::form->{order_by}};
1041 my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
1042 if ($::form->{sort_dir}) {
1043 if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
1044 @to_sort = sort { $a->{order_by} <=> $b->{order_by} } @to_sort;
1046 @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
1049 if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
1050 @to_sort = sort { $b->{order_by} <=> $a->{order_by} } @to_sort;
1052 @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
1056 ->run('kivi.Order.redisplay_items', \@to_sort)
1060 # show the popup to choose a price/discount source
1061 sub action_price_popup {
1064 my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
1065 my $item = $self->order->items_sorted->[$idx];
1067 $self->render_price_dialog($item);
1070 # save the order in a session variable and redirect to the part controller
1071 sub action_create_part {
1074 my $previousform = $::auth->save_form_in_session(non_scalars => 1);
1076 my $callback = $self->url_for(
1077 action => 'return_from_create_part',
1078 type => $self->type, # type is needed for check_auth on return
1079 previousform => $previousform,
1082 flash_later('info', t8('You are adding a new part while you are editing another document. You will be redirected to your document when saving the new part or aborting this form.'));
1084 my @redirect_params = (
1085 controller => 'Part',
1087 part_type => $::form->{add_item}->{create_part_type},
1088 callback => $callback,
1092 $self->redirect_to(@redirect_params);
1095 sub action_return_from_create_part {
1098 $self->{created_part} = SL::DB::Part->new(id => delete $::form->{new_parts_id})->load if $::form->{new_parts_id};
1100 $::auth->restore_form_from_session(delete $::form->{previousform});
1102 # set item ids to new fake id, to identify them as new items
1103 foreach my $item (@{$self->order->items_sorted}) {
1104 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1108 $self->get_unalterable_data();
1109 $self->pre_render();
1111 # trigger rendering values for second row/longdescription as hidden,
1112 # because they are loaded only on demand. So we need to keep the values
1114 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1115 $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1119 title => $self->get_title_for('edit'),
1120 %{$self->{template_args}}
1125 # load the second row for one or more items
1127 # This action gets the html code for all items second rows by rendering a template for
1128 # the second row and sets the html code via client js.
1129 sub action_load_second_rows {
1132 $self->recalc() if $self->order->is_sales; # for margin calculation
1134 foreach my $item_id (@{ $::form->{item_ids} }) {
1135 my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
1136 my $item = $self->order->items_sorted->[$idx];
1138 $self->js_load_second_row($item, $item_id, 0);
1141 $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
1143 $self->js->render();
1146 # update description, notes and sellprice from master data
1147 sub action_update_row_from_master_data {
1150 foreach my $item_id (@{ $::form->{item_ids} }) {
1151 my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
1152 my $item = $self->order->items_sorted->[$idx];
1153 my $texts = get_part_texts($item->part, $self->order->language_id);
1155 $item->description($texts->{description});
1156 $item->longdescription($texts->{longdescription});
1158 my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1161 if ($item->part->is_assortment) {
1162 # add assortment items with price 0, as the components carry the price
1163 $price_src = $price_source->price_from_source("");
1164 $price_src->price(0);
1166 $price_src = $price_source->best_price
1167 ? $price_source->best_price
1168 : $price_source->price_from_source("");
1169 $price_src->price($::form->round_amount($price_src->price / $self->order->exchangerate, 5)) if $self->order->exchangerate;
1170 $price_src->price(0) if !$price_source->best_price;
1174 $item->sellprice($price_src->price);
1175 $item->active_price_source($price_src);
1178 ->run('kivi.Order.update_sellprice', $item_id, $item->sellprice_as_number)
1179 ->html('.row_entry:has(#item_' . $item_id . ') [name = "partnumber"] a', $item->part->partnumber)
1180 ->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].description"]', $item->description)
1181 ->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].longdescription"]', $item->longdescription);
1183 if ($self->search_cvpartnumber) {
1184 $self->get_item_cvpartnumber($item);
1185 $self->js->html('.row_entry:has(#item_' . $item_id . ') [name = "cvpartnumber"]', $item->{cvpartnumber});
1190 $self->js_redisplay_line_values;
1191 $self->js_redisplay_amounts_and_taxes;
1193 $self->js->render();
1196 sub js_load_second_row {
1197 my ($self, $item, $item_id, $do_parse) = @_;
1200 # Parse values from form (they are formated while rendering (template)).
1201 # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1202 # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
1203 foreach my $var (@{ $item->cvars_by_config }) {
1204 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1206 $item->parse_custom_variable_values;
1209 my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);
1212 ->html('#second_row_' . $item_id, $row_as_html)
1213 ->data('#second_row_' . $item_id, 'loaded', 1);
1216 sub js_redisplay_line_values {
1219 my $is_sales = $self->order->is_sales;
1221 # sales orders with margins
1226 $::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
1227 $::form->format_amount(\%::myconfig, $_->{marge_total}, 2, 0),
1228 $::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
1229 ]} @{ $self->order->items_sorted };
1233 $::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
1234 ]} @{ $self->order->items_sorted };
1238 ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
1241 sub js_redisplay_amounts_and_taxes {
1244 if (scalar @{ $self->{taxes} }) {
1245 $self->js->show('#taxincluded_row_id');
1247 $self->js->hide('#taxincluded_row_id');
1250 if ($self->order->taxincluded) {
1251 $self->js->hide('#subtotal_row_id');
1253 $self->js->show('#subtotal_row_id');
1256 if ($self->order->is_sales) {
1257 my $is_neg = $self->order->marge_total < 0;
1259 ->html('#marge_total_id', $::form->format_amount(\%::myconfig, $self->order->marge_total, 2))
1260 ->html('#marge_percent_id', $::form->format_amount(\%::myconfig, $self->order->marge_percent, 2))
1261 ->action_if( $is_neg, 'addClass', '#marge_total_id', 'plus0')
1262 ->action_if( $is_neg, 'addClass', '#marge_percent_id', 'plus0')
1263 ->action_if( $is_neg, 'addClass', '#marge_percent_sign_id', 'plus0')
1264 ->action_if(!$is_neg, 'removeClass', '#marge_total_id', 'plus0')
1265 ->action_if(!$is_neg, 'removeClass', '#marge_percent_id', 'plus0')
1266 ->action_if(!$is_neg, 'removeClass', '#marge_percent_sign_id', 'plus0');
1270 ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
1271 ->html('#amount_id', $::form->format_amount(\%::myconfig, $self->order->amount, -2))
1272 ->remove('.tax_row')
1273 ->insertBefore($self->build_tax_rows, '#amount_row_id');
1276 sub js_redisplay_cvpartnumbers {
1279 $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
1281 my @data = map {[$_->{cvpartnumber}]} @{ $self->order->items_sorted };
1284 ->run('kivi.Order.redisplay_cvpartnumbers', \@data);
1287 sub js_reset_order_and_item_ids_after_save {
1291 ->val('#id', $self->order->id)
1292 ->val('#converted_from_oe_id', '')
1293 ->val('#order_' . $self->nr_key(), $self->order->number);
1296 foreach my $form_item_id (@{ $::form->{orderitem_ids} }) {
1297 next if !$self->order->items_sorted->[$idx]->id;
1298 next if $form_item_id !~ m{^new};
1300 ->val ('[name="orderitem_ids[+]"][value="' . $form_item_id . '"]', $self->order->items_sorted->[$idx]->id)
1301 ->val ('#item_' . $form_item_id, $self->order->items_sorted->[$idx]->id)
1302 ->attr('#item_' . $form_item_id, "id", 'item_' . $self->order->items_sorted->[$idx]->id);
1306 $self->js->val('[name="converted_from_orderitems_ids[+]"]', '');
1313 sub init_valid_types {
1314 [ sales_order_type(), purchase_order_type(), sales_quotation_type(), request_quotation_type() ];
1320 if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
1321 die "Not a valid type for order";
1324 $self->type($::form->{type});
1330 my $cv = (any { $self->type eq $_ } (sales_order_type(), sales_quotation_type())) ? 'customer'
1331 : (any { $self->type eq $_ } (purchase_order_type(), request_quotation_type())) ? 'vendor'
1332 : die "Not a valid type for order";
1337 sub init_search_cvpartnumber {
1340 my $user_prefs = SL::Helper::UserPreferences::PartPickerSearch->new();
1341 my $search_cvpartnumber;
1342 $search_cvpartnumber = !!$user_prefs->get_sales_search_customer_partnumber() if $self->cv eq 'customer';
1343 $search_cvpartnumber = !!$user_prefs->get_purchase_search_makemodel() if $self->cv eq 'vendor';
1345 return $search_cvpartnumber;
1348 sub init_show_update_button {
1351 !!SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
1362 sub init_all_price_factors {
1363 SL::DB::Manager::PriceFactor->get_all;
1366 sub init_part_picker_classification_ids {
1368 my $attribute = 'used_for_' . ($self->type =~ m{sales} ? 'sale' : 'purchase');
1370 return [ map { $_->id } @{ SL::DB::Manager::PartClassification->get_all(where => [ $attribute => 1 ]) } ];
1376 my $right_for = { map { $_ => $_.'_edit' . ' | ' . $_.'_view' } @{$self->valid_types} };
1378 my $right = $right_for->{ $self->type };
1379 $right ||= 'DOES_NOT_EXIST';
1381 $::auth->assert($right);
1384 sub check_auth_for_edit {
1387 my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
1389 my $right = $right_for->{ $self->type };
1390 $right ||= 'DOES_NOT_EXIST';
1392 $::auth->assert($right);
1395 # build the selection box for contacts
1397 # Needed, if customer/vendor changed.
1398 sub build_contact_select {
1401 select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
1402 value_key => 'cp_id',
1403 title_key => 'full_name_dep',
1404 default => $self->order->cp_id,
1406 style => 'width: 300px',
1410 # build the selection box for the additional billing address
1412 # Needed, if customer/vendor changed.
1413 sub build_billing_address_select {
1416 return '' if $self->cv ne 'customer';
1418 select_tag('order.billing_address_id',
1419 [ {displayable_id => '', id => ''}, $self->order->{$self->cv}->additional_billing_addresses ],
1421 title_key => 'displayable_id',
1422 default => $self->order->billing_address_id,
1424 style => 'width: 300px',
1428 # build the selection box for shiptos
1430 # Needed, if customer/vendor changed.
1431 sub build_shipto_select {
1434 select_tag('order.shipto_id',
1435 [ {displayable_id => t8("No/individual shipping address"), shipto_id => ''}, $self->order->{$self->cv}->shipto ],
1436 value_key => 'shipto_id',
1437 title_key => 'displayable_id',
1438 default => $self->order->shipto_id,
1440 style => 'width: 300px',
1444 # build the inputs for the cusom shipto dialog
1446 # Needed, if customer/vendor changed.
1447 sub build_shipto_inputs {
1450 my $content = $self->p->render('common/_ship_to_dialog',
1451 vc_obj => $self->order->customervendor,
1452 cs_obj => $self->order->custom_shipto,
1453 cvars => $self->order->custom_shipto->cvars_by_config,
1454 id_selector => '#order_shipto_id');
1456 div_tag($content, id => 'shipto_inputs');
1459 # render the info line for business
1461 # Needed, if customer/vendor changed.
1462 sub build_business_info_row
1464 $_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
1467 # build the rows for displaying taxes
1469 # Called if amounts where recalculated and redisplayed.
1470 sub build_tax_rows {
1474 foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
1475 $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
1477 return $rows_as_html;
1481 sub render_price_dialog {
1482 my ($self, $record_item) = @_;
1484 my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
1488 'kivi.io.price_chooser_dialog',
1489 t8('Available Prices'),
1490 $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
1495 # $self->js->text('#dialog_flash_error_content', join ' ', @errors);
1496 # $self->js->show('#dialog_flash_error');
1505 return if !$::form->{id};
1507 $self->order(SL::DB::Order->new(id => $::form->{id})->load);
1509 # Add an empty custom shipto to the order, so that the dialog can render the cvar inputs.
1510 # You need a custom shipto object to call cvars_by_config to get the cvars.
1511 $self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => [])) if !$self->order->custom_shipto;
1513 return $self->order;
1516 # load or create a new order object
1518 # And assign changes from the form to this object.
1519 # If the order is loaded from db, check if items are deleted in the form,
1520 # remove them form the object and collect them for removing from db on saving.
1521 # Then create/update items from form (via make_item) and add them.
1525 # add_items adds items to an order with no items for saving, but they cannot
1526 # be retrieved via items until the order is saved. Adding empty items to new
1527 # order here solves this problem.
1529 $order = SL::DB::Order->new(id => $::form->{id})->load(with => [ 'orderitems', 'orderitems.part' ]) if $::form->{id};
1530 $order ||= SL::DB::Order->new(orderitems => [],
1531 quotation => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type())),
1532 currency_id => $::instance_conf->get_currency_id(),);
1534 my $cv_id_method = $self->cv . '_id';
1535 if (!$::form->{id} && $::form->{$cv_id_method}) {
1536 $order->$cv_id_method($::form->{$cv_id_method});
1537 setup_order_from_cv($order);
1540 my $form_orderitems = delete $::form->{order}->{orderitems};
1541 my $form_periodic_invoices_config = delete $::form->{order}->{periodic_invoices_config};
1543 $order->assign_attributes(%{$::form->{order}});
1545 $self->setup_custom_shipto_from_form($order, $::form);
1547 if (my $periodic_invoices_config_attrs = $form_periodic_invoices_config ? SL::YAML::Load($form_periodic_invoices_config) : undef) {
1548 my $periodic_invoices_config = $order->periodic_invoices_config || $order->periodic_invoices_config(SL::DB::PeriodicInvoicesConfig->new);
1549 $periodic_invoices_config->assign_attributes(%$periodic_invoices_config_attrs);
1552 # remove deleted items
1553 $self->item_ids_to_delete([]);
1554 foreach my $idx (reverse 0..$#{$order->orderitems}) {
1555 my $item = $order->orderitems->[$idx];
1556 if (none { $item->id == $_->{id} } @{$form_orderitems}) {
1557 splice @{$order->orderitems}, $idx, 1;
1558 push @{$self->item_ids_to_delete}, $item->id;
1564 foreach my $form_attr (@{$form_orderitems}) {
1565 my $item = make_item($order, $form_attr);
1566 $item->position($pos);
1570 $order->add_items(grep {!$_->id} @items);
1575 # create or update items from form
1577 # Make item objects from form values. For items already existing read from db.
1578 # Create a new item else. And assign attributes.
1580 my ($record, $attr) = @_;
1583 $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
1585 my $is_new = !$item;
1587 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1588 # they cannot be retrieved via custom_variables until the order/orderitem is
1589 # saved. Adding empty custom_variables to new orderitem here solves this problem.
1590 $item ||= SL::DB::OrderItem->new(custom_variables => []);
1592 $item->assign_attributes(%$attr);
1595 my $texts = get_part_texts($item->part, $record->language_id);
1596 $item->longdescription($texts->{longdescription}) if !defined $attr->{longdescription};
1597 $item->project_id($record->globalproject_id) if !defined $attr->{project_id};
1598 $item->lastcost($record->is_sales ? $item->part->lastcost : 0) if !defined $attr->{lastcost_as_number};
1606 # This is used to add one item
1608 my ($record, $attr) = @_;
1610 my $item = SL::DB::OrderItem->new;
1612 # Remove attributes where the user left or set the inputs empty.
1613 # So these attributes will be undefined and we can distinguish them
1614 # from zero later on.
1615 for (qw(qty_as_number sellprice_as_number discount_as_percent)) {
1616 delete $attr->{$_} if $attr->{$_} eq '';
1619 $item->assign_attributes(%$attr);
1621 my $part = SL::DB::Part->new(id => $attr->{parts_id})->load;
1622 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
1624 $item->unit($part->unit) if !$item->unit;
1627 if ( $part->is_assortment ) {
1628 # add assortment items with price 0, as the components carry the price
1629 $price_src = $price_source->price_from_source("");
1630 $price_src->price(0);
1631 } elsif (defined $item->sellprice) {
1632 $price_src = $price_source->price_from_source("");
1633 $price_src->price($item->sellprice);
1635 $price_src = $price_source->best_price
1636 ? $price_source->best_price
1637 : $price_source->price_from_source("");
1638 $price_src->price($::form->round_amount($price_src->price / $record->exchangerate, 5)) if $record->exchangerate;
1639 $price_src->price(0) if !$price_source->best_price;
1643 if (defined $item->discount) {
1644 $discount_src = $price_source->discount_from_source("");
1645 $discount_src->discount($item->discount);
1647 $discount_src = $price_source->best_discount
1648 ? $price_source->best_discount
1649 : $price_source->discount_from_source("");
1650 $discount_src->discount(0) if !$price_source->best_discount;
1654 $new_attr{part} = $part;
1655 $new_attr{description} = $part->description if ! $item->description;
1656 $new_attr{qty} = 1.0 if ! $item->qty;
1657 $new_attr{price_factor_id} = $part->price_factor_id if ! $item->price_factor_id;
1658 $new_attr{sellprice} = $price_src->price;
1659 $new_attr{discount} = $discount_src->discount;
1660 $new_attr{active_price_source} = $price_src;
1661 $new_attr{active_discount_source} = $discount_src;
1662 $new_attr{longdescription} = $part->notes if ! defined $attr->{longdescription};
1663 $new_attr{project_id} = $record->globalproject_id;
1664 $new_attr{lastcost} = $record->is_sales ? $part->lastcost : 0;
1666 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1667 # they cannot be retrieved via custom_variables until the order/orderitem is
1668 # saved. Adding empty custom_variables to new orderitem here solves this problem.
1669 $new_attr{custom_variables} = [];
1671 my $texts = get_part_texts($part, $record->language_id, description => $new_attr{description}, longdescription => $new_attr{longdescription});
1673 $item->assign_attributes(%new_attr, %{ $texts });
1678 sub setup_order_from_cv {
1681 $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id currency_id));
1683 $order->intnotes($order->customervendor->notes);
1685 return if !$order->is_sales;
1687 $order->salesman_id($order->customer->salesman_id || SL::DB::Manager::Employee->current->id);
1688 $order->taxincluded(defined($order->customer->taxincluded_checked)
1689 ? $order->customer->taxincluded_checked
1690 : $::myconfig{taxincluded_checked});
1692 my $address = $order->customer->default_billing_address;;
1693 $order->billing_address_id($address ? $address->id : undef);
1696 # setup custom shipto from form
1698 # The dialog returns form variables starting with 'shipto' and cvars starting
1699 # with 'shiptocvar_'.
1700 # Mark it to be deleted if a shipto from master data is selected
1701 # (i.e. order has a shipto).
1702 # Else, update or create a new custom shipto. If the fields are empty, it
1703 # will not be saved on save.
1704 sub setup_custom_shipto_from_form {
1705 my ($self, $order, $form) = @_;
1707 if ($order->shipto) {
1708 $self->is_custom_shipto_to_delete(1);
1710 my $custom_shipto = $order->custom_shipto || $order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
1712 my $shipto_cvars = {map { my ($key) = m{^shiptocvar_(.+)}; $key => delete $form->{$_}} grep { m{^shiptocvar_} } keys %$form};
1713 my $shipto_attrs = {map { $_ => delete $form->{$_}} grep { m{^shipto} } keys %$form};
1715 $custom_shipto->assign_attributes(%$shipto_attrs);
1716 $custom_shipto->cvar_by_name($_)->value($shipto_cvars->{$_}) for keys %$shipto_cvars;
1720 # recalculate prices and taxes
1722 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1726 my %pat = $self->order->calculate_prices_and_taxes();
1728 $self->{taxes} = [];
1729 foreach my $tax_id (keys %{ $pat{taxes_by_tax_id} }) {
1730 my $netamount = sum0 map { $pat{amounts}->{$_}->{amount} } grep { $pat{amounts}->{$_}->{tax_id} == $tax_id } keys %{ $pat{amounts} };
1732 push(@{ $self->{taxes} }, { amount => $pat{taxes_by_tax_id}->{$tax_id},
1733 netamount => $netamount,
1734 tax => SL::DB::Tax->new(id => $tax_id)->load });
1736 pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items_sorted}, @{$pat{items}};
1739 # get data for saving, printing, ..., that is not changed in the form
1741 # Only cvars for now.
1742 sub get_unalterable_data {
1745 foreach my $item (@{ $self->order->items }) {
1746 # autovivify all cvars that are not in the form (cvars_by_config can do it).
1747 # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1748 foreach my $var (@{ $item->cvars_by_config }) {
1749 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1751 $item->parse_custom_variable_values;
1757 # And remove related files in the spool directory
1762 my $db = $self->order->db;
1764 $db->with_transaction(
1766 my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
1767 $self->order->delete;
1768 my $spool = $::lx_office_conf{paths}->{spool};
1769 unlink map { "$spool/$_" } @spoolfiles if $spool;
1771 $self->save_history('DELETED');
1774 }) || push(@{$errors}, $db->error);
1781 # And delete items that are deleted in the form.
1786 my $db = $self->order->db;
1788 $db->with_transaction(sub {
1789 # delete custom shipto if it is to be deleted or if it is empty
1790 if ($self->order->custom_shipto && ($self->is_custom_shipto_to_delete || $self->order->custom_shipto->is_empty)) {
1791 $self->order->custom_shipto->delete if $self->order->custom_shipto->shipto_id;
1792 $self->order->custom_shipto(undef);
1795 SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete || []};
1796 $self->order->save(cascade => 1);
1799 if ($::form->{converted_from_oe_id}) {
1800 my @converted_from_oe_ids = split ' ', $::form->{converted_from_oe_id};
1802 foreach my $converted_from_oe_id (@converted_from_oe_ids) {
1803 my $src = SL::DB::Order->new(id => $converted_from_oe_id)->load;
1804 $src->update_attributes(closed => 1) if $src->type =~ /_quotation$/;
1805 $src->link_to_record($self->order);
1807 if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1809 foreach (@{ $self->order->items_sorted }) {
1810 my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1812 SL::DB::RecordLink->new(from_table => 'orderitems',
1813 from_id => $from_id,
1814 to_table => 'orderitems',
1821 $self->link_requirement_specs_linking_to_created_from_objects(@converted_from_oe_ids);
1824 $self->set_project_in_linked_requirement_specs if $self->order->globalproject_id;
1826 $self->save_history('SAVED');
1829 }) || push(@{$errors}, $db->error);
1834 sub workflow_sales_or_request_for_quotation {
1838 my $errors = $self->save();
1840 if (scalar @{ $errors }) {
1841 $self->js->flash('error', $_) for @{ $errors };
1842 return $self->js->render();
1845 my $destination_type = $::form->{type} eq sales_order_type() ? sales_quotation_type() : request_quotation_type();
1847 $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1848 $self->{converted_from_oe_id} = delete $::form->{id};
1850 # set item ids to new fake id, to identify them as new items
1851 foreach my $item (@{$self->order->items_sorted}) {
1852 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1856 $::form->{type} = $destination_type;
1857 $self->type($self->init_type);
1858 $self->cv ($self->init_cv);
1862 $self->get_unalterable_data();
1863 $self->pre_render();
1865 # trigger rendering values for second row as hidden, because they
1866 # are loaded only on demand. So we need to keep the values from the
1868 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1872 title => $self->get_title_for('edit'),
1873 %{$self->{template_args}}
1877 sub workflow_sales_or_purchase_order {
1881 my $errors = $self->save();
1883 if (scalar @{ $errors }) {
1884 $self->js->flash('error', $_) foreach @{ $errors };
1885 return $self->js->render();
1888 my $destination_type = $::form->{type} eq sales_quotation_type() ? sales_order_type()
1889 : $::form->{type} eq request_quotation_type() ? purchase_order_type()
1890 : $::form->{type} eq purchase_order_type() ? sales_order_type()
1891 : $::form->{type} eq sales_order_type() ? purchase_order_type()
1894 # check for direct delivery
1895 # copy shipto in custom shipto (custom shipto will be copied by new_from() in case)
1897 if ( $::form->{type} eq sales_order_type() && $destination_type eq purchase_order_type()
1898 && $::form->{use_shipto} && $self->order->shipto) {
1899 $custom_shipto = $self->order->shipto->clone('SL::DB::Order');
1902 $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1903 $self->{converted_from_oe_id} = delete $::form->{id};
1905 # set item ids to new fake id, to identify them as new items
1906 foreach my $item (@{$self->order->items_sorted}) {
1907 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1910 if ($::form->{type} eq sales_order_type() && $destination_type eq purchase_order_type()) {
1911 if ($::form->{use_shipto}) {
1912 $self->order->custom_shipto($custom_shipto) if $custom_shipto;
1914 # remove any custom shipto if not wanted
1915 $self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
1920 $::form->{type} = $destination_type;
1921 $self->type($self->init_type);
1922 $self->cv ($self->init_cv);
1926 $self->get_unalterable_data();
1927 $self->pre_render();
1929 # trigger rendering values for second row as hidden, because they
1930 # are loaded only on demand. So we need to keep the values from the
1932 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1936 title => $self->get_title_for('edit'),
1937 %{$self->{template_args}}
1945 $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
1946 $self->{all_currencies} = SL::DB::Manager::Currency->get_all_sorted();
1947 $self->{all_departments} = SL::DB::Manager::Department->get_all_sorted();
1948 $self->{all_languages} = SL::DB::Manager::Language->get_all_sorted();
1949 $self->{all_employees} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1952 $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1955 $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1957 $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1958 $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
1959 $self->{periodic_invoices_status} = $self->get_periodic_invoices_status($self->order->periodic_invoices_config);
1960 $self->{order_probabilities} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
1961 $self->{positions_scrollbar_height} = SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
1963 my $print_form = Form->new('');
1964 $print_form->{type} = $self->type;
1965 $print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;
1966 $self->{print_options} = SL::Helper::PrintOptions->get_print_options(
1967 form => $print_form,
1968 options => {dialog_name_prefix => 'print_options.',
1972 no_opendocument => 0,
1976 foreach my $item (@{$self->order->orderitems}) {
1977 my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1978 $item->active_price_source( $price_source->price_from_source( $item->active_price_source ));
1979 $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
1982 if (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())) {
1983 # Calculate shipped qtys here to prevent calling calculate for every item via the items method.
1984 # Do not use write_to_objects to prevent order->delivered to be set, because this should be
1985 # the value from db, which can be set manually or is set when linked delivery orders are saved.
1986 SL::Helper::ShippedQty->new->calculate($self->order)->write_to(\@{$self->order->items});
1989 if ($self->order->number && $::instance_conf->get_webdav) {
1990 my $webdav = SL::Webdav->new(
1991 type => $self->type,
1992 number => $self->order->number,
1994 my @all_objects = $webdav->get_all_objects;
1995 @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1997 link => File::Spec->catfile($_->full_filedescriptor),
2001 if ( (any { $self->type eq $_ } (sales_quotation_type(), sales_order_type()))
2002 && $::instance_conf->get_transport_cost_reminder_article_number_id ) {
2003 $self->{template_args}->{transport_cost_reminder_article} = SL::DB::Part->new(id => $::instance_conf->get_transport_cost_reminder_article_number_id)->load;
2006 $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
2008 $::request->{layout}->use_javascript("${_}.js") for qw(kivi.Validator kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery
2009 edit_periodic_invoices_config calculate_qty follow_up show_history);
2010 $self->setup_edit_action_bar;
2013 sub setup_edit_action_bar {
2014 my ($self, %params) = @_;
2016 my $deletion_allowed = (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type()))
2017 || (($self->type eq sales_order_type()) && $::instance_conf->get_sales_order_show_delete)
2018 || (($self->type eq purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);
2020 my @req_trans_cost_art = qw(kivi.Order.check_transport_cost_article_presence) x!!$::instance_conf->get_transport_cost_reminder_article_number_id;
2021 my @req_cusordnumber = qw(kivi.Order.check_cusordnumber_presence) x($self->type eq sales_order_type() && $::instance_conf->get_order_warn_no_cusordnumber);
2023 my $has_invoice_for_advance_payment;
2024 if ($self->order->id && $self->type eq sales_order_type()) {
2025 my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
2026 $has_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
2029 my $has_final_invoice;
2030 if ($self->order->id && $self->type eq sales_order_type()) {
2031 my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
2032 $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->type} @$lr;
2035 my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
2036 my $right = $right_for->{ $self->type };
2037 $right ||= 'DOES_NOT_EXIST';
2039 if ($::auth->assert($right, 1)) {
2040 for my $bar ($::request->layout->get('actionbar')) {
2045 call => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
2046 $::instance_conf->get_order_warn_no_deliverydate,
2048 checks => [ 'kivi.Order.check_save_active_periodic_invoices', ['kivi.validate_form','#order_form'],
2049 @req_trans_cost_art, @req_cusordnumber,
2054 call => [ 'kivi.Order.save', 'save_as_new', $::instance_conf->get_order_warn_duplicate_parts ],
2055 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2056 @req_trans_cost_art, @req_cusordnumber,
2058 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2060 ], # end of combobox "Save"
2067 t8('Save and Quotation'),
2068 submit => [ '#order_form', { action => "Order/sales_quotation" } ],
2069 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2070 only_if => (any { $self->type eq $_ } (sales_order_type())),
2074 submit => [ '#order_form', { action => "Order/request_for_quotation" } ],
2075 only_if => (any { $self->type eq $_ } (purchase_order_type())),
2078 t8('Save and Sales Order'),
2079 submit => [ '#order_form', { action => "Order/sales_order" } ],
2080 checks => [ @req_trans_cost_art ],
2081 only_if => (any { $self->type eq $_ } (sales_quotation_type(), purchase_order_type())),
2084 t8('Save and Purchase Order'),
2085 call => [ 'kivi.Order.purchase_order_check_for_direct_delivery' ],
2086 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2087 only_if => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
2090 t8('Save and Delivery Order'),
2091 call => [ 'kivi.Order.save', 'save_and_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
2092 $::instance_conf->get_order_warn_no_deliverydate,
2094 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2095 @req_trans_cost_art, @req_cusordnumber,
2097 only_if => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type()))
2100 t8('Save and Supplier Delivery Order'),
2101 call => [ 'kivi.Order.save', 'save_and_supplier_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
2102 $::instance_conf->get_order_warn_no_deliverydate,
2104 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2105 @req_trans_cost_art, @req_cusordnumber,
2107 only_if => (any { $self->type eq $_ } (purchase_order_type()))
2110 t8('Save and Invoice'),
2111 call => [ 'kivi.Order.save', 'save_and_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
2112 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2113 @req_trans_cost_art, @req_cusordnumber,
2117 ($has_invoice_for_advance_payment ? t8('Save and Further Invoice for Advance Payment') : t8('Save and Invoice for Advance Payment')),
2118 call => [ 'kivi.Order.save', 'save_and_invoice_for_advance_payment', $::instance_conf->get_order_warn_duplicate_parts ],
2119 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2120 @req_trans_cost_art, @req_cusordnumber,
2122 disabled => $has_final_invoice ? t8('This order has already a final invoice.')
2124 only_if => (any { $self->type eq $_ } (sales_order_type())),
2127 t8('Save and Final Invoice'),
2128 call => [ 'kivi.Order.save', 'save_and_final_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
2129 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2130 @req_trans_cost_art, @req_cusordnumber,
2132 disabled => $has_final_invoice ? t8('This order has already a final invoice.')
2134 only_if => (any { $self->type eq $_ } (sales_order_type())) && $has_invoice_for_advance_payment,
2137 t8('Save and AP Transaction'),
2138 call => [ 'kivi.Order.save', 'save_and_ap_transaction', $::instance_conf->get_order_warn_duplicate_parts ],
2139 only_if => (any { $self->type eq $_ } (purchase_order_type()))
2142 ], # end of combobox "Workflow"
2149 t8('Save and preview PDF'),
2150 call => [ 'kivi.Order.save', 'preview_pdf', $::instance_conf->get_order_warn_duplicate_parts,
2151 $::instance_conf->get_order_warn_no_deliverydate,
2153 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2156 t8('Save and print'),
2157 call => [ 'kivi.Order.show_print_options', $::instance_conf->get_order_warn_duplicate_parts,
2158 $::instance_conf->get_order_warn_no_deliverydate,
2160 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2163 t8('Save and E-mail'),
2164 id => 'save_and_email_action',
2165 call => [ 'kivi.Order.save', 'save_and_show_email_dialog', $::instance_conf->get_order_warn_duplicate_parts,
2166 $::instance_conf->get_order_warn_no_deliverydate,
2168 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2171 t8('Download attachments of all parts'),
2172 call => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
2173 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2174 only_if => $::instance_conf->get_doc_storage,
2176 ], # end of combobox "Export"
2180 call => [ 'kivi.Order.delete_order' ],
2181 confirm => $::locale->text('Do you really want to delete this object?'),
2182 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2183 only_if => $deletion_allowed,
2190 for my $bar ($::request->layout->get('actionbar')) {
2198 call => [ 'set_history_window', $self->order->id, 'id' ],
2199 disabled => !$self->order->id ? t8('This record has not been saved yet.') : undef,
2203 call => [ 'kivi.Order.follow_up_window' ],
2204 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2205 only_if => $::auth->assert('productivity', 1),
2207 ], # end of combobox "more"
2214 my ($self, $doc_ref, $params) = @_;
2216 my $order = $self->order;
2219 my $print_form = Form->new('');
2220 $print_form->{type} = $order->type;
2221 $print_form->{formname} = $params->{formname} || $order->type;
2222 $print_form->{format} = $params->{format} || 'pdf';
2223 $print_form->{media} = $params->{media} || 'file';
2224 $print_form->{groupitems} = $params->{groupitems};
2225 $print_form->{printer_id} = $params->{printer_id};
2226 $print_form->{media} = 'file' if $print_form->{media} eq 'screen';
2228 $order->language($params->{language});
2229 $order->flatten_to_form($print_form, format_amounts => 1);
2233 if ($print_form->{format} =~ /(opendocument|oasis)/i) {
2234 $template_ext = 'odt';
2235 $template_type = 'OpenDocument';
2236 } elsif ($print_form->{format} =~ m{html}i) {
2237 $template_ext = 'html';
2238 $template_type = 'HTML';
2241 # search for the template
2242 my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
2243 name => $print_form->{formname},
2244 extension => $template_ext,
2245 email => $print_form->{media} eq 'email',
2246 language => $params->{language},
2247 printer_id => $print_form->{printer_id},
2250 if (!defined $template_file) {
2251 push @errors, $::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files);
2254 return @errors if scalar @errors;
2256 $print_form->throw_on_error(sub {
2258 $print_form->prepare_for_printing;
2260 $$doc_ref = SL::Helper::CreatePDF->create_pdf(
2261 format => $print_form->{format},
2262 template_type => $template_type,
2263 template => $template_file,
2264 variables => $print_form,
2265 variable_content_types => {
2266 longdescription => 'html',
2267 partnotes => 'html',
2269 $::form->get_variable_content_types_for_cvars,
2273 } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->error : $EVAL_ERROR;
2279 sub get_files_for_email_dialog {
2282 my %files = map { ($_ => []) } qw(versions files vc_files part_files);
2284 return %files if !$::instance_conf->get_doc_storage;
2286 if ($self->order->id) {
2287 $files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id, object_type => $self->order->type, file_type => 'document') ];
2288 $files{files} = [ SL::File->get_all( object_id => $self->order->id, object_type => $self->order->type, file_type => 'attachment') ];
2289 $files{vc_files} = [ SL::File->get_all( object_id => $self->order->{$self->cv}->id, object_type => $self->cv, file_type => 'attachment') ];
2290 $files{project_files} = [ SL::File->get_all( object_id => $self->order->globalproject_id, object_type => 'project', file_type => 'attachment') ];
2294 uniq_by { $_->{id} }
2296 +{ id => $_->part->id,
2297 partnumber => $_->part->partnumber }
2298 } @{$self->order->items_sorted};
2300 foreach my $part (@parts) {
2301 my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
2302 push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
2305 foreach my $key (keys %files) {
2306 $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
2312 sub make_periodic_invoices_config_from_yaml {
2313 my ($yaml_config) = @_;
2315 return if !$yaml_config;
2316 my $attr = SL::YAML::Load($yaml_config);
2317 return if 'HASH' ne ref $attr;
2318 return SL::DB::PeriodicInvoicesConfig->new(%$attr);
2322 sub get_periodic_invoices_status {
2323 my ($self, $config) = @_;
2325 return if $self->type ne sales_order_type();
2326 return t8('not configured') if !$config;
2328 my $active = ('HASH' eq ref $config) ? $config->{active}
2329 : ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
2330 : die "Cannot get status of periodic invoices config";
2332 return $active ? t8('active') : t8('inactive');
2336 my ($self, $action) = @_;
2338 return '' if none { lc($action)} qw(add edit);
2341 # $::locale->text("Add Sales Order");
2342 # $::locale->text("Add Purchase Order");
2343 # $::locale->text("Add Quotation");
2344 # $::locale->text("Add Request for Quotation");
2345 # $::locale->text("Edit Sales Order");
2346 # $::locale->text("Edit Purchase Order");
2347 # $::locale->text("Edit Quotation");
2348 # $::locale->text("Edit Request for Quotation");
2350 $action = ucfirst(lc($action));
2351 return $self->type eq sales_order_type() ? $::locale->text("$action Sales Order")
2352 : $self->type eq purchase_order_type() ? $::locale->text("$action Purchase Order")
2353 : $self->type eq sales_quotation_type() ? $::locale->text("$action Quotation")
2354 : $self->type eq request_quotation_type() ? $::locale->text("$action Request for Quotation")
2358 sub get_item_cvpartnumber {
2359 my ($self, $item) = @_;
2361 return if !$self->search_cvpartnumber;
2362 return if !$self->order->customervendor;
2364 if ($self->cv eq 'vendor') {
2365 my @mms = grep { $_->make eq $self->order->customervendor->id } @{$item->part->makemodels};
2366 $item->{cvpartnumber} = $mms[0]->model if scalar @mms;
2367 } elsif ($self->cv eq 'customer') {
2368 my @cps = grep { $_->customer_id eq $self->order->customervendor->id } @{$item->part->customerprices};
2369 $item->{cvpartnumber} = $cps[0]->customer_partnumber if scalar @cps;
2373 sub get_part_texts {
2374 my ($part_or_id, $language_or_id, %defaults) = @_;
2376 my $part = ref($part_or_id) ? $part_or_id : SL::DB::Part->load_cached($part_or_id);
2377 my $language_id = ref($language_or_id) ? $language_or_id->id : $language_or_id;
2379 description => $defaults{description} // $part->description,
2380 longdescription => $defaults{longdescription} // $part->notes,
2383 return $texts unless $language_id;
2385 my $translation = SL::DB::Manager::Translation->get_first(
2387 parts_id => $part->id,
2388 language_id => $language_id,
2391 $texts->{description} = $translation->translation if $translation && $translation->translation;
2392 $texts->{longdescription} = $translation->longdescription if $translation && $translation->longdescription;
2397 sub sales_order_type {
2401 sub purchase_order_type {
2405 sub sales_quotation_type {
2409 sub request_quotation_type {
2410 'request_quotation';
2414 return $_[0]->type eq sales_order_type() ? 'ordnumber'
2415 : $_[0]->type eq purchase_order_type() ? 'ordnumber'
2416 : $_[0]->type eq sales_quotation_type() ? 'quonumber'
2417 : $_[0]->type eq request_quotation_type() ? 'quonumber'
2421 sub save_and_redirect_to {
2422 my ($self, %params) = @_;
2424 my $errors = $self->save();
2426 if (scalar @{ $errors }) {
2427 $self->js->flash('error', $_) foreach @{ $errors };
2428 return $self->js->render();
2431 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
2432 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
2433 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
2434 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
2436 flash_later('info', $text);
2438 $self->redirect_to(%params, id => $self->order->id);
2442 my ($self, $addition) = @_;
2444 my $number_type = $self->order->type =~ m{order} ? 'ordnumber' : 'quonumber';
2445 my $snumbers = $number_type . '_' . $self->order->$number_type;
2447 SL::DB::History->new(
2448 trans_id => $self->order->id,
2449 employee_id => SL::DB::Manager::Employee->current->id,
2450 what_done => $self->order->type,
2451 snumbers => $snumbers,
2452 addition => $addition,
2456 sub store_doc_to_webdav_and_filemanagement {
2457 my ($self, $content, $filename, $variant) = @_;
2459 my $order = $self->order;
2462 # copy file to webdav folder
2463 if ($order->number && $::instance_conf->get_webdav_documents) {
2464 my $webdav = SL::Webdav->new(
2465 type => $order->type,
2466 number => $order->number,
2468 my $webdav_file = SL::Webdav::File->new(
2470 filename => $filename,
2473 $webdav_file->store(data => \$content);
2476 push @errors, t8('Storing the document to the WebDAV folder failed: #1', $@);
2479 if ($order->id && $::instance_conf->get_doc_storage) {
2481 SL::File->save(object_id => $order->id,
2482 object_type => $order->type,
2483 mime_type => SL::MIME->mime_type_from_ext($filename),
2484 source => 'created',
2485 file_type => 'document',
2486 file_name => $filename,
2487 file_contents => $content,
2488 print_variant => $variant);
2491 push @errors, t8('Storing the document in the storage backend failed: #1', $@);
2498 sub link_requirement_specs_linking_to_created_from_objects {
2499 my ($self, @converted_from_oe_ids) = @_;
2501 return unless @converted_from_oe_ids;
2503 my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => \@converted_from_oe_ids ]);
2504 foreach my $rs_order (@{ $rs_orders }) {
2505 SL::DB::RequirementSpecOrder->new(
2506 order_id => $self->order->id,
2507 requirement_spec_id => $rs_order->requirement_spec_id,
2508 version_id => $rs_order->version_id,
2513 sub set_project_in_linked_requirement_specs {
2516 my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => $self->order->id ]);
2517 foreach my $rs_order (@{ $rs_orders }) {
2518 next if $rs_order->requirement_spec->project_id == $self->order->globalproject_id;
2520 $rs_order->requirement_spec->update_attributes(project_id => $self->order->globalproject_id);
2532 SL::Controller::Order - controller for orders
2536 This is a new form to enter orders, completely rewritten with the use
2537 of controller and java script techniques.
2539 The aim is to provide the user a better experience and a faster workflow. Also
2540 the code should be more readable, more reliable and better to maintain.
2548 One input row, so that input happens every time at the same place.
2552 Use of pickers where possible.
2556 Possibility to enter more than one item at once.
2560 Item list in a scrollable area, so that the workflow buttons stay at
2565 Reordering item rows with drag and drop is possible. Sorting item rows is
2566 possible (by partnumber, description, qty, sellprice and discount for now).
2570 No C<update> is necessary. All entries and calculations are managed
2571 with ajax-calls and the page only reloads on C<save>.
2575 User can see changes immediately, because of the use of java script
2586 =item * C<SL/Controller/Order.pm>
2590 =item * C<template/webpages/order/form.html>
2594 =item * C<template/webpages/order/tabs/basic_data.html>
2596 Main tab for basic_data.
2598 This is the only tab here for now. "linked records" and "webdav" tabs are
2599 reused from generic code.
2603 =item * C<template/webpages/order/tabs/_business_info_row.html>
2605 For displaying information on business type
2607 =item * C<template/webpages/order/tabs/_item_input.html>
2609 The input line for items
2611 =item * C<template/webpages/order/tabs/_row.html>
2613 One row for already entered items
2615 =item * C<template/webpages/order/tabs/_tax_row.html>
2617 Displaying tax information
2619 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
2621 Dialog for selecting price and discount sources
2625 =item * C<js/kivi.Order.js>
2627 java script functions
2637 =item * price sources: little symbols showing better price / better discount
2639 =item * select units in input row?
2641 =item * check for direct delivery (workflow sales order -> purchase order)
2643 =item * access rights
2645 =item * display weights
2649 =item * optional client/user behaviour
2651 (transactions has to be set - department has to be set -
2652 force project if enabled in client config)
2656 =head1 KNOWN BUGS AND CAVEATS
2662 Customer discount is not displayed as a valid discount in price source popup
2663 (this might be a bug in price sources)
2665 (I cannot reproduce this (Bernd))
2669 No indication that <shift>-up/down expands/collapses second row.
2673 Inline creation of parts is not currently supported
2677 Table header is not sticky in the scrolling area.
2681 Sorting does not include C<position>, neither does reordering.
2683 This behavior was implemented intentionally. But we can discuss, which behavior
2684 should be implemented.
2688 =head1 To discuss / Nice to have
2694 How to expand/collapse second row. Now it can be done clicking the icon or
2699 Possibility to select PriceSources in input row?
2703 This controller uses a (changed) copy of the template for the PriceSource
2704 dialog. Maybe there could be used one code source.
2708 Rounding-differences between this controller (PriceTaxCalculator) and the old
2709 form. This is not only a problem here, but also in all parts using the PTC.
2710 There exists a ticket and a patch. This patch should be testet.
2714 An indicator, if the actual inputs are saved (like in an
2715 editor or on text processing application).
2719 A warning when leaving the page without saveing unchanged inputs.
2726 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>