1 package SL::Controller::Order;
 
   4 use parent qw(SL::Controller::Base);
 
   6 use SL::Helper::Flash qw(flash_later);
 
   8 use SL::Locale::String qw(t8);
 
   9 use SL::SessionFile::Random;
 
  21 use SL::Helper::CreatePDF qw(:all);
 
  22 use SL::Helper::PrintOptions;
 
  24 use SL::Controller::Helper::GetModels;
 
  26 use List::Util qw(first);
 
  27 use List::MoreUtils qw(none pairwise first_index);
 
  28 use English qw(-no_match_vars);
 
  31 use Rose::Object::MakeMethods::Generic
 
  33  scalar => [ qw(item_ids_to_delete) ],
 
  34  'scalar --get_set_init' => [ qw(order valid_types type cv p multi_items_models all_price_factors) ],
 
  39 __PACKAGE__->run_before('_check_auth');
 
  41 __PACKAGE__->run_before('_recalc',
 
  42                         only => [ qw(save save_and_delivery_order print create_pdf send_email) ]);
 
  44 __PACKAGE__->run_before('_get_unalterable_data',
 
  45                         only => [ qw(save save_and_delivery_order print create_pdf send_email) ]);
 
  55   $self->order->transdate(DateTime->now_local());
 
  56   $self->order->reqdate(DateTime->today_local->next_workday) if !$self->order->reqdate;
 
  61     title => $self->type eq _sales_order_type()    ? $::locale->text('Add Sales Order')
 
  62            : $self->type eq _purchase_order_type() ? $::locale->text('Add Purchase Order')
 
  64     %{$self->{template_args}}
 
  68 # edit an existing order
 
  77     title => $self->type eq _sales_order_type()    ? $::locale->text('Edit Sales Order')
 
  78            : $self->type eq _purchase_order_type() ? $::locale->text('Edit Purchase Order')
 
  80     %{$self->{template_args}}
 
  88   my $errors = $self->_delete();
 
  90   if (scalar @{ $errors }) {
 
  91     $self->js->flash('error', $_) foreach @{ $errors };
 
  92     return $self->js->render();
 
  95   flash_later('info', $::locale->text('The order has been deleted'));
 
  96   my @redirect_params = (
 
 101   $self->redirect_to(@redirect_params);
 
 108   my $errors = $self->_save();
 
 110   if (scalar @{ $errors }) {
 
 111     $self->js->flash('error', $_) foreach @{ $errors };
 
 112     return $self->js->render();
 
 115   flash_later('info', $::locale->text('The order has been saved'));
 
 116   my @redirect_params = (
 
 119     id     => $self->order->id,
 
 122   $self->redirect_to(@redirect_params);
 
 127 # This is called if "print" is pressed in the print dialog.
 
 128 # If PDF creation was requested and succeeded, the pdf is stored in a session
 
 129 # file and the filename is stored as session value with an unique key. A
 
 130 # javascript function with this key is then called. This function calls the
 
 131 # download action below (action_download_pdf), which offers the file for
 
 136   my $format      = $::form->{print_options}->{format};
 
 137   my $media       = $::form->{print_options}->{media};
 
 138   my $formname    = $::form->{print_options}->{formname};
 
 139   my $copies      = $::form->{print_options}->{copies};
 
 140   my $groupitems  = $::form->{print_options}->{groupitems};
 
 143   if (none { $format eq $_ } qw(pdf)) {
 
 144     return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
 
 147   # only screen or printer by now
 
 148   if (none { $media eq $_ } qw(screen printer)) {
 
 149     return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
 
 153   $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
 
 155   my $form = Form->new;
 
 156   $form->{ordnumber} = $self->order->ordnumber;
 
 157   $form->{type}      = $self->type;
 
 158   $form->{format}    = $format;
 
 159   $form->{formname}  = $formname;
 
 160   $form->{language}  = '_' . $language->template_code if $language;
 
 161   my $pdf_filename   = $form->generate_attachment_filename();
 
 164   my @errors = _create_pdf($self->order, \$pdf, { format     => $format,
 
 165                                                   formname   => $formname,
 
 166                                                   language   => $language,
 
 167                                                   groupitems => $groupitems });
 
 168   if (scalar @errors) {
 
 169     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
 
 172   if ($media eq 'screen') {
 
 174     my $sfile = SL::SessionFile::Random->new(mode => "w");
 
 175     $sfile->fh->print($pdf);
 
 178     my $key = join('_', Time::HiRes::gettimeofday(), int rand 1000000000000);
 
 179     $::auth->set_session_value("Order::create_pdf-${key}" => $sfile->file_name);
 
 182     ->run('kivi.Order.download_pdf', $pdf_filename, $key)
 
 183     ->flash('info', t8('The PDF has been created'));
 
 185   } elsif ($media eq 'printer') {
 
 187     my $printer_id = $::form->{print_options}->{printer_id};
 
 188     SL::DB::Printer->new(id => $printer_id)->load->print_document(
 
 193     $self->js->flash('info', t8('The PDF has been printed'));
 
 196   # copy file to webdav folder
 
 197   if ($self->order->ordnumber && $::instance_conf->get_webdav_documents) {
 
 198     my $webdav = SL::Webdav->new(
 
 200       number   => $self->order->ordnumber,
 
 202     my $webdav_file = SL::Webdav::File->new(
 
 204       filename => $pdf_filename,
 
 207       $webdav_file->store(data => \$pdf);
 
 210       $self->js->flash('error', t8('Storing PDF to webdav folder failed: #1', $@));
 
 213   if ($self->order->ordnumber && $::instance_conf->get_doc_storage) {
 
 214     SL::File->store( object_id     => $self->order->id,
 
 215                      object_type   => $self->type,
 
 216                      mime_type     => 'application/pdf',
 
 218                      file_type     => 'document',
 
 219                      file_name     => $pdf_filename,
 
 220                      file_contents => $pdf);
 
 225 # offer pdf for download
 
 227 # It needs to get the key for the session value to get the pdf file.
 
 228 sub action_download_pdf {
 
 231   my $key = $::form->{key};
 
 232   my $tmp_filename = $::auth->get_session_value("Order::create_pdf-${key}");
 
 233   return $self->send_file(
 
 235     type => 'application/pdf',
 
 236     name => $::form->{pdf_filename},
 
 240 # open the email dialog
 
 241 sub action_show_email_dialog {
 
 244   my $cv_method = $self->cv;
 
 246   if (!$self->order->$cv_method) {
 
 247     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'))
 
 251   $self->{email}->{to}   = $self->order->contact->cp_email if $self->order->contact;
 
 252   $self->{email}->{to} ||= $self->order->$cv_method->email;
 
 253   $self->{email}->{cc}   = $self->order->$cv_method->cc;
 
 254   $self->{email}->{bcc}  = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
 
 255   # Todo: get addresses from shipto, if any
 
 257   my $form = Form->new;
 
 258   $form->{ordnumber} = $self->order->ordnumber;
 
 259   $form->{formname}  = $self->type;
 
 260   $form->{type}      = $self->type;
 
 261   $form->{language} = 'de';
 
 262   $form->{format}   = 'pdf';
 
 264   $self->{email}->{subject}             = $form->generate_email_subject();
 
 265   $self->{email}->{attachment_filename} = $form->generate_attachment_filename();
 
 266   $self->{email}->{message}             = $form->create_email_signature();
 
 268   my $dialog_html = $self->render('order/tabs/_email_dialog', { output => 0 });
 
 270       ->run('kivi.Order.show_email_dialog', $dialog_html)
 
 277 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
 
 278 sub action_send_email {
 
 281   my $mail      = Mailer->new;
 
 282   $mail->{from} = qq|"$::myconfig{name}" <$::myconfig{email}>|;
 
 283   $mail->{$_}   = $::form->{email}->{$_} for qw(to cc bcc subject message);
 
 286   my @errors = _create_pdf($self->order, \$pdf, {media => 'email'});
 
 287   if (scalar @errors) {
 
 288     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render($self);
 
 291   $mail->{attachments} = [{ "content" => $pdf,
 
 292                             "name"    => $::form->{email}->{attachment_filename} }];
 
 294   if (my $err = $mail->send) {
 
 295     return $self->js->flash('error', t8('Sending E-mail: ') . $err)
 
 300   my $intnotes = $self->order->intnotes;
 
 301   $intnotes   .= "\n\n" if $self->order->intnotes;
 
 302   $intnotes   .= t8('[email]')                                                                                        . "\n";
 
 303   $intnotes   .= t8('Date')       . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
 
 304   $intnotes   .= t8('To (email)') . ": " . $mail->{to}                                                                . "\n";
 
 305   $intnotes   .= t8('Cc')         . ": " . $mail->{cc}                                                                . "\n"    if $mail->{cc};
 
 306   $intnotes   .= t8('Bcc')        . ": " . $mail->{bcc}                                                               . "\n"    if $mail->{bcc};
 
 307   $intnotes   .= t8('Subject')    . ": " . $mail->{subject}                                                           . "\n\n";
 
 308   $intnotes   .= t8('Message')    . ": " . $mail->{message};
 
 311       ->val('#order_intnotes', $intnotes)
 
 312       ->run('kivi.Order.close_email_dialog')
 
 316 # save the order and redirect to the frontend subroutine for a new
 
 318 sub action_save_and_delivery_order {
 
 321   my $errors = $self->_save();
 
 323   if (scalar @{ $errors }) {
 
 324     $self->js->flash('error', $_) foreach @{ $errors };
 
 325     return $self->js->render();
 
 327   flash_later('info', $::locale->text('The order has been saved'));
 
 329   my @redirect_params = (
 
 330     controller => 'oe.pl',
 
 331     action     => 'oe_delivery_order_from_order',
 
 332     id         => $self->order->id,
 
 335   $self->redirect_to(@redirect_params);
 
 338 # set form elements in respect to a changed customer or vendor
 
 340 # This action is called on an change of the customer/vendor picker.
 
 341 sub action_customer_vendor_changed {
 
 344   my $cv_method = $self->cv;
 
 346   if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
 
 347     $self->js->show('#cp_row');
 
 349     $self->js->hide('#cp_row');
 
 352   if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
 
 353     $self->js->show('#shipto_row');
 
 355     $self->js->hide('#shipto_row');
 
 358   $self->order->taxzone_id($self->order->$cv_method->taxzone_id);
 
 360   if ($self->order->is_sales) {
 
 361     $self->order->taxincluded(defined($self->order->$cv_method->taxincluded_checked)
 
 362                               ? $self->order->$cv_method->taxincluded_checked
 
 363                               : $::myconfig{taxincluded_checked});
 
 366   $self->order->payment_id($self->order->$cv_method->payment_id);
 
 367   $self->order->delivery_term_id($self->order->$cv_method->delivery_term_id);
 
 372     ->replaceWith('#order_cp_id',            $self->build_contact_select)
 
 373     ->replaceWith('#order_shipto_id',        $self->build_shipto_select)
 
 374     ->val(        '#order_taxzone_id',       $self->order->taxzone_id)
 
 375     ->val(        '#order_taxincluded',      $self->order->taxincluded)
 
 376     ->val(        '#order_payment_id',       $self->order->payment_id)
 
 377     ->val(        '#order_delivery_term_id', $self->order->delivery_term_id)
 
 378     ->val(        '#order_intnotes',         $self->order->$cv_method->notes)
 
 379     ->focus(      '#order_' . $self->cv . '_id');
 
 381   $self->_js_redisplay_amounts_and_taxes;
 
 385 # called if a unit in an existing item row is changed
 
 386 sub action_unit_changed {
 
 389   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
 
 390   my $item = $self->order->items_sorted->[$idx];
 
 392   my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
 
 393   $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
 
 398     ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
 
 399   $self->_js_redisplay_line_values;
 
 400   $self->_js_redisplay_amounts_and_taxes;
 
 404 # add an item row for a new item entered in the input row
 
 405 sub action_add_item {
 
 408   my $form_attr = $::form->{add_item};
 
 410   return unless $form_attr->{parts_id};
 
 412   my $item = _new_item($self->order, $form_attr);
 
 414   $self->order->add_items($item);
 
 418   my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
 
 419   my $row_as_html = $self->p->render('order/tabs/_row',
 
 422                                      ALL_PRICE_FACTORS => $self->all_price_factors
 
 426     ->append('#row_table_id', $row_as_html);
 
 428   if ( $item->part->is_assortment ) {
 
 429     $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
 
 430     foreach my $assortment_item ( @{$item->part->assortment_items} ) {
 
 431       my $attr = { parts_id => $assortment_item->parts_id,
 
 432                    qty      => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
 
 433                    unit     => $assortment_item->unit,
 
 434                    description => $assortment_item->part->description,
 
 436       my $item = _new_item($self->order, $attr);
 
 438       # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
 
 439       $item->discount(1) unless $assortment_item->charge;
 
 441       $self->order->add_items( $item );
 
 443       my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
 
 444       my $row_as_html = $self->p->render('order/tabs/_row',
 
 447                                          ALL_PRICE_FACTORS => $self->all_price_factors
 
 450         ->append('#row_table_id', $row_as_html);
 
 455     ->val('.add_item_input', '')
 
 456     ->run('kivi.Order.init_row_handlers')
 
 457     ->run('kivi.Order.row_table_scroll_down')
 
 458     ->run('kivi.Order.renumber_positions')
 
 459     ->focus('#add_item_parts_id_name');
 
 461   $self->_js_redisplay_amounts_and_taxes;
 
 465 # open the dialog for entering multiple items at once
 
 466 sub action_show_multi_items_dialog {
 
 467   require SL::DB::PartsGroup;
 
 468   $_[0]->render('order/tabs/_multi_items_dialog', { layout => 0 },
 
 469                 all_partsgroups => SL::DB::Manager::PartsGroup->get_all);
 
 472 # update the filter results in the multi item dialog
 
 473 sub action_multi_items_update_result {
 
 476   $::form->{multi_items}->{filter}->{obsolete} = 0;
 
 478   my $count = $_[0]->multi_items_models->count;
 
 481     my $text = SL::Presenter::EscapedText->new(text => $::locale->text('No results.'));
 
 482     $_[0]->render($text, { layout => 0 });
 
 483   } elsif ($count > $max_count) {
 
 484     my $text = SL::Presenter::EscapedText->new(text => $::locale->text('Too many results (#1 from #2).', $count, $max_count));
 
 485     $_[0]->render($text, { layout => 0 });
 
 487     my $multi_items = $_[0]->multi_items_models->get;
 
 488     $_[0]->render('order/tabs/_multi_items_result', { layout => 0 },
 
 489                   multi_items => $multi_items);
 
 493 # add item rows for multiple items at once
 
 494 sub action_add_multi_items {
 
 497   my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_multi_items} };
 
 498   return $self->js->render() unless scalar @form_attr;
 
 501   foreach my $attr (@form_attr) {
 
 502     my $item = _new_item($self->order, $attr);
 
 504     if ( $item->part->is_assortment ) {
 
 505       foreach my $assortment_item ( @{$item->part->assortment_items} ) {
 
 506         my $attr = { parts_id => $assortment_item->parts_id,
 
 507                      qty      => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
 
 508                      unit     => $assortment_item->unit,
 
 509                      description => $assortment_item->part->description,
 
 511         my $item = _new_item($self->order, $attr);
 
 513         # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
 
 514         $item->discount(1) unless $assortment_item->charge;
 
 515         push @items, $assortment_item;
 
 519   $self->order->add_items(@items);
 
 523   foreach my $item (@items) {
 
 524     my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
 
 525     my $row_as_html = $self->p->render('order/tabs/_row',
 
 528                                        ALL_PRICE_FACTORS => $self->all_price_factors
 
 531     $self->js->append('#row_table_id', $row_as_html);
 
 535     ->run('kivi.Order.close_multi_items_dialog')
 
 536     ->run('kivi.Order.init_row_handlers')
 
 537     ->run('kivi.Order.row_table_scroll_down')
 
 538     ->run('kivi.Order.renumber_positions')
 
 539     ->focus('#add_item_parts_id_name');
 
 541   $self->_js_redisplay_amounts_and_taxes;
 
 545 # recalculate all linetotals, amounts and taxes and redisplay them
 
 546 sub action_recalc_amounts_and_taxes {
 
 551   $self->_js_redisplay_line_values;
 
 552   $self->_js_redisplay_amounts_and_taxes;
 
 556 # redisplay item rows if they are sorted by an attribute
 
 557 sub action_reorder_items {
 
 561     partnumber  => sub { $_[0]->part->partnumber },
 
 562     description => sub { $_[0]->description },
 
 563     qty         => sub { $_[0]->qty },
 
 564     sellprice   => sub { $_[0]->sellprice },
 
 565     discount    => sub { $_[0]->discount },
 
 568   my $method = $sort_keys{$::form->{order_by}};
 
 569   my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
 
 570   if ($::form->{sort_dir}) {
 
 571     @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
 
 573     @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
 
 576     ->run('kivi.Order.redisplay_items', \@to_sort)
 
 580 # show the popup to choose a price/discount source
 
 581 sub action_price_popup {
 
 584   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
 
 585   my $item = $self->order->items_sorted->[$idx];
 
 587   $self->render_price_dialog($item);
 
 590 # get the longdescription for an item if the dialog to enter/change the
 
 591 # longdescription was opened and the longdescription is empty
 
 593 # If this item is new, get the longdescription from Part.
 
 594 # Otherwise get it from OrderItem.
 
 595 sub action_get_item_longdescription {
 
 598   if ($::form->{item_id}) {
 
 599     $longdescription = SL::DB::OrderItem->new(id => $::form->{item_id})->load->longdescription;
 
 600   } elsif ($::form->{parts_id}) {
 
 601     $longdescription = SL::DB::Part->new(id => $::form->{parts_id})->load->notes;
 
 603   $_[0]->render(\ $longdescription, { type => 'text' });
 
 606 # load the second row for one or more items
 
 608 # This action gets the html code for all items second rows by rendering a template for
 
 609 # the second row and sets the html code via client js.
 
 610 sub action_load_second_rows {
 
 613   $self->_recalc() if $self->order->is_sales; # for margin calculation
 
 615   foreach my $item_id (@{ $::form->{item_ids} }) {
 
 616     my $idx  = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
 
 617     my $item = $self->order->items_sorted->[$idx];
 
 619     $self->_js_load_second_row($item, $item_id, 0);
 
 622   $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
 
 627 sub _js_load_second_row {
 
 628   my ($self, $item, $item_id, $do_parse) = @_;
 
 631     # Parse values from form (they are formated while rendering (template)).
 
 632     # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
 
 633     # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
 
 634     foreach my $var (@{ $item->cvars_by_config }) {
 
 635       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
 
 637     $item->parse_custom_variable_values;
 
 640   my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item);
 
 643     ->html('.row_entry:has(#item_' . $item_id . ') [name = "second_row"]', $row_as_html)
 
 644     ->data('.row_entry:has(#item_' . $item_id . ') [name = "second_row"]', 'loaded', 1);
 
 647 sub _js_redisplay_line_values {
 
 650   my $is_sales = $self->order->is_sales;
 
 652   # sales orders with margins
 
 657        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
 
 658        $::form->format_amount(\%::myconfig, $_->{marge_total},   2, 0),
 
 659        $::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
 
 660       ]} @{ $self->order->items_sorted };
 
 664        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
 
 665       ]} @{ $self->order->items_sorted };
 
 669     ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
 
 672 sub _js_redisplay_amounts_and_taxes {
 
 675   if (scalar @{ $self->{taxes} }) {
 
 676     $self->js->show('#taxincluded_row_id');
 
 678     $self->js->hide('#taxincluded_row_id');
 
 681   if ($self->order->taxincluded) {
 
 682     $self->js->hide('#subtotal_row_id');
 
 684     $self->js->show('#subtotal_row_id');
 
 688     ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
 
 689     ->html('#amount_id',    $::form->format_amount(\%::myconfig, $self->order->amount,    -2))
 
 691     ->insertBefore($self->build_tax_rows, '#amount_row_id');
 
 698 sub init_valid_types {
 
 699   [ _sales_order_type(), _purchase_order_type() ];
 
 705   if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
 
 706     die "Not a valid type for order";
 
 709   $self->type($::form->{type});
 
 715   my $cv = $self->type eq _sales_order_type()    ? 'customer'
 
 716          : $self->type eq _purchase_order_type() ? 'vendor'
 
 717          : die "Not a valid type for order";
 
 730 # model used to filter/display the parts in the multi-items dialog
 
 731 sub init_multi_items_models {
 
 732   SL::Controller::Helper::GetModels->new(
 
 735     with_objects   => [ qw(unit_obj) ],
 
 736     disable_plugin => 'paginated',
 
 737     source         => $::form->{multi_items},
 
 743       partnumber  => t8('Partnumber'),
 
 744       description => t8('Description')}
 
 748 sub init_all_price_factors {
 
 749   SL::DB::Manager::PriceFactor->get_all;
 
 755   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
 
 757   my $right   = $right_for->{ $self->type };
 
 758   $right    ||= 'DOES_NOT_EXIST';
 
 760   $::auth->assert($right);
 
 763 # build the selection box for contacts
 
 765 # Needed, if customer/vendor changed.
 
 766 sub build_contact_select {
 
 769   $self->p->select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
 
 770                        value_key  => 'cp_id',
 
 771                        title_key  => 'full_name_dep',
 
 772                        default    => $self->order->cp_id,
 
 774                        style      => 'width: 300px',
 
 778 # build the selection box for shiptos
 
 780 # Needed, if customer/vendor changed.
 
 781 sub build_shipto_select {
 
 784   $self->p->select_tag('order.shipto_id', [ $self->order->{$self->cv}->shipto ],
 
 785                        value_key  => 'shipto_id',
 
 786                        title_key  => 'displayable_id',
 
 787                        default    => $self->order->shipto_id,
 
 789                        style      => 'width: 300px',
 
 793 # build the rows for displaying taxes
 
 795 # Called if amounts where recalculated and redisplayed.
 
 800   foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
 
 801     $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
 
 803   return $rows_as_html;
 
 807 sub render_price_dialog {
 
 808   my ($self, $record_item) = @_;
 
 810   my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
 
 814       'kivi.io.price_chooser_dialog',
 
 815       t8('Available Prices'),
 
 816       $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
 
 821 #     $self->js->text('#dialog_flash_error_content', join ' ', @errors);
 
 822 #     $self->js->show('#dialog_flash_error');
 
 831   return if !$::form->{id};
 
 833   $self->order(SL::DB::Manager::Order->find_by(id => $::form->{id}));
 
 836 # load or create a new order object
 
 838 # And assign changes from the for to this object.
 
 839 # If the order is loaded from db, check if items are deleted in the form,
 
 840 # remove them form the object and collect them for removing from db on saving.
 
 841 # Then create/update items from form (via _make_item) and add them.
 
 845   # add_items adds items to an order with no items for saving, but they cannot
 
 846   # be retrieved via items until the order is saved. Adding empty items to new
 
 847   # order here solves this problem.
 
 849   $order   = SL::DB::Manager::Order->find_by(id => $::form->{id}) if $::form->{id};
 
 850   $order ||= SL::DB::Order->new(orderitems => []);
 
 852   my $form_orderitems = delete $::form->{order}->{orderitems};
 
 853   $order->assign_attributes(%{$::form->{order}});
 
 855   # remove deleted items
 
 856   $self->item_ids_to_delete([]);
 
 857   foreach my $idx (reverse 0..$#{$order->orderitems}) {
 
 858     my $item = $order->orderitems->[$idx];
 
 859     if (none { $item->id == $_->{id} } @{$form_orderitems}) {
 
 860       splice @{$order->orderitems}, $idx, 1;
 
 861       push @{$self->item_ids_to_delete}, $item->id;
 
 867   foreach my $form_attr (@{$form_orderitems}) {
 
 868     my $item = _make_item($order, $form_attr);
 
 869     $item->position($pos);
 
 873   $order->add_items(grep {!$_->id} @items);
 
 878 # create or update items from form
 
 880 # Make item objects from form values. For items already existing read from db.
 
 881 # Create a new item else. And assign attributes.
 
 883   my ($record, $attr) = @_;
 
 886   $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
 
 890   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
 
 891   # they cannot be retrieved via custom_variables until the order/orderitem is
 
 892   # saved. Adding empty custom_variables to new orderitem here solves this problem.
 
 893   $item ||= SL::DB::OrderItem->new(custom_variables => []);
 
 895   $item->assign_attributes(%$attr);
 
 896   $item->longdescription($item->part->notes)   if $is_new && !defined $attr->{longdescription};
 
 897   $item->project_id($record->globalproject_id) if $is_new && !defined $attr->{project_id};
 
 898   $item->lastcost($item->part->lastcost)       if $is_new && !defined $attr->{lastcost_as_number};
 
 905 # This is used to add one item
 
 907   my ($record, $attr) = @_;
 
 909   my $item = SL::DB::OrderItem->new;
 
 910   $item->assign_attributes(%$attr);
 
 912   my $part         = SL::DB::Part->new(id => $attr->{parts_id})->load;
 
 913   my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
 
 915   $item->unit($part->unit) if !$item->unit;
 
 918   if ( $part->is_assortment ) {
 
 919     # add assortment items with price 0, as the components carry the price
 
 920     $price_src = $price_source->price_from_source("");
 
 921     $price_src->price(0);
 
 922   } elsif ($item->sellprice) {
 
 923     $price_src = $price_source->price_from_source("");
 
 924     $price_src->price($item->sellprice);
 
 926     $price_src = $price_source->best_price
 
 927            ? $price_source->best_price
 
 928            : $price_source->price_from_source("");
 
 929     $price_src->price(0) if !$price_source->best_price;
 
 933   if ($item->discount) {
 
 934     $discount_src = $price_source->discount_from_source("");
 
 935     $discount_src->discount($item->discount);
 
 937     $discount_src = $price_source->best_discount
 
 938                   ? $price_source->best_discount
 
 939                   : $price_source->discount_from_source("");
 
 940     $discount_src->discount(0) if !$price_source->best_discount;
 
 944   $new_attr{part}                   = $part;
 
 945   $new_attr{description}            = $part->description     if ! $item->description;
 
 946   $new_attr{qty}                    = 1.0                    if ! $item->qty;
 
 947   $new_attr{price_factor_id}        = $part->price_factor_id if ! $item->price_factor_id;
 
 948   $new_attr{sellprice}              = $price_src->price;
 
 949   $new_attr{discount}               = $discount_src->discount;
 
 950   $new_attr{active_price_source}    = $price_src;
 
 951   $new_attr{active_discount_source} = $discount_src;
 
 952   $new_attr{longdescription}        = $part->notes           if ! defined $attr->{longdescription};
 
 953   $new_attr{project_id}             = $record->globalproject_id;
 
 954   $new_attr{lastcost}               = $part->lastcost;
 
 956   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
 
 957   # they cannot be retrieved via custom_variables until the order/orderitem is
 
 958   # saved. Adding empty custom_variables to new orderitem here solves this problem.
 
 959   $new_attr{custom_variables} = [];
 
 961   $item->assign_attributes(%new_attr);
 
 966 # recalculate prices and taxes
 
 968 # Using the PriceTaxCalculator. Store linetotals in the item objects.
 
 972   # bb: todo: currency later
 
 973   $self->order->currency_id($::instance_conf->get_currency_id());
 
 975   my %pat = $self->order->calculate_prices_and_taxes();
 
 977   foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
 
 978     my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
 
 980     my @amount_keys = grep { $pat{amounts}->{$_}->{tax_id} == $tax->id } keys %{ $pat{amounts} };
 
 981     push(@{ $self->{taxes} }, { amount    => $pat{taxes}->{$tax_chart_id},
 
 982                                 netamount => $pat{amounts}->{$amount_keys[0]}->{amount},
 
 986   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
 
 989 # get data for saving, printing, ..., that is not changed in the form
 
 991 # Only cvars for now.
 
 992 sub _get_unalterable_data {
 
 995   foreach my $item (@{ $self->order->items }) {
 
 996     # autovivify all cvars that are not in the form (cvars_by_config can do it).
 
 997     # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
 
 998     foreach my $var (@{ $item->cvars_by_config }) {
 
 999       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
 
1001     $item->parse_custom_variable_values;
 
1007 # And remove related files in the spool directory
 
1012   my $db     = $self->order->db;
 
1014   $db->with_transaction(
 
1016       my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
 
1017       $self->order->delete;
 
1018       my $spool = $::lx_office_conf{paths}->{spool};
 
1019       unlink map { "$spool/$_" } @spoolfiles if $spool;
 
1022   }) || push(@{$errors}, $db->error);
 
1029 # And delete items that are deleted in the form.
 
1034   my $db     = $self->order->db;
 
1036   $db->with_transaction(sub {
 
1037     SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete};
 
1038     $self->order->save(cascade => 1);
 
1039   }) || push(@{$errors}, $db->error);
 
1048   $self->{all_taxzones}        = SL::DB::Manager::TaxZone->get_all_sorted();
 
1049   $self->{all_departments}     = SL::DB::Manager::Department->get_all_sorted();
 
1050   $self->{all_employees}       = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
 
1053   $self->{all_salesmen}        = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
 
1056   $self->{all_projects}        = SL::DB::Manager::Project->get_all(where => [ or => [ id => $self->order->globalproject_id,
 
1058                                                                    sort_by => 'projectnumber');
 
1059   $self->{all_payment_terms}   = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
 
1062   $self->{all_delivery_terms}  = SL::DB::Manager::DeliveryTerm->get_all_sorted();
 
1064   $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
 
1066   my $print_form = Form->new('');
 
1067   $print_form->{type}      = $self->type;
 
1068   $print_form->{printers}  = SL::DB::Manager::Printer->get_all_sorted;
 
1069   $print_form->{languages} = SL::DB::Manager::Language->get_all_sorted;
 
1070   $self->{print_options}   = SL::Helper::PrintOptions->get_print_options(
 
1071     form => $print_form,
 
1072     options => {dialog_name_prefix => 'print_options.',
 
1076                 no_opendocument    => 1,
 
1080   foreach my $item (@{$self->order->orderitems}) {
 
1081     my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
 
1082     $item->active_price_source(   $price_source->price_from_source(   $item->active_price_source   ));
 
1083     $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
 
1086   if ($self->order->ordnumber && $::instance_conf->get_webdav) {
 
1087     my $webdav = SL::Webdav->new(
 
1088       type     => $self->type,
 
1089       number   => $self->order->ordnumber,
 
1091     my $webdav_path = $webdav->webdav_path;
 
1092     my @all_objects = $webdav->get_all_objects;
 
1093     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
 
1095                                                     link => File::Spec->catfile($_->full_filedescriptor),
 
1099   $::request->{layout}->use_javascript("${_}.js")  for qw(kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery);
 
1103   my ($order, $pdf_ref, $params) = @_;
 
1107   my $print_form = Form->new('');
 
1108   $print_form->{type}        = $order->type;
 
1109   $print_form->{formname}    = $params->{formname} || $order->type;
 
1110   $print_form->{format}      = $params->{format}   || 'pdf';
 
1111   $print_form->{media}       = $params->{media}    || 'file';
 
1112   $print_form->{groupitems}  = $params->{groupitems};
 
1113   $print_form->{media}       = 'file'                             if $print_form->{media} eq 'screen';
 
1114   $print_form->{language}    = $params->{language}->template_code if $print_form->{language};
 
1115   $print_form->{language_id} = $params->{language}->id            if $print_form->{language};
 
1117   $order->flatten_to_form($print_form, format_amounts => 1);
 
1119   # search for the template
 
1120   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
 
1121     name        => $print_form->{formname},
 
1122     email       => $print_form->{media} eq 'email',
 
1123     language    => $params->{language},
 
1124     printer_id  => $print_form->{printer_id},  # todo
 
1127   if (!defined $template_file) {
 
1128     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);
 
1131   return @errors if scalar @errors;
 
1133   $print_form->throw_on_error(sub {
 
1135       $print_form->prepare_for_printing;
 
1137       $$pdf_ref = SL::Helper::CreatePDF->create_pdf(
 
1138         template  => $template_file,
 
1139         variables => $print_form,
 
1140         variable_content_types => {
 
1141           longdescription => 'html',
 
1142           partnotes       => 'html',
 
1147     } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
 
1153 sub _sales_order_type {
 
1157 sub _purchase_order_type {
 
1169 SL::Controller::Order - controller for orders
 
1173 This is a new form to enter orders, completely rewritten with the use
 
1174 of controller and java script techniques.
 
1176 The aim is to provide the user a better expirience and a faster flow
 
1177 of work. Also the code should be more readable, more reliable and
 
1186 One input row, so that input happens every time at the same place.
 
1190 Use of pickers where possible.
 
1194 Possibility to enter more than one item at once.
 
1198 Save order only on "save" (and "save and delivery order"-workflow). No
 
1199 hidden save on "print" or "email".
 
1203 Item list in a scrollable area, so that the workflow buttons stay at
 
1208 Reordering item rows with drag and drop is possible. Sorting item rows is
 
1209 possible (by partnumber, description, qty, sellprice and discount for now).
 
1213 No C<update> is necessary. All entries and calculations are managed
 
1214 with ajax-calls and the page does only reload on C<save>.
 
1218 User can see changes immediately, because of the use of java script
 
1229 =item * C<SL/Controller/Order.pm>
 
1233 =item * C<template/webpages/order/form.html>
 
1237 =item * C<template/webpages/order/tabs/basic_data.html>
 
1239 Main tab for basic_data.
 
1241 This is the only tab here for now. "linked records" and "webdav" tabs are
 
1242 reused from generic code.
 
1246 =item * C<template/webpages/order/tabs/_item_input.html>
 
1248 The input line for items
 
1250 =item * C<template/webpages/order/tabs/_row.html>
 
1252 One row for already entered items
 
1254 =item * C<template/webpages/order/tabs/_tax_row.html>
 
1256 Displaying tax information
 
1258 =item * C<template/webpages/order/tabs/_multi_items_dialog.html>
 
1260 Dialog for entering more than one item at once
 
1262 =item * C<template/webpages/order/tabs/_multi_items_result.html>
 
1264 Results for the filter in the multi items dialog
 
1266 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
 
1268 Dialog for selecting price and discount sources
 
1270 =item * C<template/webpages/order/tabs/_email_dialog.html>
 
1276 =item * C<js/kivi.Order.js>
 
1278 java script functions
 
1290 =item * customer/vendor details ('D'-button)
 
1292 =item * credit limit
 
1294 =item * more workflows (save as new / invoice)
 
1296 =item * price sources: little symbols showing better price / better discount
 
1298 =item * select units in input row?
 
1300 =item * custom shipto address
 
1302 =item * periodic invoices
 
1304 =item * language / part translations
 
1306 =item * access rights
 
1308 =item * preset salesman from customer
 
1310 =item * display weights
 
1316 =item * optional client/user behaviour
 
1318 (transactions has to be set - department has to be set -
 
1319  force project if enabled in client config - transport cost reminder)
 
1323 =head1 KNOWN BUGS AND CAVEATS
 
1329 Customer discount is not displayed as a valid discount in price source popup
 
1330 (this might be a bug in price sources)
 
1334 No indication that <shift>-up/down expands/collapses second row.
 
1338 Inline creation of parts is not currently supported
 
1342 Table header is not sticky in the scrolling area.
 
1346 Sorting does not include C<position>, neither does reordering.
 
1348 This behavior was implemented intentionally. But we can discuss, which behavior
 
1349 should be implemented.
 
1353 C<show_multi_items_dialog> does not use the currently inserted string for
 
1358 =head1 To discuss / Nice to have
 
1364 How to expand/collapse second row. Now it can be done clicking the icon or
 
1369 Possibility to change longdescription in input row?
 
1373 Possibility to select PriceSources in input row?
 
1377 This controller uses a (changed) copy of the template for the PriceSource
 
1378 dialog. Maybe there could be used one code source.
 
1382 Rounding-differences between this controller (PriceTaxCalculator) and the old
 
1383 form. This is not only a problem here, but also in all parts using the PTC.
 
1384 There exists a ticket and a patch. This patch should be testet.
 
1388 An indicator, if the actual inputs are saved (like in an
 
1389 editor or on text processing application).
 
1393 A warning when leaving the page without saveing unchanged inputs.
 
1399 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>