1 package SL::Controller::Order;
4 use parent qw(SL::Controller::Base);
6 use SL::Helper::Flash qw(flash_later);
7 use SL::Presenter::Tag qw(select_tag hidden_tag);
8 use SL::Locale::String qw(t8);
9 use SL::SessionFile::Random;
13 use SL::Util qw(trim);
18 use SL::DB::PartsGroup;
21 use SL::DB::RecordLink;
23 use SL::Helper::CreatePDF qw(:all);
24 use SL::Helper::PrintOptions;
25 use SL::Helper::ShippedQty;
27 use SL::Controller::Helper::GetModels;
29 use List::Util qw(first);
30 use List::UtilsBy qw(sort_by uniq_by);
31 use List::MoreUtils qw(any none pairwise first_index);
32 use English qw(-no_match_vars);
36 use Rose::Object::MakeMethods::Generic
38 scalar => [ qw(item_ids_to_delete) ],
39 'scalar --get_set_init' => [ qw(order valid_types type cv p multi_items_models all_price_factors) ],
44 __PACKAGE__->run_before('check_auth');
46 __PACKAGE__->run_before('recalc',
47 only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print send_email) ]);
49 __PACKAGE__->run_before('get_unalterable_data',
50 only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print send_email) ]);
60 $self->order->transdate(DateTime->now_local());
61 my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval : 1;
62 $self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days)) if !$self->order->reqdate;
67 title => $self->get_title_for('add'),
68 %{$self->{template_args}}
72 # edit an existing order
80 # this is to edit an order from an unsaved order object
82 # set item ids to new fake id, to identify them as new items
83 foreach my $item (@{$self->order->items_sorted}) {
84 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
86 # trigger rendering values for second row/longdescription as hidden,
87 # because they are loaded only on demand. So we need to keep the values
89 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
90 $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
97 title => $self->get_title_for('edit'),
98 %{$self->{template_args}}
106 my $errors = $self->delete();
108 if (scalar @{ $errors }) {
109 $self->js->flash('error', $_) foreach @{ $errors };
110 return $self->js->render();
113 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been deleted')
114 : $self->type eq purchase_order_type() ? $::locale->text('The order has been deleted')
115 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been deleted')
116 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been deleted')
118 flash_later('info', $text);
120 my @redirect_params = (
125 $self->redirect_to(@redirect_params);
132 my $errors = $self->save();
134 if (scalar @{ $errors }) {
135 $self->js->flash('error', $_) foreach @{ $errors };
136 return $self->js->render();
139 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
140 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
141 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
142 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
144 flash_later('info', $text);
146 my @redirect_params = (
149 id => $self->order->id,
152 $self->redirect_to(@redirect_params);
155 # save the order as new document an open it for edit
156 sub action_save_as_new {
159 my $order = $self->order;
162 $self->js->flash('error', t8('This object has not been saved yet.'));
163 return $self->js->render();
166 # load order from db to check if values changed
167 my $saved_order = SL::DB::Order->new(id => $order->id)->load;
170 # Lets assign a new number if the user hasn't changed the previous one.
171 # If it has been changed manually then use it as-is.
172 $new_attrs{number} = (trim($order->number) eq $saved_order->number)
174 : trim($order->number);
176 # Clear transdate unless changed
177 $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
178 ? DateTime->today_local
181 # Set new reqdate unless changed
182 if ($order->reqdate == $saved_order->reqdate) {
183 my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval : 1;
184 $new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
186 $new_attrs{reqdate} = $order->reqdate;
190 $new_attrs{employee} = SL::DB::Manager::Employee->current;
192 # Create new record from current one
193 $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
195 # no linked records on save as new
196 delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
199 $self->action_save();
204 # This is called if "print" is pressed in the print dialog.
205 # If PDF creation was requested and succeeded, the pdf is stored in a session
206 # file and the filename is stored as session value with an unique key. A
207 # javascript function with this key is then called. This function calls the
208 # download action below (action_download_pdf), which offers the file for
213 my $errors = $self->save();
215 if (scalar @{ $errors }) {
216 $self->js->flash('error', $_) foreach @{ $errors };
217 return $self->js->render();
220 $self->js->val('#id', $self->order->id)
221 ->val('#order_' . $self->nr_key(), $self->order->number);
223 my $format = $::form->{print_options}->{format};
224 my $media = $::form->{print_options}->{media};
225 my $formname = $::form->{print_options}->{formname};
226 my $copies = $::form->{print_options}->{copies};
227 my $groupitems = $::form->{print_options}->{groupitems};
229 # only pdf and opendocument by now
230 if (none { $format eq $_ } qw(pdf opendocument opendocument_pdf)) {
231 return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
234 # only screen or printer by now
235 if (none { $media eq $_ } qw(screen printer)) {
236 return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
240 $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
242 # create a form for generate_attachment_filename
243 my $form = Form->new;
244 $form->{$self->nr_key()} = $self->order->number;
245 $form->{type} = $self->type;
246 $form->{format} = $format;
247 $form->{formname} = $formname;
248 $form->{language} = '_' . $language->template_code if $language;
249 my $pdf_filename = $form->generate_attachment_filename();
252 my @errors = generate_pdf($self->order, \$pdf, { format => $format,
253 formname => $formname,
254 language => $language,
255 groupitems => $groupitems });
256 if (scalar @errors) {
257 return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
260 if ($media eq 'screen') {
262 my $sfile = SL::SessionFile::Random->new(mode => "w");
263 $sfile->fh->print($pdf);
266 my $key = join('_', Time::HiRes::gettimeofday(), int rand 1000000000000);
267 $::auth->set_session_value("Order::print-${key}" => $sfile->file_name);
270 ->run('kivi.Order.download_pdf', $pdf_filename, $key)
271 ->flash('info', t8('The PDF has been created'));
273 } elsif ($media eq 'printer') {
275 my $printer_id = $::form->{print_options}->{printer_id};
276 SL::DB::Printer->new(id => $printer_id)->load->print_document(
281 $self->js->flash('info', t8('The PDF has been printed'));
284 # copy file to webdav folder
285 if ($self->order->number && $::instance_conf->get_webdav_documents) {
286 my $webdav = SL::Webdav->new(
288 number => $self->order->number,
290 my $webdav_file = SL::Webdav::File->new(
292 filename => $pdf_filename,
295 $webdav_file->store(data => \$pdf);
298 $self->js->flash('error', t8('Storing PDF to webdav folder failed: #1', $@));
301 if ($self->order->number && $::instance_conf->get_doc_storage) {
303 SL::File->save(object_id => $self->order->id,
304 object_type => $self->type,
305 mime_type => 'application/pdf',
307 file_type => 'document',
308 file_name => $pdf_filename,
309 file_contents => $pdf);
312 $self->js->flash('error', t8('Storing PDF in storage backend failed: #1', $@));
318 # offer pdf for download
320 # It needs to get the key for the session value to get the pdf file.
321 sub action_download_pdf {
324 my $key = $::form->{key};
325 my $tmp_filename = $::auth->get_session_value("Order::print-${key}");
326 return $self->send_file(
328 type => 'application/pdf',
329 name => $::form->{pdf_filename},
333 # open the email dialog
334 sub action_show_email_dialog {
337 my $cv_method = $self->cv;
339 if (!$self->order->$cv_method) {
340 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'))
345 $email_form->{to} = $self->order->contact->cp_email if $self->order->contact;
346 $email_form->{to} ||= $self->order->$cv_method->email;
347 $email_form->{cc} = $self->order->$cv_method->cc;
348 $email_form->{bcc} = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
349 # Todo: get addresses from shipto, if any
351 my $form = Form->new;
352 $form->{$self->nr_key()} = $self->order->number;
353 $form->{formname} = $self->type;
354 $form->{type} = $self->type;
355 $form->{language} = 'de';
356 $form->{format} = 'pdf';
358 $email_form->{subject} = $form->generate_email_subject();
359 $email_form->{attachment_filename} = $form->generate_attachment_filename();
360 $email_form->{message} = $form->generate_email_body();
361 $email_form->{js_send_function} = 'kivi.Order.send_email()';
363 my %files = $self->get_files_for_email_dialog();
364 my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
365 email_form => $email_form,
366 show_bcc => $::auth->assert('email_bcc', 'may fail'),
368 is_customer => $self->cv eq 'customer',
372 ->run('kivi.Order.show_email_dialog', $dialog_html)
379 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
380 sub action_send_email {
383 my $errors = $self->save();
385 if (scalar @{ $errors }) {
386 $self->js->run('kivi.Order.close_email_dialog');
387 $self->js->flash('error', $_) foreach @{ $errors };
388 return $self->js->render();
391 $self->js->val('#id', $self->order->id)
392 ->val('#order_' . $self->nr_key(), $self->order->number);
394 my $email_form = delete $::form->{email_form};
395 my %field_names = (to => 'email');
397 $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
399 # for Form::cleanup which may be called in Form::send_email
400 $::form->{cwd} = getcwd();
401 $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
403 $::form->{$_} = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
404 $::form->{media} = 'email';
406 if (($::form->{attachment_policy} // '') !~ m{^(?:old_file|no_file)$}) {
408 $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
411 my @errors = generate_pdf($self->order, \$pdf, {media => $::form->{media},
412 format => $::form->{print_options}->{format},
413 formname => $::form->{print_options}->{formname},
414 language => $language,
415 groupitems => $::form->{print_options}->{groupitems}});
416 if (scalar @errors) {
417 return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render($self);
420 my $sfile = SL::SessionFile::Random->new(mode => "w");
421 $sfile->fh->print($pdf);
424 $::form->{tmpfile} = $sfile->file_name;
425 $::form->{tmpdir} = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
428 $::form->send_email(\%::myconfig, 'pdf');
431 my $intnotes = $self->order->intnotes;
432 $intnotes .= "\n\n" if $self->order->intnotes;
433 $intnotes .= t8('[email]') . "\n";
434 $intnotes .= t8('Date') . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
435 $intnotes .= t8('To (email)') . ": " . $::form->{email} . "\n";
436 $intnotes .= t8('Cc') . ": " . $::form->{cc} . "\n" if $::form->{cc};
437 $intnotes .= t8('Bcc') . ": " . $::form->{bcc} . "\n" if $::form->{bcc};
438 $intnotes .= t8('Subject') . ": " . $::form->{subject} . "\n\n";
439 $intnotes .= t8('Message') . ": " . $::form->{message};
441 $self->order->update_attributes(intnotes => $intnotes);
444 ->val('#order_intnotes', $intnotes)
445 ->run('kivi.Order.close_email_dialog')
446 ->flash('info', t8('The email has been sent.'))
450 # open the periodic invoices config dialog
452 # If there are values in the form (i.e. dialog was opened before),
453 # then use this values. Create new ones, else.
454 sub action_show_periodic_invoices_config_dialog {
457 my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
458 $config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
459 $config ||= SL::DB::PeriodicInvoicesConfig->new(periodicity => 'm',
460 order_value_periodicity => 'p', # = same as periodicity
461 start_date_as_date => $::form->{transdate} || $::form->current_date,
462 extend_automatically_by => 12,
464 email_subject => GenericTranslations->get(
465 language_id => $::form->{language_id},
466 translation_type =>"preset_text_periodic_invoices_email_subject"),
467 email_body => GenericTranslations->get(
468 language_id => $::form->{language_id},
469 translation_type =>"preset_text_periodic_invoices_email_body"),
471 $config->periodicity('m') if none { $_ eq $config->periodicity } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
472 $config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
474 $::form->get_lists(printers => "ALL_PRINTERS",
475 charts => { key => 'ALL_CHARTS',
476 transdate => 'current_date' });
478 $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
480 if ($::form->{customer_id}) {
481 $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
484 $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
486 popup_js_close_function => 'kivi.Order.close_periodic_invoices_config_dialog()',
487 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
492 # assign the values of the periodic invoices config dialog
493 # as yaml in the hidden tag and set the status.
494 sub action_assign_periodic_invoices_config {
497 $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
499 my $config = { active => $::form->{active} ? 1 : 0,
500 terminated => $::form->{terminated} ? 1 : 0,
501 direct_debit => $::form->{direct_debit} ? 1 : 0,
502 periodicity => (any { $_ eq $::form->{periodicity} } @SL::DB::PeriodicInvoicesConfig::PERIODICITIES) ? $::form->{periodicity} : 'm',
503 order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
504 start_date_as_date => $::form->{start_date_as_date},
505 end_date_as_date => $::form->{end_date_as_date},
506 first_billing_date_as_date => $::form->{first_billing_date_as_date},
507 print => $::form->{print} ? 1 : 0,
508 printer_id => $::form->{print} ? $::form->{printer_id} * 1 : undef,
509 copies => $::form->{copies} * 1 ? $::form->{copies} : 1,
510 extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
511 ar_chart_id => $::form->{ar_chart_id} * 1,
512 send_email => $::form->{send_email} ? 1 : 0,
513 email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
514 email_recipient_address => $::form->{email_recipient_address},
515 email_sender => $::form->{email_sender},
516 email_subject => $::form->{email_subject},
517 email_body => $::form->{email_body},
520 my $periodic_invoices_config = YAML::Dump($config);
522 my $status = $self->get_periodic_invoices_status($config);
525 ->remove('#order_periodic_invoices_config')
526 ->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
527 ->run('kivi.Order.close_periodic_invoices_config_dialog')
528 ->html('#periodic_invoices_status', $status)
529 ->flash('info', t8('The periodic invoices config has been assigned.'))
533 sub action_get_has_active_periodic_invoices {
536 my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
537 $config ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
539 my $has_active_periodic_invoices =
540 $self->type eq sales_order_type()
543 && (!$config->end_date || ($config->end_date > DateTime->today_local))
544 && $config->get_previous_billed_period_start_date;
546 $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
549 # save the order and redirect to the frontend subroutine for a new
551 sub action_save_and_delivery_order {
554 my $errors = $self->save();
556 if (scalar @{ $errors }) {
557 $self->js->flash('error', $_) foreach @{ $errors };
558 return $self->js->render();
561 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
562 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
563 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
564 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
566 flash_later('info', $text);
568 my @redirect_params = (
569 controller => 'oe.pl',
570 action => 'oe_delivery_order_from_order',
571 id => $self->order->id,
574 $self->redirect_to(@redirect_params);
577 # save the order and redirect to the frontend subroutine for a new
579 sub action_save_and_invoice {
582 my $errors = $self->save();
584 if (scalar @{ $errors }) {
585 $self->js->flash('error', $_) foreach @{ $errors };
586 return $self->js->render();
589 my $text = $self->type eq sales_order_type() ? $::locale->text('The order has been saved')
590 : $self->type eq purchase_order_type() ? $::locale->text('The order has been saved')
591 : $self->type eq sales_quotation_type() ? $::locale->text('The quotation has been saved')
592 : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
594 flash_later('info', $text);
596 my @redirect_params = (
597 controller => 'oe.pl',
598 action => 'oe_invoice_from_order',
599 id => $self->order->id,
602 $self->redirect_to(@redirect_params);
605 # workflow from sales quotation to sales order
606 sub action_sales_order {
607 $_[0]->workflow_sales_or_purchase_order();
610 # workflow from rfq to purchase order
611 sub action_purchase_order {
612 $_[0]->workflow_sales_or_purchase_order();
615 # set form elements in respect to a changed customer or vendor
617 # This action is called on an change of the customer/vendor picker.
618 sub action_customer_vendor_changed {
621 setup_order_from_cv($self->order);
624 my $cv_method = $self->cv;
626 if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
627 $self->js->show('#cp_row');
629 $self->js->hide('#cp_row');
632 if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
633 $self->js->show('#shipto_row');
635 $self->js->hide('#shipto_row');
638 $self->js->val( '#order_salesman_id', $self->order->salesman_id) if $self->order->is_sales;
641 ->replaceWith('#order_cp_id', $self->build_contact_select)
642 ->replaceWith('#order_shipto_id', $self->build_shipto_select)
643 ->replaceWith('#business_info_row', $self->build_business_info_row)
644 ->val( '#order_taxzone_id', $self->order->taxzone_id)
645 ->val( '#order_taxincluded', $self->order->taxincluded)
646 ->val( '#order_payment_id', $self->order->payment_id)
647 ->val( '#order_delivery_term_id', $self->order->delivery_term_id)
648 ->val( '#order_intnotes', $self->order->intnotes)
649 ->val( '#language_id', $self->order->$cv_method->language_id)
650 ->focus( '#order_' . $self->cv . '_id');
652 $self->js_redisplay_amounts_and_taxes;
656 # open the dialog for customer/vendor details
657 sub action_show_customer_vendor_details_dialog {
660 my $is_customer = 'customer' eq $::form->{vc};
663 $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
665 $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
668 my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
669 $details{discount_as_percent} = $cv->discount_as_percent;
670 $details{creditlimt} = $cv->creditlimit_as_number;
671 $details{business} = $cv->business->description if $cv->business;
672 $details{language} = $cv->language_obj->description if $cv->language_obj;
673 $details{delivery_terms} = $cv->delivery_term->description if $cv->delivery_term;
674 $details{payment_terms} = $cv->payment->description if $cv->payment;
675 $details{pricegroup} = $cv->pricegroup->pricegroup if $is_customer && $cv->pricegroup;
677 foreach my $entry (@{ $cv->shipto }) {
678 push @{ $details{SHIPTO} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
680 foreach my $entry (@{ $cv->contacts }) {
681 push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
684 $_[0]->render('common/show_vc_details', { layout => 0 },
685 is_customer => $is_customer,
690 # called if a unit in an existing item row is changed
691 sub action_unit_changed {
694 my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
695 my $item = $self->order->items_sorted->[$idx];
697 my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
698 $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
703 ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
704 $self->js_redisplay_line_values;
705 $self->js_redisplay_amounts_and_taxes;
709 # add an item row for a new item entered in the input row
710 sub action_add_item {
713 my $form_attr = $::form->{add_item};
715 return unless $form_attr->{parts_id};
717 my $item = new_item($self->order, $form_attr);
719 $self->order->add_items($item);
723 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
724 my $row_as_html = $self->p->render('order/tabs/_row',
728 ALL_PRICE_FACTORS => $self->all_price_factors
732 ->append('#row_table_id', $row_as_html);
734 if ( $item->part->is_assortment ) {
735 $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
736 foreach my $assortment_item ( @{$item->part->assortment_items} ) {
737 my $attr = { parts_id => $assortment_item->parts_id,
738 qty => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
739 unit => $assortment_item->unit,
740 description => $assortment_item->part->description,
742 my $item = new_item($self->order, $attr);
744 # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
745 $item->discount(1) unless $assortment_item->charge;
747 $self->order->add_items( $item );
749 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
750 my $row_as_html = $self->p->render('order/tabs/_row',
754 ALL_PRICE_FACTORS => $self->all_price_factors
757 ->append('#row_table_id', $row_as_html);
762 ->val('.add_item_input', '')
763 ->run('kivi.Order.init_row_handlers')
764 ->run('kivi.Order.row_table_scroll_down')
765 ->run('kivi.Order.renumber_positions')
766 ->focus('#add_item_parts_id_name');
768 $self->js_redisplay_amounts_and_taxes;
772 # open the dialog for entering multiple items at once
773 sub action_show_multi_items_dialog {
774 $_[0]->render('order/tabs/_multi_items_dialog', { layout => 0 },
775 all_partsgroups => SL::DB::Manager::PartsGroup->get_all);
778 # update the filter results in the multi item dialog
779 sub action_multi_items_update_result {
782 $::form->{multi_items}->{filter}->{obsolete} = 0;
784 my $count = $_[0]->multi_items_models->count;
787 my $text = SL::Presenter::EscapedText->new(text => $::locale->text('No results.'));
788 $_[0]->render($text, { layout => 0 });
789 } elsif ($count > $max_count) {
790 my $text = SL::Presenter::EscapedText->new(text => $::locale->text('Too many results (#1 from #2).', $count, $max_count));
791 $_[0]->render($text, { layout => 0 });
793 my $multi_items = $_[0]->multi_items_models->get;
794 $_[0]->render('order/tabs/_multi_items_result', { layout => 0 },
795 multi_items => $multi_items);
799 # add item rows for multiple items at once
800 sub action_add_multi_items {
803 my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_multi_items} };
804 return $self->js->render() unless scalar @form_attr;
807 foreach my $attr (@form_attr) {
808 my $item = new_item($self->order, $attr);
810 if ( $item->part->is_assortment ) {
811 foreach my $assortment_item ( @{$item->part->assortment_items} ) {
812 my $attr = { parts_id => $assortment_item->parts_id,
813 qty => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
814 unit => $assortment_item->unit,
815 description => $assortment_item->part->description,
817 my $item = new_item($self->order, $attr);
819 # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
820 $item->discount(1) unless $assortment_item->charge;
825 $self->order->add_items(@items);
829 foreach my $item (@items) {
830 my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
831 my $row_as_html = $self->p->render('order/tabs/_row',
835 ALL_PRICE_FACTORS => $self->all_price_factors
838 $self->js->append('#row_table_id', $row_as_html);
842 ->run('kivi.Order.close_multi_items_dialog')
843 ->run('kivi.Order.init_row_handlers')
844 ->run('kivi.Order.row_table_scroll_down')
845 ->run('kivi.Order.renumber_positions')
846 ->focus('#add_item_parts_id_name');
848 $self->js_redisplay_amounts_and_taxes;
852 # recalculate all linetotals, amounts and taxes and redisplay them
853 sub action_recalc_amounts_and_taxes {
858 $self->js_redisplay_line_values;
859 $self->js_redisplay_amounts_and_taxes;
863 # redisplay item rows if they are sorted by an attribute
864 sub action_reorder_items {
868 partnumber => sub { $_[0]->part->partnumber },
869 description => sub { $_[0]->description },
870 qty => sub { $_[0]->qty },
871 sellprice => sub { $_[0]->sellprice },
872 discount => sub { $_[0]->discount },
875 my $method = $sort_keys{$::form->{order_by}};
876 my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
877 if ($::form->{sort_dir}) {
878 @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
880 @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
883 ->run('kivi.Order.redisplay_items', \@to_sort)
887 # show the popup to choose a price/discount source
888 sub action_price_popup {
891 my $idx = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
892 my $item = $self->order->items_sorted->[$idx];
894 $self->render_price_dialog($item);
897 # get the longdescription for an item if the dialog to enter/change the
898 # longdescription was opened and the longdescription is empty
900 # If this item is new, get the longdescription from Part.
901 # Otherwise get it from OrderItem.
902 sub action_get_item_longdescription {
905 if ($::form->{item_id}) {
906 $longdescription = SL::DB::OrderItem->new(id => $::form->{item_id})->load->longdescription;
907 } elsif ($::form->{parts_id}) {
908 $longdescription = SL::DB::Part->new(id => $::form->{parts_id})->load->notes;
910 $_[0]->render(\ $longdescription, { type => 'text' });
913 # load the second row for one or more items
915 # This action gets the html code for all items second rows by rendering a template for
916 # the second row and sets the html code via client js.
917 sub action_load_second_rows {
920 $self->recalc() if $self->order->is_sales; # for margin calculation
922 foreach my $item_id (@{ $::form->{item_ids} }) {
923 my $idx = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
924 my $item = $self->order->items_sorted->[$idx];
926 $self->js_load_second_row($item, $item_id, 0);
929 $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
934 sub js_load_second_row {
935 my ($self, $item, $item_id, $do_parse) = @_;
938 # Parse values from form (they are formated while rendering (template)).
939 # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
940 # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
941 foreach my $var (@{ $item->cvars_by_config }) {
942 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
944 $item->parse_custom_variable_values;
947 my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);
950 ->html('.row_entry:has(#item_' . $item_id . ') [name = "second_row"]', $row_as_html)
951 ->data('.row_entry:has(#item_' . $item_id . ') [name = "second_row"]', 'loaded', 1);
954 sub js_redisplay_line_values {
957 my $is_sales = $self->order->is_sales;
959 # sales orders with margins
964 $::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
965 $::form->format_amount(\%::myconfig, $_->{marge_total}, 2, 0),
966 $::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
967 ]} @{ $self->order->items_sorted };
971 $::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0),
972 ]} @{ $self->order->items_sorted };
976 ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
979 sub js_redisplay_amounts_and_taxes {
982 if (scalar @{ $self->{taxes} }) {
983 $self->js->show('#taxincluded_row_id');
985 $self->js->hide('#taxincluded_row_id');
988 if ($self->order->taxincluded) {
989 $self->js->hide('#subtotal_row_id');
991 $self->js->show('#subtotal_row_id');
994 if ($self->order->is_sales) {
995 my $is_neg = $self->order->marge_total < 0;
997 ->html('#marge_total_id', $::form->format_amount(\%::myconfig, $self->order->marge_total, 2))
998 ->html('#marge_percent_id', $::form->format_amount(\%::myconfig, $self->order->marge_percent, 2))
999 ->action_if( $is_neg, 'addClass', '#marge_total_id', 'plus0')
1000 ->action_if( $is_neg, 'addClass', '#marge_percent_id', 'plus0')
1001 ->action_if( $is_neg, 'addClass', '#marge_percent_sign_id', 'plus0')
1002 ->action_if(!$is_neg, 'removeClass', '#marge_total_id', 'plus0')
1003 ->action_if(!$is_neg, 'removeClass', '#marge_percent_id', 'plus0')
1004 ->action_if(!$is_neg, 'removeClass', '#marge_percent_sign_id', 'plus0');
1008 ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
1009 ->html('#amount_id', $::form->format_amount(\%::myconfig, $self->order->amount, -2))
1010 ->remove('.tax_row')
1011 ->insertBefore($self->build_tax_rows, '#amount_row_id');
1018 sub init_valid_types {
1019 [ sales_order_type(), purchase_order_type(), sales_quotation_type(), request_quotation_type() ];
1025 if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
1026 die "Not a valid type for order";
1029 $self->type($::form->{type});
1035 my $cv = (any { $self->type eq $_ } (sales_order_type(), sales_quotation_type())) ? 'customer'
1036 : (any { $self->type eq $_ } (purchase_order_type(), request_quotation_type())) ? 'vendor'
1037 : die "Not a valid type for order";
1050 # model used to filter/display the parts in the multi-items dialog
1051 sub init_multi_items_models {
1052 SL::Controller::Helper::GetModels->new(
1053 controller => $_[0],
1055 with_objects => [ qw(unit_obj) ],
1056 disable_plugin => 'paginated',
1057 source => $::form->{multi_items},
1063 partnumber => t8('Partnumber'),
1064 description => t8('Description')}
1068 sub init_all_price_factors {
1069 SL::DB::Manager::PriceFactor->get_all;
1075 my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
1077 my $right = $right_for->{ $self->type };
1078 $right ||= 'DOES_NOT_EXIST';
1080 $::auth->assert($right);
1083 # build the selection box for contacts
1085 # Needed, if customer/vendor changed.
1086 sub build_contact_select {
1089 select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
1090 value_key => 'cp_id',
1091 title_key => 'full_name_dep',
1092 default => $self->order->cp_id,
1094 style => 'width: 300px',
1098 # build the selection box for shiptos
1100 # Needed, if customer/vendor changed.
1101 sub build_shipto_select {
1104 select_tag('order.shipto_id', [ $self->order->{$self->cv}->shipto ],
1105 value_key => 'shipto_id',
1106 title_key => 'displayable_id',
1107 default => $self->order->shipto_id,
1109 style => 'width: 300px',
1113 # render the info line for business
1115 # Needed, if customer/vendor changed.
1116 sub build_business_info_row
1118 $_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
1121 # build the rows for displaying taxes
1123 # Called if amounts where recalculated and redisplayed.
1124 sub build_tax_rows {
1128 foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
1129 $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
1131 return $rows_as_html;
1135 sub render_price_dialog {
1136 my ($self, $record_item) = @_;
1138 my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
1142 'kivi.io.price_chooser_dialog',
1143 t8('Available Prices'),
1144 $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
1149 # $self->js->text('#dialog_flash_error_content', join ' ', @errors);
1150 # $self->js->show('#dialog_flash_error');
1159 return if !$::form->{id};
1161 $self->order(SL::DB::Order->new(id => $::form->{id})->load);
1164 # load or create a new order object
1166 # And assign changes from the form to this object.
1167 # If the order is loaded from db, check if items are deleted in the form,
1168 # remove them form the object and collect them for removing from db on saving.
1169 # Then create/update items from form (via make_item) and add them.
1173 # add_items adds items to an order with no items for saving, but they cannot
1174 # be retrieved via items until the order is saved. Adding empty items to new
1175 # order here solves this problem.
1177 $order = SL::DB::Manager::Order->find_by(id => $::form->{id}) if $::form->{id};
1178 $order ||= SL::DB::Order->new(orderitems => [],
1179 quotation => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type())));
1181 my $cv_id_method = $self->cv . '_id';
1182 if (!$::form->{id} && $::form->{$cv_id_method}) {
1183 $order->$cv_id_method($::form->{$cv_id_method});
1184 setup_order_from_cv($order);
1187 my $form_orderitems = delete $::form->{order}->{orderitems};
1188 my $form_periodic_invoices_config = delete $::form->{order}->{periodic_invoices_config};
1190 $order->assign_attributes(%{$::form->{order}});
1192 if (my $periodic_invoices_config_attrs = $form_periodic_invoices_config ? YAML::Load($form_periodic_invoices_config) : undef) {
1193 my $periodic_invoices_config = $order->periodic_invoices_config || $order->periodic_invoices_config(SL::DB::PeriodicInvoicesConfig->new);
1194 $periodic_invoices_config->assign_attributes(%$periodic_invoices_config_attrs);
1197 # remove deleted items
1198 $self->item_ids_to_delete([]);
1199 foreach my $idx (reverse 0..$#{$order->orderitems}) {
1200 my $item = $order->orderitems->[$idx];
1201 if (none { $item->id == $_->{id} } @{$form_orderitems}) {
1202 splice @{$order->orderitems}, $idx, 1;
1203 push @{$self->item_ids_to_delete}, $item->id;
1209 foreach my $form_attr (@{$form_orderitems}) {
1210 my $item = make_item($order, $form_attr);
1211 $item->position($pos);
1215 $order->add_items(grep {!$_->id} @items);
1220 # create or update items from form
1222 # Make item objects from form values. For items already existing read from db.
1223 # Create a new item else. And assign attributes.
1225 my ($record, $attr) = @_;
1228 $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
1230 my $is_new = !$item;
1232 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1233 # they cannot be retrieved via custom_variables until the order/orderitem is
1234 # saved. Adding empty custom_variables to new orderitem here solves this problem.
1235 $item ||= SL::DB::OrderItem->new(custom_variables => []);
1237 $item->assign_attributes(%$attr);
1238 $item->longdescription($item->part->notes) if $is_new && !defined $attr->{longdescription};
1239 $item->project_id($record->globalproject_id) if $is_new && !defined $attr->{project_id};
1240 $item->lastcost($record->is_sales ? $item->part->lastcost : 0) if $is_new && !defined $attr->{lastcost_as_number};
1247 # This is used to add one item
1249 my ($record, $attr) = @_;
1251 my $item = SL::DB::OrderItem->new;
1253 # Remove attributes where the user left or set the inputs empty.
1254 # So these attributes will be undefined and we can distinguish them
1255 # from zero later on.
1256 for (qw(qty_as_number sellprice_as_number discount_as_percent)) {
1257 delete $attr->{$_} if $attr->{$_} eq '';
1260 $item->assign_attributes(%$attr);
1262 my $part = SL::DB::Part->new(id => $attr->{parts_id})->load;
1263 my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
1265 $item->unit($part->unit) if !$item->unit;
1268 if ( $part->is_assortment ) {
1269 # add assortment items with price 0, as the components carry the price
1270 $price_src = $price_source->price_from_source("");
1271 $price_src->price(0);
1272 } elsif (defined $item->sellprice) {
1273 $price_src = $price_source->price_from_source("");
1274 $price_src->price($item->sellprice);
1276 $price_src = $price_source->best_price
1277 ? $price_source->best_price
1278 : $price_source->price_from_source("");
1279 $price_src->price(0) if !$price_source->best_price;
1283 if (defined $item->discount) {
1284 $discount_src = $price_source->discount_from_source("");
1285 $discount_src->discount($item->discount);
1287 $discount_src = $price_source->best_discount
1288 ? $price_source->best_discount
1289 : $price_source->discount_from_source("");
1290 $discount_src->discount(0) if !$price_source->best_discount;
1294 $new_attr{part} = $part;
1295 $new_attr{description} = $part->description if ! $item->description;
1296 $new_attr{qty} = 1.0 if ! $item->qty;
1297 $new_attr{price_factor_id} = $part->price_factor_id if ! $item->price_factor_id;
1298 $new_attr{sellprice} = $price_src->price;
1299 $new_attr{discount} = $discount_src->discount;
1300 $new_attr{active_price_source} = $price_src;
1301 $new_attr{active_discount_source} = $discount_src;
1302 $new_attr{longdescription} = $part->notes if ! defined $attr->{longdescription};
1303 $new_attr{project_id} = $record->globalproject_id;
1304 $new_attr{lastcost} = $record->is_sales ? $part->lastcost : 0;
1306 # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1307 # they cannot be retrieved via custom_variables until the order/orderitem is
1308 # saved. Adding empty custom_variables to new orderitem here solves this problem.
1309 $new_attr{custom_variables} = [];
1311 $item->assign_attributes(%new_attr);
1316 sub setup_order_from_cv {
1319 $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id));
1321 $order->intnotes($order->customervendor->notes);
1323 if ($order->is_sales) {
1324 $order->salesman_id($order->customer->salesman_id || SL::DB::Manager::Employee->current->id);
1325 $order->taxincluded(defined($order->customer->taxincluded_checked)
1326 ? $order->customer->taxincluded_checked
1327 : $::myconfig{taxincluded_checked});
1332 # recalculate prices and taxes
1334 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1338 # bb: todo: currency later
1339 $self->order->currency_id($::instance_conf->get_currency_id());
1341 my %pat = $self->order->calculate_prices_and_taxes();
1342 $self->{taxes} = [];
1343 foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
1344 my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
1346 my @amount_keys = grep { $pat{amounts}->{$_}->{tax_id} == $tax->id } keys %{ $pat{amounts} };
1347 push(@{ $self->{taxes} }, { amount => $pat{taxes}->{$tax_chart_id},
1348 netamount => $pat{amounts}->{$amount_keys[0]}->{amount},
1352 pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
1355 # get data for saving, printing, ..., that is not changed in the form
1357 # Only cvars for now.
1358 sub get_unalterable_data {
1361 foreach my $item (@{ $self->order->items }) {
1362 # autovivify all cvars that are not in the form (cvars_by_config can do it).
1363 # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1364 foreach my $var (@{ $item->cvars_by_config }) {
1365 $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1367 $item->parse_custom_variable_values;
1373 # And remove related files in the spool directory
1378 my $db = $self->order->db;
1380 $db->with_transaction(
1382 my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
1383 $self->order->delete;
1384 my $spool = $::lx_office_conf{paths}->{spool};
1385 unlink map { "$spool/$_" } @spoolfiles if $spool;
1388 }) || push(@{$errors}, $db->error);
1395 # And delete items that are deleted in the form.
1400 my $db = $self->order->db;
1402 $db->with_transaction(sub {
1403 SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete};
1404 $self->order->save(cascade => 1);
1407 if ($::form->{converted_from_oe_id}) {
1408 my $src = SL::DB::Order->new(id => $::form->{converted_from_oe_id})->load;
1409 # implement OE::_close_quotations_rfqs - this a 1 : 1 connection
1410 # close only if workflow: quotation -> order. TODO test case
1411 $src->update_attributes(closed => 1) if $src->type =~ /_quotation$/;
1412 $src->link_to_record($self->order);
1414 if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1416 foreach (@{ $self->order->items_sorted }) {
1417 my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1419 SL::DB::RecordLink->new(from_table => 'orderitems',
1420 from_id => $from_id,
1421 to_table => 'orderitems',
1429 }) || push(@{$errors}, $db->error);
1434 sub workflow_sales_or_purchase_order {
1437 my $destination_type = $::form->{type} eq sales_quotation_type() ? sales_order_type()
1438 : $::form->{type} eq request_quotation_type() ? purchase_order_type()
1439 : $::form->{type} eq purchase_order_type() ? sales_order_type()
1440 : $::form->{type} eq sales_order_type() ? purchase_order_type()
1443 $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1444 $self->{converted_from_oe_id} = delete $::form->{id};
1446 # set item ids to new fake id, to identify them as new items
1447 foreach my $item (@{$self->order->items_sorted}) {
1448 $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1452 $::form->{type} = $destination_type;
1453 $self->type($self->init_type);
1454 $self->cv ($self->init_cv);
1458 $self->get_unalterable_data();
1459 $self->pre_render();
1461 # trigger rendering values for second row/longdescription as hidden,
1462 # because they are loaded only on demand. So we need to keep the values
1464 $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1465 $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1469 title => $self->get_title_for('edit'),
1470 %{$self->{template_args}}
1478 $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
1479 $self->{all_departments} = SL::DB::Manager::Department->get_all_sorted();
1480 $self->{all_employees} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1483 $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1486 $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1488 $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1489 $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
1490 $self->{periodic_invoices_status} = $self->get_periodic_invoices_status($self->order->periodic_invoices_config);
1491 $self->{order_probabilities} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
1493 my $print_form = Form->new('');
1494 $print_form->{type} = $self->type;
1495 $print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;
1496 $print_form->{languages} = SL::DB::Manager::Language->get_all_sorted;
1497 $self->{print_options} = SL::Helper::PrintOptions->get_print_options(
1498 form => $print_form,
1499 options => {dialog_name_prefix => 'print_options.',
1503 no_opendocument => 0,
1507 foreach my $item (@{$self->order->orderitems}) {
1508 my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1509 $item->active_price_source( $price_source->price_from_source( $item->active_price_source ));
1510 $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
1513 if (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())) {
1514 # calculate shipped qtys here to prevent calling calculate for every item via the items method
1515 SL::Helper::ShippedQty->new->calculate($self->order)->write_to_objects;
1518 if ($self->order->number && $::instance_conf->get_webdav) {
1519 my $webdav = SL::Webdav->new(
1520 type => $self->type,
1521 number => $self->order->number,
1523 my @all_objects = $webdav->get_all_objects;
1524 @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1526 link => File::Spec->catfile($_->full_filedescriptor),
1530 $::request->{layout}->use_javascript("${_}.js") for qw(kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery edit_periodic_invoices_config calculate_qty);
1531 $self->setup_edit_action_bar;
1534 sub setup_edit_action_bar {
1535 my ($self, %params) = @_;
1537 my $deletion_allowed = (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type()))
1538 || (($self->type eq sales_order_type()) && $::instance_conf->get_sales_order_show_delete)
1539 || (($self->type eq purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);
1541 for my $bar ($::request->layout->get('actionbar')) {
1546 call => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
1547 $::instance_conf->get_order_warn_no_deliverydate,
1549 checks => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1553 call => [ 'kivi.Order.save', 'save_as_new', $::instance_conf->get_order_warn_duplicate_parts ],
1554 checks => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1555 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1557 ], # end of combobox "Save"
1565 submit => [ '#order_form', { action => "Order/sales_order" } ],
1566 only_if => (any { $self->type eq $_ } (sales_quotation_type(), purchase_order_type())),
1567 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1570 t8('Purchase Order'),
1571 submit => [ '#order_form', { action => "Order/purchase_order" } ],
1572 only_if => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
1573 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1576 t8('Save and Delivery Order'),
1577 call => [ 'kivi.Order.save', 'save_and_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
1578 $::instance_conf->get_order_warn_no_deliverydate,
1580 checks => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1581 only_if => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type()))
1584 t8('Save and Invoice'),
1585 call => [ 'kivi.Order.save', 'save_and_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
1586 checks => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1588 ], # end of combobox "Workflow"
1595 t8('Save and print'),
1596 call => [ 'kivi.Order.show_print_options', $::instance_conf->get_order_warn_duplicate_parts ],
1599 t8('Save and E-mail'),
1600 call => [ 'kivi.Order.email', $::instance_conf->get_order_warn_duplicate_parts ],
1603 t8('Download attachments of all parts'),
1604 call => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
1605 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1606 only_if => $::instance_conf->get_doc_storage,
1608 ], # end of combobox "Export"
1612 call => [ 'kivi.Order.delete_order' ],
1613 confirm => $::locale->text('Do you really want to delete this object?'),
1614 disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1615 only_if => $deletion_allowed,
1622 my ($order, $pdf_ref, $params) = @_;
1626 my $print_form = Form->new('');
1627 $print_form->{type} = $order->type;
1628 $print_form->{formname} = $params->{formname} || $order->type;
1629 $print_form->{format} = $params->{format} || 'pdf';
1630 $print_form->{media} = $params->{media} || 'file';
1631 $print_form->{groupitems} = $params->{groupitems};
1632 $print_form->{media} = 'file' if $print_form->{media} eq 'screen';
1634 $order->language($params->{language});
1635 $order->flatten_to_form($print_form, format_amounts => 1);
1639 if ($print_form->{format} =~ /(opendocument|oasis)/i) {
1640 $template_ext = 'odt';
1641 $template_type = 'OpenDocument';
1644 # search for the template
1645 my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1646 name => $print_form->{formname},
1647 extension => $template_ext,
1648 email => $print_form->{media} eq 'email',
1649 language => $params->{language},
1650 printer_id => $print_form->{printer_id}, # todo
1653 if (!defined $template_file) {
1654 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);
1657 return @errors if scalar @errors;
1659 $print_form->throw_on_error(sub {
1661 $print_form->prepare_for_printing;
1663 $$pdf_ref = SL::Helper::CreatePDF->create_pdf(
1664 format => $print_form->{format},
1665 template_type => $template_type,
1666 template => $template_file,
1667 variables => $print_form,
1668 variable_content_types => {
1669 longdescription => 'html',
1670 partnotes => 'html',
1675 } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
1681 sub get_files_for_email_dialog {
1684 my %files = map { ($_ => []) } qw(versions files vc_files part_files);
1686 return %files if !$::instance_conf->get_doc_storage;
1688 if ($self->order->id) {
1689 $files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id, object_type => $self->order->type, file_type => 'document') ];
1690 $files{files} = [ SL::File->get_all( object_id => $self->order->id, object_type => $self->order->type, file_type => 'attachment') ];
1691 $files{vc_files} = [ SL::File->get_all( object_id => $self->order->{$self->cv}->id, object_type => $self->cv, file_type => 'attachment') ];
1695 uniq_by { $_->{id} }
1697 +{ id => $_->part->id,
1698 partnumber => $_->part->partnumber }
1699 } @{$self->order->items_sorted};
1701 foreach my $part (@parts) {
1702 my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
1703 push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
1706 foreach my $key (keys %files) {
1707 $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
1713 sub make_periodic_invoices_config_from_yaml {
1714 my ($yaml_config) = @_;
1716 return if !$yaml_config;
1717 my $attr = YAML::Load($yaml_config);
1718 return if 'HASH' ne ref $attr;
1719 return SL::DB::PeriodicInvoicesConfig->new(%$attr);
1723 sub get_periodic_invoices_status {
1724 my ($self, $config) = @_;
1726 return if $self->type ne sales_order_type();
1727 return t8('not configured') if !$config;
1729 my $active = ('HASH' eq ref $config) ? $config->{active}
1730 : ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
1731 : die "Cannot get status of periodic invoices config";
1733 return $active ? t8('active') : t8('inactive');
1737 my ($self, $action) = @_;
1739 return '' if none { lc($action)} qw(add edit);
1742 # $::locale->text("Add Sales Order");
1743 # $::locale->text("Add Purchase Order");
1744 # $::locale->text("Add Quotation");
1745 # $::locale->text("Add Request for Quotation");
1746 # $::locale->text("Edit Sales Order");
1747 # $::locale->text("Edit Purchase Order");
1748 # $::locale->text("Edit Quotation");
1749 # $::locale->text("Edit Request for Quotation");
1751 $action = ucfirst(lc($action));
1752 return $self->type eq sales_order_type() ? $::locale->text("$action Sales Order")
1753 : $self->type eq purchase_order_type() ? $::locale->text("$action Purchase Order")
1754 : $self->type eq sales_quotation_type() ? $::locale->text("$action Quotation")
1755 : $self->type eq request_quotation_type() ? $::locale->text("$action Request for Quotation")
1759 sub sales_order_type {
1763 sub purchase_order_type {
1767 sub sales_quotation_type {
1771 sub request_quotation_type {
1772 'request_quotation';
1776 return $_[0]->type eq sales_order_type() ? 'ordnumber'
1777 : $_[0]->type eq purchase_order_type() ? 'ordnumber'
1778 : $_[0]->type eq sales_quotation_type() ? 'quonumber'
1779 : $_[0]->type eq request_quotation_type() ? 'quonumber'
1791 SL::Controller::Order - controller for orders
1795 This is a new form to enter orders, completely rewritten with the use
1796 of controller and java script techniques.
1798 The aim is to provide the user a better expirience and a faster flow
1799 of work. Also the code should be more readable, more reliable and
1808 One input row, so that input happens every time at the same place.
1812 Use of pickers where possible.
1816 Possibility to enter more than one item at once.
1820 Item list in a scrollable area, so that the workflow buttons stay at
1825 Reordering item rows with drag and drop is possible. Sorting item rows is
1826 possible (by partnumber, description, qty, sellprice and discount for now).
1830 No C<update> is necessary. All entries and calculations are managed
1831 with ajax-calls and the page does only reload on C<save>.
1835 User can see changes immediately, because of the use of java script
1846 =item * C<SL/Controller/Order.pm>
1850 =item * C<template/webpages/order/form.html>
1854 =item * C<template/webpages/order/tabs/basic_data.html>
1856 Main tab for basic_data.
1858 This is the only tab here for now. "linked records" and "webdav" tabs are
1859 reused from generic code.
1863 =item * C<template/webpages/order/tabs/_business_info_row.html>
1865 For displaying information on business type
1867 =item * C<template/webpages/order/tabs/_item_input.html>
1869 The input line for items
1871 =item * C<template/webpages/order/tabs/_row.html>
1873 One row for already entered items
1875 =item * C<template/webpages/order/tabs/_tax_row.html>
1877 Displaying tax information
1879 =item * C<template/webpages/order/tabs/_multi_items_dialog.html>
1881 Dialog for entering more than one item at once
1883 =item * C<template/webpages/order/tabs/_multi_items_result.html>
1885 Results for the filter in the multi items dialog
1887 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
1889 Dialog for selecting price and discount sources
1893 =item * C<js/kivi.Order.js>
1895 java script functions
1907 =item * credit limit
1909 =item * more workflows (quotation, rfq)
1911 =item * price sources: little symbols showing better price / better discount
1913 =item * select units in input row?
1915 =item * custom shipto address
1917 =item * check for direct delivery (workflow sales order -> purchase order)
1919 =item * language / part translations
1921 =item * access rights
1923 =item * display weights
1929 =item * optional client/user behaviour
1931 (transactions has to be set - department has to be set -
1932 force project if enabled in client config - transport cost reminder)
1936 =head1 KNOWN BUGS AND CAVEATS
1942 Customer discount is not displayed as a valid discount in price source popup
1943 (this might be a bug in price sources)
1945 (I cannot reproduce this (Bernd))
1949 No indication that <shift>-up/down expands/collapses second row.
1953 Inline creation of parts is not currently supported
1957 Table header is not sticky in the scrolling area.
1961 Sorting does not include C<position>, neither does reordering.
1963 This behavior was implemented intentionally. But we can discuss, which behavior
1964 should be implemented.
1968 C<show_multi_items_dialog> does not use the currently inserted string for
1973 The language selected in print or email dialog is not saved when the order is saved.
1977 =head1 To discuss / Nice to have
1983 How to expand/collapse second row. Now it can be done clicking the icon or
1988 Possibility to change longdescription in input row?
1992 Possibility to select PriceSources in input row?
1996 This controller uses a (changed) copy of the template for the PriceSource
1997 dialog. Maybe there could be used one code source.
2001 Rounding-differences between this controller (PriceTaxCalculator) and the old
2002 form. This is not only a problem here, but also in all parts using the PTC.
2003 There exists a ticket and a patch. This patch should be testet.
2007 An indicator, if the actual inputs are saved (like in an
2008 editor or on text processing application).
2012 A warning when leaving the page without saveing unchanged inputs.
2019 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>