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::DisplayPreferences;
37 use SL::Helper::UserPreferences::PositionsScrollbar;
38 use SL::Helper::UserPreferences::UpdatePositions;
40 use SL::Controller::Helper::GetModels;
42 use List::Util qw(first sum0);
43 use List::UtilsBy qw(sort_by uniq_by);
44 use List::MoreUtils qw(any none pairwise first_index);
45 use English qw(-no_match_vars);
50 use Rose::Object::MakeMethods::Generic
52 scalar => [ qw(item_ids_to_delete is_custom_shipto_to_delete) ],
53 'scalar --get_set_init' => [ qw(order valid_types type cv p all_price_factors search_cvpartnumber show_update_button part_picker_classification_ids) ],
58 __PACKAGE__->run_before('check_auth');
60 __PACKAGE__->run_before('check_auth_for_edit',
61 except => [ qw(edit show_customer_vendor_details_dialog price_popup load_second_rows) ]);
63 __PACKAGE__->run_before('recalc',
64 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
67 __PACKAGE__->run_before('get_unalterable_data',
68 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
79 $self->order->transdate(DateTime->now_local());
80 my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval :
81 $self->type eq sales_order_type() ? $::instance_conf->get_delivery_date_interval : 1;
83 if ( ($self->type eq sales_order_type() && $::instance_conf->get_deliverydate_on)
84 || ($self->type eq sales_quotation_type() && $::instance_conf->get_reqdate_on)
85 && (!$self->order->reqdate)) {
86 $self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days));
93 title => $self->get_title_for('add'),
94 %{$self->{template_args}}
98 # edit an existing order
106 # this is to edit an order from an unsaved order object
108 # set item ids to new fake id, to identify them as new items
109 foreach my $item (@{$self->order->items_sorted}) {
110 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
112 # trigger rendering values for second row as hidden, because they
113 # are loaded only on demand. So we need to keep the values from
115 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
122 title => $self->get_title_for('edit'),
123 %{$self->{template_args}}
127 # edit a collective order (consisting of one or more existing orders)
128 sub action_edit_collective {
132 my @multi_ids = map {
133 $_ =~ m{^multi_id_(\d+)$} && $::form->{'multi_id_' . $1} && $::form->{'trans_id_' . $1} && $::form->{'trans_id_' . $1}
134 } grep { $_ =~ m{^multi_id_\d+$} } keys %$::form;
136 # fall back to add if no ids are given
137 if (scalar @multi_ids == 0) {
142 # fall back to save as new if only one id is given
143 if (scalar @multi_ids == 1) {
144 $self->order(SL::DB::Order->new(id => $multi_ids[0])->load);
145 $self->action_save_as_new();
149 # make new order from given orders
150 my @multi_orders = map { SL::DB::Order->new(id => $_)->load } @multi_ids;
151 $self->{converted_from_oe_id} = join ' ', map { $_->id } @multi_orders;
152 $self->order(SL::DB::Order->new_from_multi(\@multi_orders, sort_sources_by => 'transdate'));
154 $self->action_edit();
161 my $errors = $self->delete();
163 if (scalar @{ $errors }) {
164 $self->js->flash('error', $_) foreach @{ $errors };
165 return $self->js->render();
168 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been deleted')
169 : $self->type eq purchase_order_type() ? $::locale->text('The order has been deleted')
170 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been deleted')
171 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been deleted')
173 flash_later('info', $text);
175 my @redirect_params = (
180 $self->redirect_to(@redirect_params);
187 my $errors = $self->save();
189 if (scalar @{ $errors }) {
190 $self->js->flash('error', $_) foreach @{ $errors };
191 return $self->js->render();
194 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
195 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
196 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
197 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
199 flash_later('info', $text);
202 if ($::form->{back_to_caller}) {
203 @redirect_params = $::form->{callback} ? ($::form->{callback})
204 : (controller => 'LoginScreen', action => 'user_login');
210 id => $self->order->id,
211 callback => $::form->{callback},
215 $self->redirect_to(@redirect_params);
218 # save the order as new document an open it for edit
219 sub action_save_as_new {
222 my $order = $self->order;
225 $self->js->flash('error', t8('This object has not been saved yet.'));
226 return $self->js->render();
229 # load order from db to check if values changed
230 my $saved_order = SL::DB::Order->new(id => $order->id)->load;
233 # Lets assign a new number if the user hasn't changed the previous one.
234 # If it has been changed manually then use it as-is.
235 $new_attrs{number} = (trim($order->number) eq $saved_order->number)
237 : trim($order->number);
239 # Clear transdate unless changed
240 $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
241 ? DateTime->today_local
244 # Set new reqdate unless changed if it is enabled in client config
245 if ($order->reqdate == $saved_order->reqdate) {
246 my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval :
247 $self->type eq sales_order_type() ? $::instance_conf->get_delivery_date_interval : 1;
249 if ( ($self->type eq sales_order_type() && !$::instance_conf->get_deliverydate_on)
250 || ($self->type eq sales_quotation_type() && !$::instance_conf->get_reqdate_on)) {
251 $new_attrs{reqdate} = '';
253 $new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
256 $new_attrs{reqdate} = $order->reqdate;
260 $new_attrs{employee} = SL::DB::Manager::Employee->current;
262 # Warn on obsolete items
263 my @obsolete_positions = map { $_->position } grep { $_->part->obsolete } @{ $order->items_sorted };
264 flash_later('warning', t8('This record containts obsolete items at position #1', join ', ', @obsolete_positions)) if @obsolete_positions;
266 # Create new record from current one
267 $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
269 # no linked records on save as new
270 delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
273 $self->action_save();
278 # This is called if "print" is pressed in the print dialog.
279 # If PDF creation was requested and succeeded, the pdf is offered for download
280 # via send_file (which uses ajax in this case).
284 my $errors = $self->save();
286 if (scalar @{ $errors }) {
287 $self->js->flash('error', $_) foreach @{ $errors };
288 return $self->js->render();
291 $self->js_reset_order_and_item_ids_after_save;
293 my $format = $::form->{print_options}->{format};
294 my $media = $::form->{print_options}->{media};
295 my $formname = $::form->{print_options}->{formname};
296 my $copies = $::form->{print_options}->{copies};
297 my $groupitems = $::form->{print_options}->{groupitems};
298 my $printer_id = $::form->{print_options}->{printer_id};
300 # only PDF, OpenDocument & HTML for now
301 if (none { $format eq $_ } qw(pdf opendocument opendocument_pdf html)) {
302 return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
305 # only screen or printer by now
306 if (none { $media eq $_ } qw(screen printer)) {
307 return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
310 # create a form for generate_attachment_filename
311 my $form = Form->new;
312 $form->{$self->nr_key()} = $self->order->number;
313 $form->{type} = $self->type;
314 $form->{format} = $format;
315 $form->{formname} = $formname;
316 $form->{language} = '_' . $self->order->language->template_code if $self->order->language;
317 my $doc_filename = $form->generate_attachment_filename();
320 my @errors = $self->generate_doc(\$doc, { media => $media,
322 formname => $formname,
323 language => $self->order->language,
324 printer_id => $printer_id,
325 groupitems => $groupitems });
326 if (scalar @errors) {
327 return $self->js->flash('error', t8('Generating the document failed: #1', $errors[0]))->render;
330 if ($media eq 'screen') {
332 $self->js->flash('info', t8('The document has been created.'));
335 type => SL::MIME->mime_type_from_ext($doc_filename),
336 name => $doc_filename,
340 } elsif ($media eq 'printer') {
342 my $printer_id = $::form->{print_options}->{printer_id};
343 SL::DB::Printer->new(id => $printer_id)->load->print_document(
348 $self->js->flash('info', t8('The document has been printed.'));
351 my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $doc_filename, $formname);
352 if (scalar @warnings) {
353 $self->js->flash('warning', $_) for @warnings;
356 $self->save_history('PRINTED');
359 ->run('kivi.ActionBar.setEnabled', '#save_and_email_action')
362 sub action_preview_pdf {
365 my $errors = $self->save();
366 if (scalar @{ $errors }) {
367 $self->js->flash('error', $_) foreach @{ $errors };
368 return $self->js->render();
371 $self->js_reset_order_and_item_ids_after_save;
374 my $media = 'screen';
375 my $formname = $self->type;
378 # create a form for generate_attachment_filename
379 my $form = Form->new;
380 $form->{$self->nr_key()} = $self->order->number;
381 $form->{type} = $self->type;
382 $form->{format} = $format;
383 $form->{formname} = $formname;
384 $form->{language} = '_' . $self->order->language->template_code if $self->order->language;
385 my $pdf_filename = $form->generate_attachment_filename();
388 my @errors = $self->generate_doc(\$pdf, { media => $media,
390 formname => $formname,
391 language => $self->order->language,
393 if (scalar @errors) {
394 return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
396 $self->save_history('PREVIEWED');
397 $self->js->flash('info', t8('The PDF has been previewed'));
401 type => SL::MIME->mime_type_from_ext($pdf_filename),
402 name => $pdf_filename,
407 # open the email dialog
408 sub action_save_and_show_email_dialog {
411 my $errors = $self->save();
413 if (scalar @{ $errors }) {
414 $self->js->flash('error', $_) foreach @{ $errors };
415 return $self->js->render();
418 my $cv_method = $self->cv;
420 if (!$self->order->$cv_method) {
421 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'))
426 $email_form->{to} = $self->order->contact->cp_email if $self->order->contact;
427 $email_form->{to} ||= $self->order->$cv_method->email;
428 $email_form->{cc} = $self->order->$cv_method->cc;
429 $email_form->{bcc} = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
430 # Todo: get addresses from shipto, if any
432 my $form = Form->new;
433 $form->{$self->nr_key()} = $self->order->number;
434 $form->{cusordnumber} = $self->order->cusordnumber;
435 $form->{formname} = $self->type;
436 $form->{type} = $self->type;
437 $form->{language} = '_' . $self->order->language->template_code if $self->order->language;
438 $form->{language_id} = $self->order->language->id if $self->order->language;
439 $form->{format} = 'pdf';
440 $form->{cp_id} = $self->order->contact->cp_id if $self->order->contact;
442 $email_form->{subject} = $form->generate_email_subject();
443 $email_form->{attachment_filename} = $form->generate_attachment_filename();
444 $email_form->{message} = $form->generate_email_body();
445 $email_form->{js_send_function} = 'kivi.Order.send_email()';
447 my %files = $self->get_files_for_email_dialog();
449 my @employees_with_email = grep {
450 my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
451 $user && !!trim($user->get_config_value('email'));
452 } @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
455 my $all_partner_email_addresses = $self->order->customervendor->get_all_email_addresses();
457 my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
458 email_form => $email_form,
459 show_bcc => $::auth->assert('email_bcc', 'may fail'),
461 is_customer => $self->cv eq 'customer',
462 ALL_EMPLOYEES => \@employees_with_email,
463 ALL_PARTNER_EMAIL_ADDRESSES => $all_partner_email_addresses,
467 ->run('kivi.Order.show_email_dialog', $dialog_html)
474 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
475 sub action_send_email {
478 my $errors = $self->save();
480 if (scalar @{ $errors }) {
481 $self->js->run('kivi.Order.close_email_dialog');
482 $self->js->flash('error', $_) foreach @{ $errors };
483 return $self->js->render();
486 $self->js_reset_order_and_item_ids_after_save;
488 my $email_form = delete $::form->{email_form};
490 if ($email_form->{additional_to}) {
491 $email_form->{to} = join ', ', grep { $_ } $email_form->{to}, @{$email_form->{additional_to}};
492 delete $email_form->{additional_to};
495 my %field_names = (to => 'email');
497 $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
499 # for Form::cleanup which may be called in Form::send_email
500 $::form->{cwd} = getcwd();
501 $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
503 $::form->{$_} = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
504 $::form->{media} = 'email';
506 $::form->{attachment_policy} //= '';
508 # Is an old file version available?
510 if ($::form->{attachment_policy} eq 'old_file') {
511 $attfile = SL::File->get_all(object_id => $self->order->id,
512 object_type => $self->type,
513 file_type => 'document',
514 print_variant => $::form->{formname});
517 if ($::form->{attachment_policy} ne 'no_file' && !($::form->{attachment_policy} eq 'old_file' && $attfile)) {
519 my @errors = $self->generate_doc(\$doc, {media => $::form->{media},
520 format => $::form->{print_options}->{format},
521 formname => $::form->{print_options}->{formname},
522 language => $self->order->language,
523 printer_id => $::form->{print_options}->{printer_id},
524 groupitems => $::form->{print_options}->{groupitems}});
525 if (scalar @errors) {
526 return $self->js->flash('error', t8('Generating the document failed: #1', $errors[0]))->render($self);
529 my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $::form->{attachment_filename}, $::form->{formname});
530 if (scalar @warnings) {
531 flash_later('warning', $_) for @warnings;
534 my $sfile = SL::SessionFile::Random->new(mode => "w");
535 $sfile->fh->print($doc);
538 $::form->{tmpfile} = $sfile->file_name;
539 $::form->{tmpdir} = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
542 $::form->{id} = $self->order->id; # this is used in SL::Mailer to create a linked record to the mail
543 $::form->send_email(\%::myconfig, $::form->{print_options}->{format});
545 # internal notes unless no email journal
546 unless ($::instance_conf->get_email_journal) {
547 my $intnotes = $self->order->intnotes;
548 $intnotes .= "\n\n" if $self->order->intnotes;
549 $intnotes .= t8('[email]') . "\n";
550 $intnotes .= t8('Date') . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
551 $intnotes .= t8('To (email)') . ": " . $::form->{email} . "\n";
552 $intnotes .= t8('Cc') . ": " . $::form->{cc} . "\n" if $::form->{cc};
553 $intnotes .= t8('Bcc') . ": " . $::form->{bcc} . "\n" if $::form->{bcc};
554 $intnotes .= t8('Subject') . ": " . $::form->{subject} . "\n\n";
555 $intnotes .= t8('Message') . ": " . SL::HTML::Util->strip($::form->{message});
557 $self->order->update_attributes(intnotes => $intnotes);
560 $self->save_history('MAILED');
562 flash_later('info', t8('The email has been sent.'));
564 my @redirect_params = (
567 id => $self->order->id,
570 $self->redirect_to(@redirect_params);
573 # open the periodic invoices config dialog
575 # If there are values in the form (i.e. dialog was opened before),
576 # then use this values. Create new ones, else.
577 sub action_show_periodic_invoices_config_dialog {
580 my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
581 $config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
582 $config ||= SL::DB::PeriodicInvoicesConfig->new(periodicity => 'm',
583 order_value_periodicity => 'p', # = same as periodicity
584 start_date_as_date => $::form->{transdate_as_date} || $::form->current_date,
585 extend_automatically_by => 12,
587 email_subject => GenericTranslations->get(
588 language_id => $::form->{language_id},
589 translation_type =>"preset_text_periodic_invoices_email_subject"),
590 email_body => GenericTranslations->get(
591 language_id => $::form->{language_id},
592 translation_type => "salutation_general")
593 . GenericTranslations->get(
594 language_id => $::form->{language_id},
595 translation_type => "salutation_punctuation_mark") . "\n\n"
596 . GenericTranslations->get(
597 language_id => $::form->{language_id},
598 translation_type =>"preset_text_periodic_invoices_email_body"),
600 # for older configs, replace email preset text if not yet set.
601 $config->email_subject(GenericTranslations->get(
602 language_id => $::form->{language_id},
603 translation_type =>"preset_text_periodic_invoices_email_subject")
604 ) unless $config->email_subject;
606 $config->email_body(GenericTranslations->get(
607 language_id => $::form->{language_id},
608 translation_type => "salutation_general")
609 . GenericTranslations->get(
610 language_id => $::form->{language_id},
611 translation_type => "salutation_punctuation_mark") . "\n\n"
612 . GenericTranslations->get(
613 language_id => $::form->{language_id},
614 translation_type =>"preset_text_periodic_invoices_email_body")
615 ) unless $config->email_body;
617 $config->periodicity('m') if none { $_ eq $config->periodicity } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
618 $config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
620 $::form->get_lists(printers => "ALL_PRINTERS",
621 charts => { key => 'ALL_CHARTS',
622 transdate => 'current_date' });
624 $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
626 if ($::form->{customer_id}) {
627 $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
628 my $customer_object = SL::DB::Manager::Customer->find_by(id => $::form->{customer_id});
629 $::form->{postal_invoice} = $customer_object->postal_invoice;
630 $::form->{email_recipient_invoice_address} = $::form->{postal_invoice} ? '' : $customer_object->invoice_mail;
631 $config->send_email(0) if $::form->{postal_invoice};
634 $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
636 popup_js_close_function => 'kivi.Order.close_periodic_invoices_config_dialog()',
637 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
642 # assign the values of the periodic invoices config dialog
643 # as yaml in the hidden tag and set the status.
644 sub action_assign_periodic_invoices_config {
647 $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
649 my $config = { active => $::form->{active} ? 1 : 0,
650 terminated => $::form->{terminated} ? 1 : 0,
651 direct_debit => $::form->{direct_debit} ? 1 : 0,
652 periodicity => (any { $_ eq $::form->{periodicity} } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES) ? $::form->{periodicity} : 'm',
653 order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
654 start_date_as_date => $::form->{start_date_as_date},
655 end_date_as_date => $::form->{end_date_as_date},
656 first_billing_date_as_date => $::form->{first_billing_date_as_date},
657 print => $::form->{print} ? 1 : 0,
658 printer_id => $::form->{print} ? $::form->{printer_id} * 1 : undef,
659 copies => $::form->{copies} * 1 ? $::form->{copies} : 1,
660 extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
661 ar_chart_id => $::form->{ar_chart_id} * 1,
662 send_email => $::form->{send_email} ? 1 : 0,
663 email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
664 email_recipient_address => $::form->{email_recipient_address},
665 email_sender => $::form->{email_sender},
666 email_subject => $::form->{email_subject},
667 email_body => $::form->{email_body},
670 my $periodic_invoices_config = SL::YAML::Dump($config);
672 my $status = $self->get_periodic_invoices_status($config);
675 ->remove('#order_periodic_invoices_config')
676 ->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
677 ->run('kivi.Order.close_periodic_invoices_config_dialog')
678 ->html('#periodic_invoices_status', $status)
679 ->flash('info', t8('The periodic invoices config has been assigned.'))
683 sub action_get_has_active_periodic_invoices {
686 my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
687 $config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
689 my $has_active_periodic_invoices =
690 $self->type eq sales_order_type()
693 && (!$config->end_date || ($config->end_date > DateTime->today_local))
694 && $config->get_previous_billed_period_start_date;
696 $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
699 # save the order and redirect to the frontend subroutine for a new
701 sub action_save_and_delivery_order {
704 $self->save_and_redirect_to(
705 controller => 'oe.pl',
706 action => 'oe_delivery_order_from_order',
710 sub action_save_and_supplier_delivery_order {
713 $self->save_and_redirect_to(
714 controller => 'controller.pl',
715 action => 'DeliveryOrder/add_from_order',
716 type => 'supplier_delivery_order',
720 # save the order and redirect to the frontend subroutine for a new
722 sub action_save_and_invoice {
725 $self->save_and_redirect_to(
726 controller => 'oe.pl',
727 action => 'oe_invoice_from_order',
731 sub action_save_and_invoice_for_advance_payment {
734 $self->save_and_redirect_to(
735 controller => 'oe.pl',
736 action => 'oe_invoice_from_order',
737 new_invoice_type => 'invoice_for_advance_payment',
741 sub action_save_and_final_invoice {
744 $self->save_and_redirect_to(
745 controller => 'oe.pl',
746 action => 'oe_invoice_from_order',
747 new_invoice_type => 'final_invoice',
751 # workflow from sales order to sales quotation
752 sub action_sales_quotation {
753 $_[0]->workflow_sales_or_request_for_quotation();
756 # workflow from sales order to sales quotation
757 sub action_request_for_quotation {
758 $_[0]->workflow_sales_or_request_for_quotation();
761 # workflow from sales quotation to sales order
762 sub action_sales_order {
763 $_[0]->workflow_sales_or_purchase_order();
766 # workflow from rfq to purchase order
767 sub action_purchase_order {
768 $_[0]->workflow_sales_or_purchase_order();
771 # workflow from purchase order to ap transaction
772 sub action_save_and_ap_transaction {
775 $self->save_and_redirect_to(
776 controller => 'ap.pl',
777 action => 'add_from_purchase_order',
781 # set form elements in respect to a changed customer or vendor
783 # This action is called on an change of the customer/vendor picker.
784 sub action_customer_vendor_changed {
787 setup_order_from_cv($self->order);
790 my $cv_method = $self->cv;
792 if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
793 $self->js->show('#cp_row');
795 $self->js->hide('#cp_row');
798 if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
799 $self->js->show('#shipto_selection');
801 $self->js->hide('#shipto_selection');
804 if ($cv_method eq 'customer') {
805 my $show_hide = scalar @{ $self->order->customer->additional_billing_addresses } > 0 ? 'show' : 'hide';
806 $self->js->$show_hide('#billing_address_row');
809 $self->js->val( '#order_salesman_id', $self->order->salesman_id) if $self->order->is_sales;
812 ->replaceWith('#order_cp_id', $self->build_contact_select)
813 ->replaceWith('#order_shipto_id', $self->build_shipto_select)
814 ->replaceWith('#shipto_inputs ', $self->build_shipto_inputs)
815 ->replaceWith('#order_billing_address_id', $self->build_billing_address_select)
816 ->replaceWith('#business_info_row', $self->build_business_info_row)
817 ->val( '#order_taxzone_id', $self->order->taxzone_id)
818 ->val( '#order_taxincluded', $self->order->taxincluded)
819 ->val( '#order_currency_id', $self->order->currency_id)
820 ->val( '#order_payment_id', $self->order->payment_id)
821 ->val( '#order_delivery_term_id', $self->order->delivery_term_id)
822 ->val( '#order_intnotes', $self->order->intnotes)
823 ->val( '#order_language_id', $self->order->$cv_method->language_id)
824 ->focus( '#order_' . $self->cv . '_id')
825 ->run('kivi.Order.update_exchangerate');
827 $self->js_redisplay_amounts_and_taxes;
828 $self->js_redisplay_cvpartnumbers;
832 # open the dialog for customer/vendor details
833 sub action_show_customer_vendor_details_dialog {
836 my $is_customer = 'customer' eq $::form->{vc};
839 $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
841 $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
844 my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
845 $details{discount_as_percent} = $cv->discount_as_percent;
846 $details{creditlimt} = $cv->creditlimit_as_number;
847 $details{business} = $cv->business->description if $cv->business;
848 $details{language} = $cv->language_obj->description if $cv->language_obj;
849 $details{delivery_terms} = $cv->delivery_term->description if $cv->delivery_term;
850 $details{payment_terms} = $cv->payment->description if $cv->payment;
851 $details{pricegroup} = $cv->pricegroup->pricegroup if $is_customer && $cv->pricegroup;
854 foreach my $entry (@{ $cv->additional_billing_addresses }) {
855 push @{ $details{ADDITIONAL_BILLING_ADDRESSES} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
858 foreach my $entry (@{ $cv->shipto }) {
859 push @{ $details{SHIPTO} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
861 foreach my $entry (@{ $cv->contacts }) {
862 push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
865 $_[0]->render('common/show_vc_details', { layout => 0 },
866 is_customer => $is_customer,
871 # called if a unit in an existing item row is changed
872 sub action_unit_changed {
875 my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
876 my $item = $self->order->items_sorted->[$idx];
878 my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
879 $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
884 ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
885 $self->js_redisplay_line_values;
886 $self->js_redisplay_amounts_and_taxes;
890 # update item input row when a part ist picked
891 sub action_update_item_input_row {
894 delete $::form->{add_item}->{$_} for qw(create_part_type sellprice_as_number discount_as_percent);
896 my $form_attr = $::form->{add_item};
898 return unless $form_attr->{parts_id};
900 my $record = $self->order;
901 my $item = SL::DB::OrderItem->new(%$form_attr);
902 $item->unit($item->part->unit);
904 my ($price_src, $discount_src) = get_best_price_and_discount_source($record, $item, 0);
907 ->val ('#add_item_unit', $item->unit)
908 ->val ('#add_item_description', $item->part->description)
909 ->val ('#add_item_sellprice_as_number', '')
910 ->attr ('#add_item_sellprice_as_number', 'placeholder', $price_src->price_as_number)
911 ->attr ('#add_item_sellprice_as_number', 'title', $price_src->source_description)
912 ->val ('#add_item_discount_as_percent', '')
913 ->attr ('#add_item_discount_as_percent', 'placeholder', $discount_src->discount_as_percent)
914 ->attr ('#add_item_discount_as_percent', 'title', $discount_src->source_description)
918 # add an item row for a new item entered in the input row
919 sub action_add_item {
922 delete $::form->{add_item}->{create_part_type};
924 my $form_attr = $::form->{add_item};
926 return unless $form_attr->{parts_id};
928 my $item = new_item($self->order, $form_attr);
930 $self->order->add_items($item);
934 $self->get_item_cvpartnumber($item);
936 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
937 my $row_as_html = $self->p->render('order/tabs/_row',
943 if ($::form->{insert_before_item_id}) {
945 ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
948 ->append('#row_table_id', $row_as_html);
951 if ( $item->part->is_assortment ) {
952 $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
953 foreach my $assortment_item ( @{$item->part->assortment_items} ) {
954 my $attr = { parts_id => $assortment_item->parts_id,
955 qty => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
956 unit => $assortment_item->unit,
957 description => $assortment_item->part->description,
959 my $item = new_item($self->order, $attr);
961 # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
962 $item->discount(1) unless $assortment_item->charge;
964 $self->order->add_items( $item );
966 $self->get_item_cvpartnumber($item);
967 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
968 my $row_as_html = $self->p->render('order/tabs/_row',
973 if ($::form->{insert_before_item_id}) {
975 ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
978 ->append('#row_table_id', $row_as_html);
984 ->val('.add_item_input', '')
985 ->attr('.add_item_input', 'placeholder', '')
986 ->attr('.add_item_input', 'title', '')
987 ->run('kivi.Order.init_row_handlers')
988 ->run('kivi.Order.renumber_positions')
989 ->focus('#add_item_parts_id_name');
991 $self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};
993 $self->js_redisplay_amounts_and_taxes;
997 # add item rows for multiple items at once
998 sub action_add_multi_items {
1001 my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_items} };
1002 return $self->js->render() unless scalar @form_attr;
1005 foreach my $attr (@form_attr) {
1006 my $item = new_item($self->order, $attr);
1008 if ( $item->part->is_assortment ) {
1009 foreach my $assortment_item ( @{$item->part->assortment_items} ) {
1010 my $attr = { parts_id => $assortment_item->parts_id,
1011 qty => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
1012 unit => $assortment_item->unit,
1013 description => $assortment_item->part->description,
1015 my $item = new_item($self->order, $attr);
1017 # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
1018 $item->discount(1) unless $assortment_item->charge;
1023 $self->order->add_items(@items);
1027 foreach my $item (@items) {
1028 $self->get_item_cvpartnumber($item);
1029 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1030 my $row_as_html = $self->p->render('order/tabs/_row',
1036 if ($::form->{insert_before_item_id}) {
1038 ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
1041 ->append('#row_table_id', $row_as_html);
1046 ->run('kivi.Part.close_picker_dialogs')
1047 ->run('kivi.Order.init_row_handlers')
1048 ->run('kivi.Order.renumber_positions')
1049 ->focus('#add_item_parts_id_name');
1051 $self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};
1053 $self->js_redisplay_amounts_and_taxes;
1054 $self->js->render();
1057 # recalculate all linetotals, amounts and taxes and redisplay them
1058 sub action_recalc_amounts_and_taxes {
1063 $self->js_redisplay_line_values;
1064 $self->js_redisplay_amounts_and_taxes;
1065 $self->js->render();
1068 sub action_update_exchangerate {
1072 is_standard => $self->order->currency_id == $::instance_conf->get_currency_id,
1073 currency_name => $self->order->currency->name,
1074 exchangerate => $self->order->daily_exchangerate_as_null_number,
1077 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
1080 # redisplay item rows if they are sorted by an attribute
1081 sub action_reorder_items {
1085 partnumber => sub { $_[0]->part->partnumber },
1086 description => sub { $_[0]->description },
1087 qty => sub { $_[0]->qty },
1088 sellprice => sub { $_[0]->sellprice },
1089 discount => sub { $_[0]->discount },
1090 cvpartnumber => sub { $_[0]->{cvpartnumber} },
1093 $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
1095 my $method = $sort_keys{$::form->{order_by}};
1096 my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
1097 if ($::form->{sort_dir}) {
1098 if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
1099 @to_sort = sort { $a->{order_by} <=> $b->{order_by} } @to_sort;
1101 @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
1104 if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
1105 @to_sort = sort { $b->{order_by} <=> $a->{order_by} } @to_sort;
1107 @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
1111 ->run('kivi.Order.redisplay_items', \@to_sort)
1115 # show the popup to choose a price/discount source
1116 sub action_price_popup {
1119 my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
1120 my $item = $self->order->items_sorted->[$idx];
1122 $self->render_price_dialog($item);
1125 # save the order in a session variable and redirect to the part controller
1126 sub action_create_part {
1129 my $previousform = $::auth->save_form_in_session(non_scalars => 1);
1131 my $callback = $self->url_for(
1132 action => 'return_from_create_part',
1133 type => $self->type, # type is needed for check_auth on return
1134 previousform => $previousform,
1137 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.'));
1139 my @redirect_params = (
1140 controller => 'Part',
1142 part_type => $::form->{add_item}->{create_part_type},
1143 callback => $callback,
1147 $self->redirect_to(@redirect_params);
1150 sub action_return_from_create_part {
1153 $self->{created_part} = SL::DB::Part->new(id => delete $::form->{new_parts_id})->load if $::form->{new_parts_id};
1155 $::auth->restore_form_from_session(delete $::form->{previousform});
1157 # set item ids to new fake id, to identify them as new items
1158 foreach my $item (@{$self->order->items_sorted}) {
1159 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1163 $self->get_unalterable_data();
1164 $self->pre_render();
1166 # trigger rendering values for second row/longdescription as hidden,
1167 # because they are loaded only on demand. So we need to keep the values
1169 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1170 $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1174 title => $self->get_title_for('edit'),
1175 %{$self->{template_args}}
1180 # load the second row for one or more items
1182 # This action gets the html code for all items second rows by rendering a template for
1183 # the second row and sets the html code via client js.
1184 sub action_load_second_rows {
1187 $self->recalc() if $self->order->is_sales; # for margin calculation
1189 foreach my $item_id (@{ $::form->{item_ids} }) {
1190 my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
1191 my $item = $self->order->items_sorted->[$idx];
1193 $self->js_load_second_row($item, $item_id, 0);
1196 $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
1198 $self->js->render();
1201 # update description, notes and sellprice from master data
1202 sub action_update_row_from_master_data {
1205 foreach my $item_id (@{ $::form->{item_ids} }) {
1206 my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
1207 my $item = $self->order->items_sorted->[$idx];
1208 my $texts = get_part_texts($item->part, $self->order->language_id);
1210 $item->description($texts->{description});
1211 $item->longdescription($texts->{longdescription});
1213 my ($price_src, $discount_src) = get_best_price_and_discount_source($self->order, $item, 1);
1215 $item->sellprice($price_src->price);
1216 $item->active_price_source($price_src);
1217 $item->discount($discount_src->discount);
1218 $item->active_discount_source($discount_src);
1220 my $price_editable = $self->order->is_sales ? $::auth->assert('sales_edit_prices', 1) : $::auth->assert('purchase_edit_prices', 1);
1223 ->run('kivi.Order.set_price_and_source_text', $item_id, $price_src ->source, $price_src ->source_description, $item->sellprice_as_number, $price_editable)
1224 ->run('kivi.Order.set_discount_and_source_text', $item_id, $discount_src->source, $discount_src->source_description, $item->discount_as_percent, $price_editable)
1225 ->html('.row_entry:has(#item_' . $item_id . ') [name = "partnumber"] a', $item->part->partnumber)
1226 ->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].description"]', $item->description)
1227 ->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].longdescription"]', $item->longdescription);
1229 if ($self->search_cvpartnumber) {
1230 $self->get_item_cvpartnumber($item);
1231 $self->js->html('.row_entry:has(#item_' . $item_id . ') [name = "cvpartnumber"]', $item->{cvpartnumber});
1236 $self->js_redisplay_line_values;
1237 $self->js_redisplay_amounts_and_taxes;
1239 $self->js->render();
1242 sub js_load_second_row {
1243 my ($self, $item, $item_id, $do_parse) = @_;
1246 # Parse values from form (they are formated while rendering (template)).
1247 # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1248 # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
1249 foreach my $var (@{ $item->cvars_by_config }) {
1250 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1252 $item->parse_custom_variable_values;
1255 my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);
1258 ->html('#second_row_' . $item_id, $row_as_html)
1259 ->data('#second_row_' . $item_id, 'loaded', 1);
1262 sub js_redisplay_line_values {
1265 my $is_sales = $self->order->is_sales;
1267 # sales orders with margins
1272 $::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
1273 $::form->format_amount(\%::myconfig, $_->{marge_total}, 2, 0),
1274 $::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
1275 ]} @{ $self->order->items_sorted };
1279 $::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
1280 ]} @{ $self->order->items_sorted };
1284 ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
1287 sub js_redisplay_amounts_and_taxes {
1290 if (scalar @{ $self->{taxes} }) {
1291 $self->js->show('#taxincluded_row_id');
1293 $self->js->hide('#taxincluded_row_id');
1296 if ($self->order->taxincluded) {
1297 $self->js->hide('#subtotal_row_id');
1299 $self->js->show('#subtotal_row_id');
1302 if ($self->order->is_sales) {
1303 my $is_neg = $self->order->marge_total < 0;
1305 ->html('#marge_total_id', $::form->format_amount(\%::myconfig, $self->order->marge_total, 2))
1306 ->html('#marge_percent_id', $::form->format_amount(\%::myconfig, $self->order->marge_percent, 2))
1307 ->action_if( $is_neg, 'addClass', '#marge_total_id', 'plus0')
1308 ->action_if( $is_neg, 'addClass', '#marge_percent_id', 'plus0')
1309 ->action_if( $is_neg, 'addClass', '#marge_percent_sign_id', 'plus0')
1310 ->action_if(!$is_neg, 'removeClass', '#marge_total_id', 'plus0')
1311 ->action_if(!$is_neg, 'removeClass', '#marge_percent_id', 'plus0')
1312 ->action_if(!$is_neg, 'removeClass', '#marge_percent_sign_id', 'plus0');
1316 ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
1317 ->html('#amount_id', $::form->format_amount(\%::myconfig, $self->order->amount, -2))
1318 ->remove('.tax_row')
1319 ->insertBefore($self->build_tax_rows, '#amount_row_id');
1322 sub js_redisplay_cvpartnumbers {
1325 $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
1327 my @data = map {[$_->{cvpartnumber}]} @{ $self->order->items_sorted };
1330 ->run('kivi.Order.redisplay_cvpartnumbers', \@data);
1333 sub js_reset_order_and_item_ids_after_save {
1337 ->val('#id', $self->order->id)
1338 ->val('#converted_from_oe_id', '')
1339 ->val('#order_' . $self->nr_key(), $self->order->number);
1342 foreach my $form_item_id (@{ $::form->{orderitem_ids} }) {
1343 next if !$self->order->items_sorted->[$idx]->id;
1344 next if $form_item_id !~ m{^new};
1346 ->val ('[name="orderitem_ids[+]"][value="' . $form_item_id . '"]', $self->order->items_sorted->[$idx]->id)
1347 ->val ('#item_' . $form_item_id, $self->order->items_sorted->[$idx]->id)
1348 ->attr('#item_' . $form_item_id, "id", 'item_' . $self->order->items_sorted->[$idx]->id);
1352 $self->js->val('[name="converted_from_orderitems_ids[+]"]', '');
1359 sub init_valid_types {
1360 [ sales_order_type(), purchase_order_type(), sales_quotation_type(), request_quotation_type() ];
1366 if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
1367 die "Not a valid type for order";
1370 $self->type($::form->{type});
1376 my $cv = (any { $self->type eq $_ } (sales_order_type(), sales_quotation_type())) ? 'customer'
1377 : (any { $self->type eq $_ } (purchase_order_type(), request_quotation_type())) ? 'vendor'
1378 : die "Not a valid type for order";
1383 sub init_search_cvpartnumber {
1386 my $user_prefs = SL::Helper::UserPreferences::PartPickerSearch->new();
1387 my $search_cvpartnumber;
1388 $search_cvpartnumber = !!$user_prefs->get_sales_search_customer_partnumber() if $self->cv eq 'customer';
1389 $search_cvpartnumber = !!$user_prefs->get_purchase_search_makemodel() if $self->cv eq 'vendor';
1391 return $search_cvpartnumber;
1394 sub init_show_update_button {
1397 !!SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
1408 sub init_all_price_factors {
1409 SL::DB::Manager::PriceFactor->get_all;
1412 sub init_part_picker_classification_ids {
1414 my $attribute = 'used_for_' . ($self->type =~ m{sales} ? 'sale' : 'purchase');
1416 return [ map { $_->id } @{ SL::DB::Manager::PartClassification->get_all(where => [ $attribute => 1 ]) } ];
1422 my $right_for = { map { $_ => $_.'_edit' . ' | ' . $_.'_view' } @{$self->valid_types} };
1424 my $right = $right_for->{ $self->type };
1425 $right ||= 'DOES_NOT_EXIST';
1427 $::auth->assert($right);
1430 sub check_auth_for_edit {
1433 my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
1435 my $right = $right_for->{ $self->type };
1436 $right ||= 'DOES_NOT_EXIST';
1438 $::auth->assert($right);
1441 # build the selection box for contacts
1443 # Needed, if customer/vendor changed.
1444 sub build_contact_select {
1447 select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
1448 value_key => 'cp_id',
1449 title_key => 'full_name_dep',
1450 default => $self->order->cp_id,
1452 style => 'width: 300px',
1456 # build the selection box for the additional billing address
1458 # Needed, if customer/vendor changed.
1459 sub build_billing_address_select {
1462 return '' if $self->cv ne 'customer';
1464 select_tag('order.billing_address_id',
1465 [ {displayable_id => '', id => ''}, $self->order->{$self->cv}->additional_billing_addresses ],
1467 title_key => 'displayable_id',
1468 default => $self->order->billing_address_id,
1470 style => 'width: 300px',
1474 # build the selection box for shiptos
1476 # Needed, if customer/vendor changed.
1477 sub build_shipto_select {
1480 select_tag('order.shipto_id',
1481 [ {displayable_id => t8("No/individual shipping address"), shipto_id => ''}, $self->order->{$self->cv}->shipto ],
1482 value_key => 'shipto_id',
1483 title_key => 'displayable_id',
1484 default => $self->order->shipto_id,
1486 style => 'width: 300px',
1490 # build the inputs for the cusom shipto dialog
1492 # Needed, if customer/vendor changed.
1493 sub build_shipto_inputs {
1496 my $content = $self->p->render('common/_ship_to_dialog',
1497 vc_obj => $self->order->customervendor,
1498 cs_obj => $self->order->custom_shipto,
1499 cvars => $self->order->custom_shipto->cvars_by_config,
1500 id_selector => '#order_shipto_id');
1502 div_tag($content, id => 'shipto_inputs');
1505 # render the info line for business
1507 # Needed, if customer/vendor changed.
1508 sub build_business_info_row
1510 $_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
1513 # build the rows for displaying taxes
1515 # Called if amounts where recalculated and redisplayed.
1516 sub build_tax_rows {
1520 foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
1521 $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
1523 return $rows_as_html;
1527 sub render_price_dialog {
1528 my ($self, $record_item) = @_;
1530 my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
1534 'kivi.io.price_chooser_dialog',
1535 t8('Available Prices'),
1536 $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
1541 # $self->js->text('#dialog_flash_error_content', join ' ', @errors);
1542 # $self->js->show('#dialog_flash_error');
1551 return if !$::form->{id};
1553 $self->order(SL::DB::Order->new(id => $::form->{id})->load);
1555 # Add an empty custom shipto to the order, so that the dialog can render the cvar inputs.
1556 # You need a custom shipto object to call cvars_by_config to get the cvars.
1557 $self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => [])) if !$self->order->custom_shipto;
1559 return $self->order;
1562 # load or create a new order object
1564 # And assign changes from the form to this object.
1565 # If the order is loaded from db, check if items are deleted in the form,
1566 # remove them form the object and collect them for removing from db on saving.
1567 # Then create/update items from form (via make_item) and add them.
1571 # add_items adds items to an order with no items for saving, but they cannot
1572 # be retrieved via items until the order is saved. Adding empty items to new
1573 # order here solves this problem.
1575 $order = SL::DB::Order->new(id => $::form->{id})->load(with => [ 'orderitems', 'orderitems.part' ]) if $::form->{id};
1576 $order ||= SL::DB::Order->new(orderitems => [],
1577 quotation => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type())),
1578 currency_id => $::instance_conf->get_currency_id(),);
1580 my $cv_id_method = $self->cv . '_id';
1581 if (!$::form->{id} && $::form->{$cv_id_method}) {
1582 $order->$cv_id_method($::form->{$cv_id_method});
1583 setup_order_from_cv($order);
1586 my $form_orderitems = delete $::form->{order}->{orderitems};
1587 my $form_periodic_invoices_config = delete $::form->{order}->{periodic_invoices_config};
1589 $order->assign_attributes(%{$::form->{order}});
1591 $self->setup_custom_shipto_from_form($order, $::form);
1593 if (my $periodic_invoices_config_attrs = $form_periodic_invoices_config ? SL::YAML::Load($form_periodic_invoices_config) : undef) {
1594 my $periodic_invoices_config = $order->periodic_invoices_config || $order->periodic_invoices_config(SL::DB::PeriodicInvoicesConfig->new);
1595 $periodic_invoices_config->assign_attributes(%$periodic_invoices_config_attrs);
1598 # remove deleted items
1599 $self->item_ids_to_delete([]);
1600 foreach my $idx (reverse 0..$#{$order->orderitems}) {
1601 my $item = $order->orderitems->[$idx];
1602 if (none { $item->id == $_->{id} } @{$form_orderitems}) {
1603 splice @{$order->orderitems}, $idx, 1;
1604 push @{$self->item_ids_to_delete}, $item->id;
1610 foreach my $form_attr (@{$form_orderitems}) {
1611 my $item = make_item($order, $form_attr);
1612 $item->position($pos);
1616 $order->add_items(grep {!$_->id} @items);
1621 # create or update items from form
1623 # Make item objects from form values. For items already existing read from db.
1624 # Create a new item else. And assign attributes.
1626 my ($record, $attr) = @_;
1629 $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
1631 my $is_new = !$item;
1633 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1634 # they cannot be retrieved via custom_variables until the order/orderitem is
1635 # saved. Adding empty custom_variables to new orderitem here solves this problem.
1636 $item ||= SL::DB::OrderItem->new(custom_variables => []);
1638 $item->assign_attributes(%$attr);
1641 my $texts = get_part_texts($item->part, $record->language_id);
1642 $item->longdescription($texts->{longdescription}) if !defined $attr->{longdescription};
1643 $item->project_id($record->globalproject_id) if !defined $attr->{project_id};
1644 $item->lastcost($record->is_sales ? $item->part->lastcost : 0) if !defined $attr->{lastcost_as_number};
1652 # This is used to add one item
1654 my ($record, $attr) = @_;
1656 my $item = SL::DB::OrderItem->new;
1658 # Remove attributes where the user left or set the inputs empty.
1659 # So these attributes will be undefined and we can distinguish them
1660 # from zero later on.
1661 for (qw(qty_as_number sellprice_as_number discount_as_percent)) {
1662 delete $attr->{$_} if $attr->{$_} eq '';
1665 $item->assign_attributes(%$attr);
1666 $item->qty(1.0) if !$item->qty;
1667 $item->unit($item->part->unit) if !$item->unit;
1669 my ($price_src, $discount_src) = get_best_price_and_discount_source($record, $item, 0);
1672 $new_attr{description} = $item->part->description if ! $item->description;
1673 $new_attr{qty} = 1.0 if ! $item->qty;
1674 $new_attr{price_factor_id} = $item->part->price_factor_id if ! $item->price_factor_id;
1675 $new_attr{sellprice} = $price_src->price;
1676 $new_attr{discount} = $discount_src->discount;
1677 $new_attr{active_price_source} = $price_src;
1678 $new_attr{active_discount_source} = $discount_src;
1679 $new_attr{longdescription} = $item->part->notes if ! defined $attr->{longdescription};
1680 $new_attr{project_id} = $record->globalproject_id;
1681 $new_attr{lastcost} = $record->is_sales ? $item->part->lastcost : 0;
1683 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1684 # they cannot be retrieved via custom_variables until the order/orderitem is
1685 # saved. Adding empty custom_variables to new orderitem here solves this problem.
1686 $new_attr{custom_variables} = [];
1688 my $texts = get_part_texts($item->part, $record->language_id, description => $new_attr{description}, longdescription => $new_attr{longdescription});
1690 $item->assign_attributes(%new_attr, %{ $texts });
1695 sub setup_order_from_cv {
1698 $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id currency_id language_id));
1700 $order->intnotes($order->customervendor->notes);
1702 return if !$order->is_sales;
1704 $order->salesman_id($order->customer->salesman_id || SL::DB::Manager::Employee->current->id);
1705 $order->taxincluded(defined($order->customer->taxincluded_checked)
1706 ? $order->customer->taxincluded_checked
1707 : $::myconfig{taxincluded_checked});
1709 my $address = $order->customer->default_billing_address;;
1710 $order->billing_address_id($address ? $address->id : undef);
1713 # setup custom shipto from form
1715 # The dialog returns form variables starting with 'shipto' and cvars starting
1716 # with 'shiptocvar_'.
1717 # Mark it to be deleted if a shipto from master data is selected
1718 # (i.e. order has a shipto).
1719 # Else, update or create a new custom shipto. If the fields are empty, it
1720 # will not be saved on save.
1721 sub setup_custom_shipto_from_form {
1722 my ($self, $order, $form) = @_;
1724 if ($order->shipto) {
1725 $self->is_custom_shipto_to_delete(1);
1727 my $custom_shipto = $order->custom_shipto || $order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
1729 my $shipto_cvars = {map { my ($key) = m{^shiptocvar_(.+)}; $key => delete $form->{$_}} grep { m{^shiptocvar_} } keys %$form};
1730 my $shipto_attrs = {map { $_ => delete $form->{$_}} grep { m{^shipto} } keys %$form};
1732 $custom_shipto->assign_attributes(%$shipto_attrs);
1733 $custom_shipto->cvar_by_name($_)->value($shipto_cvars->{$_}) for keys %$shipto_cvars;
1737 # recalculate prices and taxes
1739 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1743 my %pat = $self->order->calculate_prices_and_taxes();
1745 $self->{taxes} = [];
1746 foreach my $tax_id (keys %{ $pat{taxes_by_tax_id} }) {
1747 my $netamount = sum0 map { $pat{amounts}->{$_}->{amount} } grep { $pat{amounts}->{$_}->{tax_id} == $tax_id } keys %{ $pat{amounts} };
1749 push(@{ $self->{taxes} }, { amount => $pat{taxes_by_tax_id}->{$tax_id},
1750 netamount => $netamount,
1751 tax => SL::DB::Tax->new(id => $tax_id)->load });
1753 pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items_sorted}, @{$pat{items}};
1756 # get data for saving, printing, ..., that is not changed in the form
1758 # Only cvars for now.
1759 sub get_unalterable_data {
1762 foreach my $item (@{ $self->order->items }) {
1763 # autovivify all cvars that are not in the form (cvars_by_config can do it).
1764 # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1765 foreach my $var (@{ $item->cvars_by_config }) {
1766 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1768 $item->parse_custom_variable_values;
1774 # And remove related files in the spool directory
1779 my $db = $self->order->db;
1781 $db->with_transaction(
1783 my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
1784 $self->order->delete;
1785 my $spool = $::lx_office_conf{paths}->{spool};
1786 unlink map { "$spool/$_" } @spoolfiles if $spool;
1788 $self->save_history('DELETED');
1791 }) || push(@{$errors}, $db->error);
1798 # And delete items that are deleted in the form.
1803 my $db = $self->order->db;
1805 $db->with_transaction(sub {
1806 # delete custom shipto if it is to be deleted or if it is empty
1807 if ($self->order->custom_shipto && ($self->is_custom_shipto_to_delete || $self->order->custom_shipto->is_empty)) {
1808 $self->order->custom_shipto->delete if $self->order->custom_shipto->shipto_id;
1809 $self->order->custom_shipto(undef);
1812 SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete || []};
1813 $self->order->save(cascade => 1);
1816 if ($::form->{converted_from_oe_id}) {
1817 my @converted_from_oe_ids = split ' ', $::form->{converted_from_oe_id};
1819 foreach my $converted_from_oe_id (@converted_from_oe_ids) {
1820 my $src = SL::DB::Order->new(id => $converted_from_oe_id)->load;
1821 $src->update_attributes(closed => 1) if $src->type =~ /_quotation$/;
1822 $src->link_to_record($self->order);
1824 if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1826 foreach (@{ $self->order->items_sorted }) {
1827 my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1829 SL::DB::RecordLink->new(from_table => 'orderitems',
1830 from_id => $from_id,
1831 to_table => 'orderitems',
1838 $self->link_requirement_specs_linking_to_created_from_objects(@converted_from_oe_ids);
1841 $self->set_project_in_linked_requirement_specs if $self->order->globalproject_id;
1843 $self->save_history('SAVED');
1846 }) || push(@{$errors}, $db->error);
1851 sub workflow_sales_or_request_for_quotation {
1855 my $errors = $self->save();
1857 if (scalar @{ $errors }) {
1858 $self->js->flash('error', $_) for @{ $errors };
1859 return $self->js->render();
1862 my $destination_type = $::form->{type} eq sales_order_type() ? sales_quotation_type() : request_quotation_type();
1864 $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1865 delete $::form->{id};
1867 # no linked records from order to quotations
1868 delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
1870 # set item ids to new fake id, to identify them as new items
1871 foreach my $item (@{$self->order->items_sorted}) {
1872 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1876 $::form->{type} = $destination_type;
1877 $self->type($self->init_type);
1878 $self->cv ($self->init_cv);
1882 $self->get_unalterable_data();
1883 $self->pre_render();
1885 # trigger rendering values for second row as hidden, because they
1886 # are loaded only on demand. So we need to keep the values from the
1888 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1892 title => $self->get_title_for('edit'),
1893 %{$self->{template_args}}
1897 sub workflow_sales_or_purchase_order {
1901 my $errors = $self->save();
1903 if (scalar @{ $errors }) {
1904 $self->js->flash('error', $_) foreach @{ $errors };
1905 return $self->js->render();
1908 my $destination_type = $::form->{type} eq sales_quotation_type() ? sales_order_type()
1909 : $::form->{type} eq request_quotation_type() ? purchase_order_type()
1910 : $::form->{type} eq purchase_order_type() ? sales_order_type()
1911 : $::form->{type} eq sales_order_type() ? purchase_order_type()
1914 # check for direct delivery
1915 # copy shipto in custom shipto (custom shipto will be copied by new_from() in case)
1917 if ( $::form->{type} eq sales_order_type() && $destination_type eq purchase_order_type()
1918 && $::form->{use_shipto} && $self->order->shipto) {
1919 $custom_shipto = $self->order->shipto->clone('SL::DB::Order');
1922 $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1923 $self->{converted_from_oe_id} = delete $::form->{id};
1925 # set item ids to new fake id, to identify them as new items
1926 foreach my $item (@{$self->order->items_sorted}) {
1927 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1930 if ($::form->{type} eq sales_order_type() && $destination_type eq purchase_order_type()) {
1931 if ($::form->{use_shipto}) {
1932 $self->order->custom_shipto($custom_shipto) if $custom_shipto;
1934 # remove any custom shipto if not wanted
1935 $self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
1940 $::form->{type} = $destination_type;
1941 $self->type($self->init_type);
1942 $self->cv ($self->init_cv);
1946 $self->get_unalterable_data();
1947 $self->pre_render();
1949 # trigger rendering values for second row as hidden, because they
1950 # are loaded only on demand. So we need to keep the values from the
1952 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1956 title => $self->get_title_for('edit'),
1957 %{$self->{template_args}}
1965 $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
1966 $self->{all_currencies} = SL::DB::Manager::Currency->get_all_sorted();
1967 $self->{all_departments} = SL::DB::Manager::Department->get_all_sorted();
1968 $self->{all_languages} = SL::DB::Manager::Language->get_all_sorted( query => [ or => [ obsolete => 0, id => $self->order->language_id ] ] );
1969 $self->{all_employees} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1972 $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1975 $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1977 $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1978 $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
1979 $self->{periodic_invoices_status} = $self->get_periodic_invoices_status($self->order->periodic_invoices_config);
1980 $self->{order_probabilities} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
1981 $self->{positions_scrollbar_height} = SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
1983 my $print_form = Form->new('');
1984 $print_form->{type} = $self->type;
1985 $print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;
1986 $self->{print_options} = SL::Helper::PrintOptions->get_print_options(
1987 form => $print_form,
1988 options => {dialog_name_prefix => 'print_options.',
1992 no_opendocument => 0,
1996 foreach my $item (@{$self->order->orderitems}) {
1997 my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1998 $item->active_price_source( $price_source->price_from_source( $item->active_price_source ));
1999 $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
2002 if (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())) {
2003 # Calculate shipped qtys here to prevent calling calculate for every item via the items method.
2004 # Do not use write_to_objects to prevent order->delivered to be set, because this should be
2005 # the value from db, which can be set manually or is set when linked delivery orders are saved.
2006 SL::Helper::ShippedQty->new->calculate($self->order)->write_to(\@{$self->order->items});
2009 if ($self->order->number && $::instance_conf->get_webdav) {
2010 my $webdav = SL::Webdav->new(
2011 type => $self->type,
2012 number => $self->order->number,
2014 my @all_objects = $webdav->get_all_objects;
2015 @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
2017 link => File::Spec->catfile($_->full_filedescriptor),
2021 if ( (any { $self->type eq $_ } (sales_quotation_type(), sales_order_type()))
2022 && $::instance_conf->get_transport_cost_reminder_article_number_id ) {
2023 $self->{template_args}->{transport_cost_reminder_article} = SL::DB::Part->new(id => $::instance_conf->get_transport_cost_reminder_article_number_id)->load;
2025 $self->{template_args}->{longdescription_dialog_size_percentage} = SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
2027 $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
2029 $::request->{layout}->use_javascript("${_}.js") for qw(kivi.Validator kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery
2030 edit_periodic_invoices_config calculate_qty follow_up show_history);
2031 $self->setup_edit_action_bar;
2034 sub setup_edit_action_bar {
2035 my ($self, %params) = @_;
2037 my $deletion_allowed = (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type()))
2038 || (($self->type eq sales_order_type()) && $::instance_conf->get_sales_order_show_delete)
2039 || (($self->type eq purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);
2041 my @req_trans_cost_art = qw(kivi.Order.check_transport_cost_article_presence) x!!$::instance_conf->get_transport_cost_reminder_article_number_id;
2042 my @req_cusordnumber = qw(kivi.Order.check_cusordnumber_presence) x($self->type eq sales_order_type() && $::instance_conf->get_order_warn_no_cusordnumber);
2044 my $has_invoice_for_advance_payment;
2045 if ($self->order->id && $self->type eq sales_order_type()) {
2046 my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
2047 $has_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
2050 my $has_final_invoice;
2051 if ($self->order->id && $self->type eq sales_order_type()) {
2052 my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
2053 $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->type} @$lr;
2056 my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
2057 my $right = $right_for->{ $self->type };
2058 $right ||= 'DOES_NOT_EXIST';
2059 my $may_edit_create = $::auth->assert($right, 'may fail');
2061 for my $bar ($::request->layout->get('actionbar')) {
2066 call => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
2067 $::instance_conf->get_order_warn_no_deliverydate,
2069 checks => [ 'kivi.Order.check_save_active_periodic_invoices', ['kivi.validate_form','#order_form'],
2070 @req_trans_cost_art, @req_cusordnumber,
2072 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2075 t8('Save and Close'),
2076 call => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
2077 $::instance_conf->get_order_warn_no_deliverydate,
2080 checks => [ 'kivi.Order.check_save_active_periodic_invoices', ['kivi.validate_form','#order_form'],
2081 @req_trans_cost_art, @req_cusordnumber,
2083 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2087 call => [ 'kivi.Order.save', 'save_as_new', $::instance_conf->get_order_warn_duplicate_parts ],
2088 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2089 @req_trans_cost_art, @req_cusordnumber,
2091 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
2092 : !$self->order->id ? t8('This object has not been saved yet.')
2095 ], # end of combobox "Save"
2102 t8('Save and Quotation'),
2103 submit => [ '#order_form', { action => "Order/sales_quotation" } ],
2104 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2105 only_if => (any { $self->type eq $_ } (sales_order_type())),
2106 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2110 submit => [ '#order_form', { action => "Order/request_for_quotation" } ],
2111 only_if => (any { $self->type eq $_ } (purchase_order_type())),
2112 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2115 t8('Save and Sales Order'),
2116 submit => [ '#order_form', { action => "Order/sales_order" } ],
2117 checks => [ @req_trans_cost_art ],
2118 only_if => (any { $self->type eq $_ } (sales_quotation_type(), purchase_order_type())),
2119 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2122 t8('Save and Purchase Order'),
2123 call => [ 'kivi.Order.purchase_order_check_for_direct_delivery' ],
2124 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2125 only_if => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
2126 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2129 t8('Save and Delivery Order'),
2130 call => [ 'kivi.Order.save', 'save_and_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
2131 $::instance_conf->get_order_warn_no_deliverydate,
2133 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2134 @req_trans_cost_art, @req_cusordnumber,
2136 only_if => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())),
2137 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2140 t8('Save and Supplier Delivery Order'),
2141 call => [ 'kivi.Order.save', 'save_and_supplier_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
2142 $::instance_conf->get_order_warn_no_deliverydate,
2144 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2145 @req_trans_cost_art, @req_cusordnumber,
2147 only_if => (any { $self->type eq $_ } (purchase_order_type())),
2148 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2151 t8('Save and Invoice'),
2152 call => [ 'kivi.Order.save', 'save_and_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
2153 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2154 @req_trans_cost_art, @req_cusordnumber,
2156 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2159 ($has_invoice_for_advance_payment ? t8('Save and Further Invoice for Advance Payment') : t8('Save and Invoice for Advance Payment')),
2160 call => [ 'kivi.Order.save', 'save_and_invoice_for_advance_payment', $::instance_conf->get_order_warn_duplicate_parts ],
2161 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2162 @req_trans_cost_art, @req_cusordnumber,
2164 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
2165 : $has_final_invoice ? t8('This order has already a final invoice.')
2167 only_if => (any { $self->type eq $_ } (sales_order_type())),
2170 t8('Save and Final Invoice'),
2171 call => [ 'kivi.Order.save', 'save_and_final_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
2172 checks => [ 'kivi.Order.check_save_active_periodic_invoices',
2173 @req_trans_cost_art, @req_cusordnumber,
2175 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
2176 : $has_final_invoice ? t8('This order has already a final invoice.')
2178 only_if => (any { $self->type eq $_ } (sales_order_type())) && $has_invoice_for_advance_payment,
2181 t8('Save and AP Transaction'),
2182 call => [ 'kivi.Order.save', 'save_and_ap_transaction', $::instance_conf->get_order_warn_duplicate_parts ],
2183 only_if => (any { $self->type eq $_ } (purchase_order_type())),
2184 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2187 ], # end of combobox "Workflow"
2194 t8('Save and preview PDF'),
2195 call => [ 'kivi.Order.save', 'preview_pdf', $::instance_conf->get_order_warn_duplicate_parts,
2196 $::instance_conf->get_order_warn_no_deliverydate,
2198 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2199 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2202 t8('Save and print'),
2203 call => [ 'kivi.Order.show_print_options', $::instance_conf->get_order_warn_duplicate_parts,
2204 $::instance_conf->get_order_warn_no_deliverydate,
2206 checks => [ @req_trans_cost_art, @req_cusordnumber ],
2207 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
2210 t8('Save and E-mail'),
2211 id => 'save_and_email_action',
2212 call => [ 'kivi.Order.save', 'save_and_show_email_dialog', $::instance_conf->get_order_warn_duplicate_parts,
2213 $::instance_conf->get_order_warn_no_deliverydate,
2215 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
2216 : !$self->order->id ? t8('This object has not been saved yet.')
2220 t8('Download attachments of all parts'),
2221 call => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
2222 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2223 only_if => $::instance_conf->get_doc_storage,
2225 ], # end of combobox "Export"
2229 call => [ 'kivi.Order.delete_order' ],
2230 confirm => $::locale->text('Do you really want to delete this object?'),
2231 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
2232 : !$self->order->id ? t8('This object has not been saved yet.')
2234 only_if => $deletion_allowed,
2243 call => [ 'set_history_window', $self->order->id, 'id' ],
2244 disabled => !$self->order->id ? t8('This record has not been saved yet.') : undef,
2248 call => [ 'kivi.Order.follow_up_window' ],
2249 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2250 only_if => $::auth->assert('productivity', 1),
2252 ], # end of combobox "more"
2258 my ($self, $doc_ref, $params) = @_;
2260 my $order = $self->order;
2263 my $print_form = Form->new('');
2264 $print_form->{type} = $order->type;
2265 $print_form->{formname} = $params->{formname} || $order->type;
2266 $print_form->{format} = $params->{format} || 'pdf';
2267 $print_form->{media} = $params->{media} || 'file';
2268 $print_form->{groupitems} = $params->{groupitems};
2269 $print_form->{printer_id} = $params->{printer_id};
2270 $print_form->{media} = 'file' if $print_form->{media} eq 'screen';
2272 $order->language($params->{language});
2273 $order->flatten_to_form($print_form, format_amounts => 1);
2277 if ($print_form->{format} =~ /(opendocument|oasis)/i) {
2278 $template_ext = 'odt';
2279 $template_type = 'OpenDocument';
2280 } elsif ($print_form->{format} =~ m{html}i) {
2281 $template_ext = 'html';
2282 $template_type = 'HTML';
2285 # search for the template
2286 my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
2287 name => $print_form->{formname},
2288 extension => $template_ext,
2289 email => $print_form->{media} eq 'email',
2290 language => $params->{language},
2291 printer_id => $print_form->{printer_id},
2294 if (!defined $template_file) {
2295 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);
2298 return @errors if scalar @errors;
2300 $print_form->throw_on_error(sub {
2302 $print_form->prepare_for_printing;
2304 $$doc_ref = SL::Helper::CreatePDF->create_pdf(
2305 format => $print_form->{format},
2306 template_type => $template_type,
2307 template => $template_file,
2308 variables => $print_form,
2309 variable_content_types => {
2310 longdescription => 'html',
2311 partnotes => 'html',
2313 $::form->get_variable_content_types_for_cvars,
2317 } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->error : $EVAL_ERROR;
2323 sub get_files_for_email_dialog {
2326 my %files = map { ($_ => []) } qw(versions files vc_files part_files);
2328 return %files if !$::instance_conf->get_doc_storage;
2330 if ($self->order->id) {
2331 $files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id, object_type => $self->order->type, file_type => 'document') ];
2332 $files{files} = [ SL::File->get_all( object_id => $self->order->id, object_type => $self->order->type, file_type => 'attachment') ];
2333 $files{vc_files} = [ SL::File->get_all( object_id => $self->order->{$self->cv}->id, object_type => $self->cv, file_type => 'attachment') ];
2334 $files{project_files} = [ SL::File->get_all( object_id => $self->order->globalproject_id, object_type => 'project', file_type => 'attachment') ];
2338 uniq_by { $_->{id} }
2340 +{ id => $_->part->id,
2341 partnumber => $_->part->partnumber }
2342 } @{$self->order->items_sorted};
2344 foreach my $part (@parts) {
2345 my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
2346 push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
2349 foreach my $key (keys %files) {
2350 $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
2356 sub make_periodic_invoices_config_from_yaml {
2357 my ($yaml_config) = @_;
2359 return if !$yaml_config;
2360 my $attr = SL::YAML::Load($yaml_config);
2361 return if 'HASH' ne ref $attr;
2362 return SL::DB::PeriodicInvoicesConfig->new(%$attr);
2366 sub get_periodic_invoices_status {
2367 my ($self, $config) = @_;
2369 return if $self->type ne sales_order_type();
2370 return t8('not configured') if !$config;
2372 my $active = ('HASH' eq ref $config) ? $config->{active}
2373 : ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
2374 : die "Cannot get status of periodic invoices config";
2376 return $active ? t8('active') : t8('inactive');
2380 my ($self, $action) = @_;
2382 return '' if none { lc($action)} qw(add edit);
2385 # $::locale->text("Add Sales Order");
2386 # $::locale->text("Add Purchase Order");
2387 # $::locale->text("Add Quotation");
2388 # $::locale->text("Add Request for Quotation");
2389 # $::locale->text("Edit Sales Order");
2390 # $::locale->text("Edit Purchase Order");
2391 # $::locale->text("Edit Quotation");
2392 # $::locale->text("Edit Request for Quotation");
2394 $action = ucfirst(lc($action));
2395 return $self->type eq sales_order_type() ? $::locale->text("$action Sales Order")
2396 : $self->type eq purchase_order_type() ? $::locale->text("$action Purchase Order")
2397 : $self->type eq sales_quotation_type() ? $::locale->text("$action Quotation")
2398 : $self->type eq request_quotation_type() ? $::locale->text("$action Request for Quotation")
2402 sub get_item_cvpartnumber {
2403 my ($self, $item) = @_;
2405 return if !$self->search_cvpartnumber;
2406 return if !$self->order->customervendor;
2408 if ($self->cv eq 'vendor') {
2409 my @mms = grep { $_->make eq $self->order->customervendor->id } @{$item->part->makemodels};
2410 $item->{cvpartnumber} = $mms[0]->model if scalar @mms;
2411 } elsif ($self->cv eq 'customer') {
2412 my @cps = grep { $_->customer_id eq $self->order->customervendor->id } @{$item->part->customerprices};
2413 $item->{cvpartnumber} = $cps[0]->customer_partnumber if scalar @cps;
2417 sub get_part_texts {
2418 my ($part_or_id, $language_or_id, %defaults) = @_;
2420 my $part = ref($part_or_id) ? $part_or_id : SL::DB::Part->load_cached($part_or_id);
2421 my $language_id = ref($language_or_id) ? $language_or_id->id : $language_or_id;
2423 description => $defaults{description} // $part->description,
2424 longdescription => $defaults{longdescription} // $part->notes,
2427 return $texts unless $language_id;
2429 my $translation = SL::DB::Manager::Translation->get_first(
2431 parts_id => $part->id,
2432 language_id => $language_id,
2435 $texts->{description} = $translation->translation if $translation && $translation->translation;
2436 $texts->{longdescription} = $translation->longdescription if $translation && $translation->longdescription;
2441 sub get_best_price_and_discount_source {
2442 my ($record, $item, $ignore_given) = @_;
2444 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
2447 if ( $item->part->is_assortment ) {
2448 # add assortment items with price 0, as the components carry the price
2449 $price_src = $price_source->price_from_source("");
2450 $price_src->price(0);
2451 } elsif (!$ignore_given && defined $item->sellprice) {
2452 $price_src = $price_source->price_from_source("");
2453 $price_src->price($item->sellprice);
2455 $price_src = $price_source->best_price
2456 ? $price_source->best_price
2457 : $price_source->price_from_source("");
2458 $price_src->price($::form->round_amount($price_src->price / $record->exchangerate, 5)) if $record->exchangerate;
2459 $price_src->price(0) if !$price_source->best_price;
2463 if (!$ignore_given && defined $item->discount) {
2464 $discount_src = $price_source->discount_from_source("");
2465 $discount_src->discount($item->discount);
2467 $discount_src = $price_source->best_discount
2468 ? $price_source->best_discount
2469 : $price_source->discount_from_source("");
2470 $discount_src->discount(0) if !$price_source->best_discount;
2473 return ($price_src, $discount_src);
2476 sub sales_order_type {
2480 sub purchase_order_type {
2484 sub sales_quotation_type {
2488 sub request_quotation_type {
2489 'request_quotation';
2493 return $_[0]->type eq sales_order_type() ? 'ordnumber'
2494 : $_[0]->type eq purchase_order_type() ? 'ordnumber'
2495 : $_[0]->type eq sales_quotation_type() ? 'quonumber'
2496 : $_[0]->type eq request_quotation_type() ? 'quonumber'
2500 sub save_and_redirect_to {
2501 my ($self, %params) = @_;
2503 my $errors = $self->save();
2505 if (scalar @{ $errors }) {
2506 $self->js->flash('error', $_) foreach @{ $errors };
2507 return $self->js->render();
2510 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
2511 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
2512 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
2513 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
2515 flash_later('info', $text);
2517 $self->redirect_to(%params, id => $self->order->id);
2521 my ($self, $addition) = @_;
2523 my $number_type = $self->order->type =~ m{order} ? 'ordnumber' : 'quonumber';
2524 my $snumbers = $number_type . '_' . $self->order->$number_type;
2526 SL::DB::History->new(
2527 trans_id => $self->order->id,
2528 employee_id => SL::DB::Manager::Employee->current->id,
2529 what_done => $self->order->type,
2530 snumbers => $snumbers,
2531 addition => $addition,
2535 sub store_doc_to_webdav_and_filemanagement {
2536 my ($self, $content, $filename, $variant) = @_;
2538 my $order = $self->order;
2541 # copy file to webdav folder
2542 if ($order->number && $::instance_conf->get_webdav_documents) {
2543 my $webdav = SL::Webdav->new(
2544 type => $order->type,
2545 number => $order->number,
2547 my $webdav_file = SL::Webdav::File->new(
2549 filename => $filename,
2552 $webdav_file->store(data => \$content);
2555 push @errors, t8('Storing the document to the WebDAV folder failed: #1', $@);
2558 if ($order->id && $::instance_conf->get_doc_storage) {
2560 SL::File->save(object_id => $order->id,
2561 object_type => $order->type,
2562 mime_type => SL::MIME->mime_type_from_ext($filename),
2563 source => 'created',
2564 file_type => 'document',
2565 file_name => $filename,
2566 file_contents => $content,
2567 print_variant => $variant);
2570 push @errors, t8('Storing the document in the storage backend failed: #1', $@);
2577 sub link_requirement_specs_linking_to_created_from_objects {
2578 my ($self, @converted_from_oe_ids) = @_;
2580 return unless @converted_from_oe_ids;
2582 my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => \@converted_from_oe_ids ]);
2583 foreach my $rs_order (@{ $rs_orders }) {
2584 SL::DB::RequirementSpecOrder->new(
2585 order_id => $self->order->id,
2586 requirement_spec_id => $rs_order->requirement_spec_id,
2587 version_id => $rs_order->version_id,
2592 sub set_project_in_linked_requirement_specs {
2595 my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => $self->order->id ]);
2596 foreach my $rs_order (@{ $rs_orders }) {
2597 next if $rs_order->requirement_spec->project_id == $self->order->globalproject_id;
2599 $rs_order->requirement_spec->update_attributes(project_id => $self->order->globalproject_id);
2611 SL::Controller::Order - controller for orders
2615 This is a new form to enter orders, completely rewritten with the use
2616 of controller and java script techniques.
2618 The aim is to provide the user a better experience and a faster workflow. Also
2619 the code should be more readable, more reliable and better to maintain.
2627 One input row, so that input happens every time at the same place.
2631 Use of pickers where possible.
2635 Possibility to enter more than one item at once.
2639 Item list in a scrollable area, so that the workflow buttons stay at
2644 Reordering item rows with drag and drop is possible. Sorting item rows is
2645 possible (by partnumber, description, qty, sellprice and discount for now).
2649 No C<update> is necessary. All entries and calculations are managed
2650 with ajax-calls and the page only reloads on C<save>.
2654 User can see changes immediately, because of the use of java script
2665 =item * C<SL/Controller/Order.pm>
2669 =item * C<template/webpages/order/form.html>
2673 =item * C<template/webpages/order/tabs/basic_data.html>
2675 Main tab for basic_data.
2677 This is the only tab here for now. "linked records" and "webdav" tabs are
2678 reused from generic code.
2682 =item * C<template/webpages/order/tabs/_business_info_row.html>
2684 For displaying information on business type
2686 =item * C<template/webpages/order/tabs/_item_input.html>
2688 The input line for items
2690 =item * C<template/webpages/order/tabs/_row.html>
2692 One row for already entered items
2694 =item * C<template/webpages/order/tabs/_tax_row.html>
2696 Displaying tax information
2698 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
2700 Dialog for selecting price and discount sources
2704 =item * C<js/kivi.Order.js>
2706 java script functions
2716 =item * price sources: little symbols showing better price / better discount
2718 =item * select units in input row?
2720 =item * check for direct delivery (workflow sales order -> purchase order)
2722 =item * access rights
2724 =item * display weights
2728 =item * optional client/user behaviour
2730 (transactions has to be set - department has to be set -
2731 force project if enabled in client config)
2735 =head1 KNOWN BUGS AND CAVEATS
2741 No indication that <shift>-up/down expands/collapses second row.
2745 Table header is not sticky in the scrolling area.
2749 Sorting does not include C<position>, neither does reordering.
2751 This behavior was implemented intentionally. But we can discuss, which behavior
2752 should be implemented.
2756 =head1 To discuss / Nice to have
2762 How to expand/collapse second row. Now it can be done clicking the icon or
2767 This controller uses a (changed) copy of the template for the PriceSource
2768 dialog. Maybe there could be used one code source.
2772 Rounding-differences between this controller (PriceTaxCalculator) and the old
2773 form. This is not only a problem here, but also in all parts using the PTC.
2774 There exists a ticket and a patch. This patch should be testet.
2778 An indicator, if the actual inputs are saved (like in an
2779 editor or on text processing application).
2783 A warning when leaving the page without saveing unchanged inputs.
2790 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>