Auftrags-Controller: Variable besser benennen …
[kivitendo-erp.git] / SL / Controller / Order.pm
1 package SL::Controller::Order;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
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;
10 use SL::PriceSource;
11 use SL::Webdav;
12 use SL::File;
13 use SL::Util qw(trim);
14 use SL::DB::Order;
15 use SL::DB::Default;
16 use SL::DB::Unit;
17 use SL::DB::Part;
18 use SL::DB::PartsGroup;
19 use SL::DB::Printer;
20 use SL::DB::Language;
21 use SL::DB::RecordLink;
22
23 use SL::Helper::CreatePDF qw(:all);
24 use SL::Helper::PrintOptions;
25 use SL::Helper::ShippedQty;
26
27 use SL::Controller::Helper::GetModels;
28
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);
33 use File::Spec;
34 use Cwd;
35
36 use Rose::Object::MakeMethods::Generic
37 (
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) ],
40 );
41
42
43 # safety
44 __PACKAGE__->run_before('check_auth');
45
46 __PACKAGE__->run_before('recalc',
47                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print send_email) ]);
48
49 __PACKAGE__->run_before('get_unalterable_data',
50                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print send_email) ]);
51
52 #
53 # actions
54 #
55
56 # add a new order
57 sub action_add {
58   my ($self) = @_;
59
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;
63
64   $self->pre_render();
65   $self->render(
66     'order/form',
67     title => $self->get_title_for('add'),
68     %{$self->{template_args}}
69   );
70 }
71
72 # edit an existing order
73 sub action_edit {
74   my ($self) = @_;
75
76   if ($::form->{id}) {
77     $self->load_order;
78
79   } else {
80     # this is to edit an order from an unsaved order object
81
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);
85     }
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
88     # from the source.
89     $_->{render_second_row}      = 1 for @{ $self->order->items_sorted };
90     $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
91   }
92
93   $self->recalc();
94   $self->pre_render();
95   $self->render(
96     'order/form',
97     title => $self->get_title_for('edit'),
98     %{$self->{template_args}}
99   );
100 }
101
102 # delete the order
103 sub action_delete {
104   my ($self) = @_;
105
106   my $errors = $self->delete();
107
108   if (scalar @{ $errors }) {
109     $self->js->flash('error', $_) foreach @{ $errors };
110     return $self->js->render();
111   }
112
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')
117            : '';
118   flash_later('info', $text);
119
120   my @redirect_params = (
121     action => 'add',
122     type   => $self->type,
123   );
124
125   $self->redirect_to(@redirect_params);
126 }
127
128 # save the order
129 sub action_save {
130   my ($self) = @_;
131
132   my $errors = $self->save();
133
134   if (scalar @{ $errors }) {
135     $self->js->flash('error', $_) foreach @{ $errors };
136     return $self->js->render();
137   }
138
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')
143            : '';
144   flash_later('info', $text);
145
146   my @redirect_params = (
147     action => 'edit',
148     type   => $self->type,
149     id     => $self->order->id,
150   );
151
152   $self->redirect_to(@redirect_params);
153 }
154
155 # save the order as new document an open it for edit
156 sub action_save_as_new {
157   my ($self) = @_;
158
159   my $order = $self->order;
160
161   if (!$order->id) {
162     $self->js->flash('error', t8('This object has not been saved yet.'));
163     return $self->js->render();
164   }
165
166   # load order from db to check if values changed
167   my $saved_order = SL::DB::Order->new(id => $order->id)->load;
168
169   my %new_attrs;
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)
173                         ? ''
174                         : trim($order->number);
175
176   # Clear transdate unless changed
177   $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
178                         ? DateTime->today_local
179                         : $order->transdate;
180
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);
185   } else {
186     $new_attrs{reqdate} = $order->reqdate;
187   }
188
189   # Update employee
190   $new_attrs{employee}  = SL::DB::Manager::Employee->current;
191
192   # Create new record from current one
193   $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
194
195   # no linked records on save as new
196   delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
197
198   # save
199   $self->action_save();
200 }
201
202 # print the order
203 #
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
209 # download.
210 sub action_print {
211   my ($self) = @_;
212
213   my $errors = $self->save();
214
215   if (scalar @{ $errors }) {
216     $self->js->flash('error', $_) foreach @{ $errors };
217     return $self->js->render();
218   }
219
220   $self->js->val('#id', $self->order->id)
221            ->val('#order_' . $self->nr_key(), $self->order->number);
222
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};
228
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;
232   }
233
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;
237   }
238
239   my $language;
240   $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
241
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();
250
251   my $pdf;
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;
258   }
259
260   if ($media eq 'screen') {
261     # screen/download
262     my $sfile = SL::SessionFile::Random->new(mode => "w");
263     $sfile->fh->print($pdf);
264     $sfile->fh->close;
265
266     my $key = join('_', Time::HiRes::gettimeofday(), int rand 1000000000000);
267     $::auth->set_session_value("Order::print-${key}" => $sfile->file_name);
268
269     $self->js
270     ->run('kivi.Order.download_pdf', $pdf_filename, $key)
271     ->flash('info', t8('The PDF has been created'));
272
273   } elsif ($media eq 'printer') {
274     # printer
275     my $printer_id = $::form->{print_options}->{printer_id};
276     SL::DB::Printer->new(id => $printer_id)->load->print_document(
277       copies  => $copies,
278       content => $pdf,
279     );
280
281     $self->js->flash('info', t8('The PDF has been printed'));
282   }
283
284   # copy file to webdav folder
285   if ($self->order->number && $::instance_conf->get_webdav_documents) {
286     my $webdav = SL::Webdav->new(
287       type     => $self->type,
288       number   => $self->order->number,
289     );
290     my $webdav_file = SL::Webdav::File->new(
291       webdav   => $webdav,
292       filename => $pdf_filename,
293     );
294     eval {
295       $webdav_file->store(data => \$pdf);
296       1;
297     } or do {
298       $self->js->flash('error', t8('Storing PDF to webdav folder failed: #1', $@));
299     }
300   }
301   if ($self->order->number && $::instance_conf->get_doc_storage) {
302     eval {
303       SL::File->save(object_id     => $self->order->id,
304                      object_type   => $self->type,
305                      mime_type     => 'application/pdf',
306                      source        => 'created',
307                      file_type     => 'document',
308                      file_name     => $pdf_filename,
309                      file_contents => $pdf);
310       1;
311     } or do {
312       $self->js->flash('error', t8('Storing PDF in storage backend failed: #1', $@));
313     }
314   }
315   $self->js->render;
316 }
317
318 # offer pdf for download
319 #
320 # It needs to get the key for the session value to get the pdf file.
321 sub action_download_pdf {
322   my ($self) = @_;
323
324   my $key = $::form->{key};
325   my $tmp_filename = $::auth->get_session_value("Order::print-${key}");
326   return $self->send_file(
327     $tmp_filename,
328     type => 'application/pdf',
329     name => $::form->{pdf_filename},
330   );
331 }
332
333 # open the email dialog
334 sub action_show_email_dialog {
335   my ($self) = @_;
336
337   my $cv_method = $self->cv;
338
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'))
341                     ->render($self);
342   }
343
344   my $email_form;
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
350
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';
357
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()';
362
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'),
367                                   FILES       => \%files,
368                                   is_customer => $self->cv eq 'customer',
369   );
370
371   $self->js
372       ->run('kivi.Order.show_email_dialog', $dialog_html)
373       ->reinit_widgets
374       ->render($self);
375 }
376
377 # send email
378 #
379 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
380 sub action_send_email {
381   my ($self) = @_;
382
383   my $errors = $self->save();
384
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();
389   }
390
391   $self->js->val('#id', $self->order->id)
392            ->val('#order_' . $self->nr_key(), $self->order->number);
393
394   my $email_form  = delete $::form->{email_form};
395   my %field_names = (to => 'email');
396
397   $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
398
399   # for Form::cleanup which may be called in Form::send_email
400   $::form->{cwd}    = getcwd();
401   $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
402
403   $::form->{$_}     = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
404   $::form->{media}  = 'email';
405
406   if (($::form->{attachment_policy} // '') !~ m{^(?:old_file|no_file)$}) {
407     my $language;
408     $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
409
410     my $pdf;
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);
418     }
419
420     my $sfile = SL::SessionFile::Random->new(mode => "w");
421     $sfile->fh->print($pdf);
422     $sfile->fh->close;
423
424     $::form->{tmpfile} = $sfile->file_name;
425     $::form->{tmpdir}  = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
426   }
427
428   $::form->send_email(\%::myconfig, 'pdf');
429
430   # internal notes
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};
440
441   $self->order->update_attributes(intnotes => $intnotes);
442
443   $self->js
444       ->val('#order_intnotes', $intnotes)
445       ->run('kivi.Order.close_email_dialog')
446       ->flash('info', t8('The email has been sent.'))
447       ->render($self);
448 }
449
450 # open the periodic invoices config dialog
451 #
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 {
455   my ($self) = @_;
456
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,
463                                                    active                  => 1,
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"),
470   );
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);
473
474   $::form->get_lists(printers => "ALL_PRINTERS",
475                      charts   => { key       => 'ALL_CHARTS',
476                                    transdate => 'current_date' });
477
478   $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
479
480   if ($::form->{customer_id}) {
481     $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
482   }
483
484   $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
485                 popup_dialog             => 1,
486                 popup_js_close_function  => 'kivi.Order.close_periodic_invoices_config_dialog()',
487                 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
488                 config                   => $config,
489                 %$::form);
490 }
491
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 {
495   my ($self) = @_;
496
497   $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
498
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},
518                };
519
520   my $periodic_invoices_config = YAML::Dump($config);
521
522   my $status = $self->get_periodic_invoices_status($config);
523
524   $self->js
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.'))
530     ->render($self);
531 }
532
533 sub action_get_has_active_periodic_invoices {
534   my ($self) = @_;
535
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};
538
539   my $has_active_periodic_invoices =
540        $self->type eq sales_order_type()
541     && $config
542     && $config->active
543     && (!$config->end_date || ($config->end_date > DateTime->today_local))
544     && $config->get_previous_billed_period_start_date;
545
546   $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
547 }
548
549 # save the order and redirect to the frontend subroutine for a new
550 # delivery order
551 sub action_save_and_delivery_order {
552   my ($self) = @_;
553
554   my $errors = $self->save();
555
556   if (scalar @{ $errors }) {
557     $self->js->flash('error', $_) foreach @{ $errors };
558     return $self->js->render();
559   }
560
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')
565            : '';
566   flash_later('info', $text);
567
568   my @redirect_params = (
569     controller => 'oe.pl',
570     action     => 'oe_delivery_order_from_order',
571     id         => $self->order->id,
572   );
573
574   $self->redirect_to(@redirect_params);
575 }
576
577 # save the order and redirect to the frontend subroutine for a new
578 # invoice
579 sub action_save_and_invoice {
580   my ($self) = @_;
581
582   my $errors = $self->save();
583
584   if (scalar @{ $errors }) {
585     $self->js->flash('error', $_) foreach @{ $errors };
586     return $self->js->render();
587   }
588
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')
593            : '';
594   flash_later('info', $text);
595
596   my @redirect_params = (
597     controller => 'oe.pl',
598     action     => 'oe_invoice_from_order',
599     id         => $self->order->id,
600   );
601
602   $self->redirect_to(@redirect_params);
603 }
604
605 # workflow from sales quotation to sales order
606 sub action_sales_order {
607   $_[0]->workflow_sales_or_purchase_order();
608 }
609
610 # workflow from rfq to purchase order
611 sub action_purchase_order {
612   $_[0]->workflow_sales_or_purchase_order();
613 }
614
615 # set form elements in respect to a changed customer or vendor
616 #
617 # This action is called on an change of the customer/vendor picker.
618 sub action_customer_vendor_changed {
619   my ($self) = @_;
620
621   setup_order_from_cv($self->order);
622   $self->recalc();
623
624   my $cv_method = $self->cv;
625
626   if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
627     $self->js->show('#cp_row');
628   } else {
629     $self->js->hide('#cp_row');
630   }
631
632   if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
633     $self->js->show('#shipto_row');
634   } else {
635     $self->js->hide('#shipto_row');
636   }
637
638   $self->js->val( '#order_salesman_id',      $self->order->salesman_id)        if $self->order->is_sales;
639
640   $self->js
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');
651
652   $self->js_redisplay_amounts_and_taxes;
653   $self->js->render();
654 }
655
656 # open the dialog for customer/vendor details
657 sub action_show_customer_vendor_details_dialog {
658   my ($self) = @_;
659
660   my $is_customer = 'customer' eq $::form->{vc};
661   my $cv;
662   if ($is_customer) {
663     $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
664   } else {
665     $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
666   }
667
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;
676
677   foreach my $entry (@{ $cv->shipto }) {
678     push @{ $details{SHIPTO} },   { map { $_ => $entry->$_ } @{$entry->meta->columns} };
679   }
680   foreach my $entry (@{ $cv->contacts }) {
681     push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
682   }
683
684   $_[0]->render('common/show_vc_details', { layout => 0 },
685                 is_customer => $is_customer,
686                 %details);
687
688 }
689
690 # called if a unit in an existing item row is changed
691 sub action_unit_changed {
692   my ($self) = @_;
693
694   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
695   my $item = $self->order->items_sorted->[$idx];
696
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));
699
700   $self->recalc();
701
702   $self->js
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;
706   $self->js->render();
707 }
708
709 # add an item row for a new item entered in the input row
710 sub action_add_item {
711   my ($self) = @_;
712
713   my $form_attr = $::form->{add_item};
714
715   return unless $form_attr->{parts_id};
716
717   my $item = new_item($self->order, $form_attr);
718
719   $self->order->add_items($item);
720
721   $self->recalc();
722
723   my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
724   my $row_as_html = $self->p->render('order/tabs/_row',
725                                      ITEM              => $item,
726                                      ID                => $item_id,
727                                      TYPE              => $self->type,
728                                      ALL_PRICE_FACTORS => $self->all_price_factors
729   );
730
731   $self->js
732     ->append('#row_table_id', $row_as_html);
733
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,
741                  };
742       my $item = new_item($self->order, $attr);
743
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;
746
747       $self->order->add_items( $item );
748       $self->recalc();
749       my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
750       my $row_as_html = $self->p->render('order/tabs/_row',
751                                          ITEM              => $item,
752                                          ID                => $item_id,
753                                          TYPE              => $self->type,
754                                          ALL_PRICE_FACTORS => $self->all_price_factors
755       );
756       $self->js
757         ->append('#row_table_id', $row_as_html);
758     };
759   };
760
761   $self->js
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');
767
768   $self->js_redisplay_amounts_and_taxes;
769   $self->js->render();
770 }
771
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);
776 }
777
778 # update the filter results in the multi item dialog
779 sub action_multi_items_update_result {
780   my $max_count = 100;
781
782   $::form->{multi_items}->{filter}->{obsolete} = 0;
783
784   my $count = $_[0]->multi_items_models->count;
785
786   if ($count == 0) {
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 });
792   } else {
793     my $multi_items = $_[0]->multi_items_models->get;
794     $_[0]->render('order/tabs/_multi_items_result', { layout => 0 },
795                   multi_items => $multi_items);
796   }
797 }
798
799 # add item rows for multiple items at once
800 sub action_add_multi_items {
801   my ($self) = @_;
802
803   my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_multi_items} };
804   return $self->js->render() unless scalar @form_attr;
805
806   my @items;
807   foreach my $attr (@form_attr) {
808     my $item = new_item($self->order, $attr);
809     push @items, $item;
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,
816                    };
817         my $item = new_item($self->order, $attr);
818
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;
821         push @items, $item;
822       }
823     }
824   }
825   $self->order->add_items(@items);
826
827   $self->recalc();
828
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',
832                                        ITEM              => $item,
833                                        ID                => $item_id,
834                                        TYPE              => $self->type,
835                                        ALL_PRICE_FACTORS => $self->all_price_factors
836     );
837
838     $self->js->append('#row_table_id', $row_as_html);
839   }
840
841   $self->js
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');
847
848   $self->js_redisplay_amounts_and_taxes;
849   $self->js->render();
850 }
851
852 # recalculate all linetotals, amounts and taxes and redisplay them
853 sub action_recalc_amounts_and_taxes {
854   my ($self) = @_;
855
856   $self->recalc();
857
858   $self->js_redisplay_line_values;
859   $self->js_redisplay_amounts_and_taxes;
860   $self->js->render();
861 }
862
863 # redisplay item rows if they are sorted by an attribute
864 sub action_reorder_items {
865   my ($self) = @_;
866
867   my %sort_keys = (
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 },
873   );
874
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;
879   } else {
880     @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
881   }
882   $self->js
883     ->run('kivi.Order.redisplay_items', \@to_sort)
884     ->render;
885 }
886
887 # show the popup to choose a price/discount source
888 sub action_price_popup {
889   my ($self) = @_;
890
891   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
892   my $item = $self->order->items_sorted->[$idx];
893
894   $self->render_price_dialog($item);
895 }
896
897 # get the longdescription for an item if the dialog to enter/change the
898 # longdescription was opened and the longdescription is empty
899 #
900 # If this item is new, get the longdescription from Part.
901 # Otherwise get it from OrderItem.
902 sub action_get_item_longdescription {
903   my $longdescription;
904
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;
909   }
910   $_[0]->render(\ $longdescription, { type => 'text' });
911 }
912
913 # load the second row for one or more items
914 #
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 {
918   my ($self) = @_;
919
920   $self->recalc() if $self->order->is_sales; # for margin calculation
921
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];
925
926     $self->js_load_second_row($item, $item_id, 0);
927   }
928
929   $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
930
931   $self->js->render();
932 }
933
934 sub js_load_second_row {
935   my ($self, $item, $item_id, $do_parse) = @_;
936
937   if ($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}));
943     }
944     $item->parse_custom_variable_values;
945   }
946
947   my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);
948
949   $self->js
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);
952 }
953
954 sub js_redisplay_line_values {
955   my ($self) = @_;
956
957   my $is_sales = $self->order->is_sales;
958
959   # sales orders with margins
960   my @data;
961   if ($is_sales) {
962     @data = map {
963       [
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 };
968   } else {
969     @data = map {
970       [
971        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
972       ]} @{ $self->order->items_sorted };
973   }
974
975   $self->js
976     ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
977 }
978
979 sub js_redisplay_amounts_and_taxes {
980   my ($self) = @_;
981
982   if (scalar @{ $self->{taxes} }) {
983     $self->js->show('#taxincluded_row_id');
984   } else {
985     $self->js->hide('#taxincluded_row_id');
986   }
987
988   if ($self->order->taxincluded) {
989     $self->js->hide('#subtotal_row_id');
990   } else {
991     $self->js->show('#subtotal_row_id');
992   }
993
994   if ($self->order->is_sales) {
995     my $is_neg = $self->order->marge_total < 0;
996     $self->js
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');
1005   }
1006
1007   $self->js
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');
1012 }
1013
1014 #
1015 # helpers
1016 #
1017
1018 sub init_valid_types {
1019   [ sales_order_type(), purchase_order_type(), sales_quotation_type(), request_quotation_type() ];
1020 }
1021
1022 sub init_type {
1023   my ($self) = @_;
1024
1025   if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
1026     die "Not a valid type for order";
1027   }
1028
1029   $self->type($::form->{type});
1030 }
1031
1032 sub init_cv {
1033   my ($self) = @_;
1034
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";
1038
1039   return $cv;
1040 }
1041
1042 sub init_p {
1043   SL::Presenter->get;
1044 }
1045
1046 sub init_order {
1047   $_[0]->make_order;
1048 }
1049
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],
1054     model          => 'Part',
1055     with_objects   => [ qw(unit_obj) ],
1056     disable_plugin => 'paginated',
1057     source         => $::form->{multi_items},
1058     sorted         => {
1059       _default    => {
1060         by  => 'partnumber',
1061         dir => 1,
1062       },
1063       partnumber  => t8('Partnumber'),
1064       description => t8('Description')}
1065   );
1066 }
1067
1068 sub init_all_price_factors {
1069   SL::DB::Manager::PriceFactor->get_all;
1070 }
1071
1072 sub check_auth {
1073   my ($self) = @_;
1074
1075   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
1076
1077   my $right   = $right_for->{ $self->type };
1078   $right    ||= 'DOES_NOT_EXIST';
1079
1080   $::auth->assert($right);
1081 }
1082
1083 # build the selection box for contacts
1084 #
1085 # Needed, if customer/vendor changed.
1086 sub build_contact_select {
1087   my ($self) = @_;
1088
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,
1093     with_empty => 1,
1094     style      => 'width: 300px',
1095   );
1096 }
1097
1098 # build the selection box for shiptos
1099 #
1100 # Needed, if customer/vendor changed.
1101 sub build_shipto_select {
1102   my ($self) = @_;
1103
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,
1108     with_empty => 1,
1109     style      => 'width: 300px',
1110   );
1111 }
1112
1113 # render the info line for business
1114 #
1115 # Needed, if customer/vendor changed.
1116 sub build_business_info_row
1117 {
1118   $_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
1119 }
1120
1121 # build the rows for displaying taxes
1122 #
1123 # Called if amounts where recalculated and redisplayed.
1124 sub build_tax_rows {
1125   my ($self) = @_;
1126
1127   my $rows_as_html;
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);
1130   }
1131   return $rows_as_html;
1132 }
1133
1134
1135 sub render_price_dialog {
1136   my ($self, $record_item) = @_;
1137
1138   my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
1139
1140   $self->js
1141     ->run(
1142       'kivi.io.price_chooser_dialog',
1143       t8('Available Prices'),
1144       $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
1145     )
1146     ->reinit_widgets;
1147
1148 #   if (@errors) {
1149 #     $self->js->text('#dialog_flash_error_content', join ' ', @errors);
1150 #     $self->js->show('#dialog_flash_error');
1151 #   }
1152
1153   $self->js->render;
1154 }
1155
1156 sub load_order {
1157   my ($self) = @_;
1158
1159   return if !$::form->{id};
1160
1161   $self->order(SL::DB::Order->new(id => $::form->{id})->load);
1162 }
1163
1164 # load or create a new order object
1165 #
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.
1170 sub make_order {
1171   my ($self) = @_;
1172
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.
1176   my $order;
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())));
1180
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);
1185   }
1186
1187   my $form_orderitems               = delete $::form->{order}->{orderitems};
1188   my $form_periodic_invoices_config = delete $::form->{order}->{periodic_invoices_config};
1189
1190   $order->assign_attributes(%{$::form->{order}});
1191
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);
1195   }
1196
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;
1204     }
1205   }
1206
1207   my @items;
1208   my $pos = 1;
1209   foreach my $form_attr (@{$form_orderitems}) {
1210     my $item = make_item($order, $form_attr);
1211     $item->position($pos);
1212     push @items, $item;
1213     $pos++;
1214   }
1215   $order->add_items(grep {!$_->id} @items);
1216
1217   return $order;
1218 }
1219
1220 # create or update items from form
1221 #
1222 # Make item objects from form values. For items already existing read from db.
1223 # Create a new item else. And assign attributes.
1224 sub make_item {
1225   my ($record, $attr) = @_;
1226
1227   my $item;
1228   $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
1229
1230   my $is_new = !$item;
1231
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 => []);
1236
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};
1241
1242   return $item;
1243 }
1244
1245 # create a new item
1246 #
1247 # This is used to add one item
1248 sub new_item {
1249   my ($record, $attr) = @_;
1250
1251   my $item = SL::DB::OrderItem->new;
1252
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 '';
1258   }
1259
1260   $item->assign_attributes(%$attr);
1261
1262   my $part         = SL::DB::Part->new(id => $attr->{parts_id})->load;
1263   my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
1264
1265   $item->unit($part->unit) if !$item->unit;
1266
1267   my $price_src;
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);
1275   } else {
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;
1280   }
1281
1282   my $discount_src;
1283   if (defined $item->discount) {
1284     $discount_src = $price_source->discount_from_source("");
1285     $discount_src->discount($item->discount);
1286   } else {
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;
1291   }
1292
1293   my %new_attr;
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;
1305
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} = [];
1310
1311   $item->assign_attributes(%new_attr);
1312
1313   return $item;
1314 }
1315
1316 sub setup_order_from_cv {
1317   my ($order) = @_;
1318
1319   $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id));
1320
1321   $order->intnotes($order->customervendor->notes);
1322
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});
1328   }
1329
1330 }
1331
1332 # recalculate prices and taxes
1333 #
1334 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1335 sub recalc {
1336   my ($self) = @_;
1337
1338   # bb: todo: currency later
1339   $self->order->currency_id($::instance_conf->get_currency_id());
1340
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);
1345
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},
1349                                 tax       => $tax });
1350   }
1351
1352   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
1353 }
1354
1355 # get data for saving, printing, ..., that is not changed in the form
1356 #
1357 # Only cvars for now.
1358 sub get_unalterable_data {
1359   my ($self) = @_;
1360
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}));
1366     }
1367     $item->parse_custom_variable_values;
1368   }
1369 }
1370
1371 # delete the order
1372 #
1373 # And remove related files in the spool directory
1374 sub delete {
1375   my ($self) = @_;
1376
1377   my $errors = [];
1378   my $db     = $self->order->db;
1379
1380   $db->with_transaction(
1381     sub {
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;
1386
1387       1;
1388   }) || push(@{$errors}, $db->error);
1389
1390   return $errors;
1391 }
1392
1393 # save the order
1394 #
1395 # And delete items that are deleted in the form.
1396 sub save {
1397   my ($self) = @_;
1398
1399   my $errors = [];
1400   my $db     = $self->order->db;
1401
1402   $db->with_transaction(sub {
1403     SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete};
1404     $self->order->save(cascade => 1);
1405
1406     # link records
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);
1413
1414       if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1415         my $idx = 0;
1416         foreach (@{ $self->order->items_sorted }) {
1417           my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1418           next if !$from_id;
1419           SL::DB::RecordLink->new(from_table => 'orderitems',
1420                                   from_id    => $from_id,
1421                                   to_table   => 'orderitems',
1422                                   to_id      => $_->id
1423           )->save;
1424           $idx++;
1425         }
1426       }
1427     }
1428     1;
1429   }) || push(@{$errors}, $db->error);
1430
1431   return $errors;
1432 }
1433
1434 sub workflow_sales_or_purchase_order {
1435   my ($self) = @_;
1436
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()
1441                        : '';
1442
1443   $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1444   $self->{converted_from_oe_id} = delete $::form->{id};
1445
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);
1449   }
1450
1451   # change form type
1452   $::form->{type} = $destination_type;
1453   $self->type($self->init_type);
1454   $self->cv  ($self->init_cv);
1455   $self->check_auth;
1456
1457   $self->recalc();
1458   $self->get_unalterable_data();
1459   $self->pre_render();
1460
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
1463   # from the source.
1464   $_->{render_second_row}      = 1 for @{ $self->order->items_sorted };
1465   $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1466
1467   $self->render(
1468     'order/form',
1469     title => $self->get_title_for('edit'),
1470     %{$self->{template_args}}
1471   );
1472 }
1473
1474
1475 sub pre_render {
1476   my ($self) = @_;
1477
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,
1481                                                                                             deleted => 0 ] ],
1482                                                                          sort_by => 'name');
1483   $self->{all_salesmen}             = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1484                                                                                             deleted => 0 ] ],
1485                                                                          sort_by => 'name');
1486   $self->{all_payment_terms}        = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1487                                                                                                       obsolete => 0 ] ]);
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) ];
1492
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.',
1500                 show_headers       => 1,
1501                 no_queue           => 1,
1502                 no_postscript      => 1,
1503                 no_opendocument    => 0,
1504                 no_html            => 1},
1505   );
1506
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));
1511   }
1512
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;
1516   }
1517
1518   if ($self->order->number && $::instance_conf->get_webdav) {
1519     my $webdav = SL::Webdav->new(
1520       type     => $self->type,
1521       number   => $self->order->number,
1522     );
1523     my @all_objects = $webdav->get_all_objects;
1524     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1525                                                     type => t8('File'),
1526                                                     link => File::Spec->catfile($_->full_filedescriptor),
1527                                                 } } @all_objects;
1528   }
1529
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;
1532 }
1533
1534 sub setup_edit_action_bar {
1535   my ($self, %params) = @_;
1536
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);
1540
1541   for my $bar ($::request->layout->get('actionbar')) {
1542     $bar->add(
1543       combobox => [
1544         action => [
1545           t8('Save'),
1546           call      => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
1547                                                     $::instance_conf->get_order_warn_no_deliverydate,
1548                                                                                                       ],
1549           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1550         ],
1551         action => [
1552           t8('Save as new'),
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,
1556         ],
1557       ], # end of combobox "Save"
1558
1559       combobox => [
1560         action => [
1561           t8('Workflow'),
1562         ],
1563         action => [
1564           t8('Sales Order'),
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,
1568         ],
1569         action => [
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,
1574         ],
1575         action => [
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,
1579                                                                                                                         ],
1580           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1581           only_if   => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type()))
1582         ],
1583         action => [
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' ],
1587         ],
1588       ], # end of combobox "Workflow"
1589
1590       combobox => [
1591         action => [
1592           t8('Export'),
1593         ],
1594         action => [
1595           t8('Save and print'),
1596           call => [ 'kivi.Order.show_print_options', $::instance_conf->get_order_warn_duplicate_parts ],
1597         ],
1598         action => [
1599           t8('Save and E-mail'),
1600           call => [ 'kivi.Order.email', $::instance_conf->get_order_warn_duplicate_parts ],
1601         ],
1602         action => [
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,
1607         ],
1608       ], # end of combobox "Export"
1609
1610       action => [
1611         t8('Delete'),
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,
1616       ],
1617     );
1618   }
1619 }
1620
1621 sub generate_pdf {
1622   my ($order, $pdf_ref, $params) = @_;
1623
1624   my @errors = ();
1625
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';
1633
1634   $order->language($params->{language});
1635   $order->flatten_to_form($print_form, format_amounts => 1);
1636
1637   my $template_ext;
1638   my $template_type;
1639   if ($print_form->{format} =~ /(opendocument|oasis)/i) {
1640     $template_ext  = 'odt';
1641     $template_type = 'OpenDocument';
1642   }
1643
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
1651   );
1652
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);
1655   }
1656
1657   return @errors if scalar @errors;
1658
1659   $print_form->throw_on_error(sub {
1660     eval {
1661       $print_form->prepare_for_printing;
1662
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',
1671           notes           => 'html',
1672         },
1673       );
1674       1;
1675     } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
1676   });
1677
1678   return @errors;
1679 }
1680
1681 sub get_files_for_email_dialog {
1682   my ($self) = @_;
1683
1684   my %files = map { ($_ => []) } qw(versions files vc_files part_files);
1685
1686   return %files if !$::instance_conf->get_doc_storage;
1687
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') ];
1692   }
1693
1694   my @parts =
1695     uniq_by { $_->{id} }
1696     map {
1697       +{ id         => $_->part->id,
1698          partnumber => $_->part->partnumber }
1699     } @{$self->order->items_sorted};
1700
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;
1704   }
1705
1706   foreach my $key (keys %files) {
1707     $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
1708   }
1709
1710   return %files;
1711 }
1712
1713 sub make_periodic_invoices_config_from_yaml {
1714   my ($yaml_config) = @_;
1715
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);
1720 }
1721
1722
1723 sub get_periodic_invoices_status {
1724   my ($self, $config) = @_;
1725
1726   return                      if $self->type ne sales_order_type();
1727   return t8('not configured') if !$config;
1728
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";
1732
1733   return $active ? t8('active') : t8('inactive');
1734 }
1735
1736 sub get_title_for {
1737   my ($self, $action) = @_;
1738
1739   return '' if none { lc($action)} qw(add edit);
1740
1741   # for locales:
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");
1750
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")
1756        : '';
1757 }
1758
1759 sub sales_order_type {
1760   'sales_order';
1761 }
1762
1763 sub purchase_order_type {
1764   'purchase_order';
1765 }
1766
1767 sub sales_quotation_type {
1768   'sales_quotation';
1769 }
1770
1771 sub request_quotation_type {
1772   'request_quotation';
1773 }
1774
1775 sub nr_key {
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'
1780        : '';
1781 }
1782
1783 1;
1784
1785 __END__
1786
1787 =encoding utf-8
1788
1789 =head1 NAME
1790
1791 SL::Controller::Order - controller for orders
1792
1793 =head1 SYNOPSIS
1794
1795 This is a new form to enter orders, completely rewritten with the use
1796 of controller and java script techniques.
1797
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
1800 better to maintain.
1801
1802 =head2 Key Features
1803
1804 =over 4
1805
1806 =item *
1807
1808 One input row, so that input happens every time at the same place.
1809
1810 =item *
1811
1812 Use of pickers where possible.
1813
1814 =item *
1815
1816 Possibility to enter more than one item at once.
1817
1818 =item *
1819
1820 Item list in a scrollable area, so that the workflow buttons stay at
1821 the bottom.
1822
1823 =item *
1824
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).
1827
1828 =item *
1829
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>.
1832
1833 =item *
1834
1835 User can see changes immediately, because of the use of java script
1836 and ajax.
1837
1838 =back
1839
1840 =head1 CODE
1841
1842 =head2 Layout
1843
1844 =over 4
1845
1846 =item * C<SL/Controller/Order.pm>
1847
1848 the controller
1849
1850 =item * C<template/webpages/order/form.html>
1851
1852 main form
1853
1854 =item * C<template/webpages/order/tabs/basic_data.html>
1855
1856 Main tab for basic_data.
1857
1858 This is the only tab here for now. "linked records" and "webdav" tabs are
1859 reused from generic code.
1860
1861 =over 4
1862
1863 =item * C<template/webpages/order/tabs/_business_info_row.html>
1864
1865 For displaying information on business type
1866
1867 =item * C<template/webpages/order/tabs/_item_input.html>
1868
1869 The input line for items
1870
1871 =item * C<template/webpages/order/tabs/_row.html>
1872
1873 One row for already entered items
1874
1875 =item * C<template/webpages/order/tabs/_tax_row.html>
1876
1877 Displaying tax information
1878
1879 =item * C<template/webpages/order/tabs/_multi_items_dialog.html>
1880
1881 Dialog for entering more than one item at once
1882
1883 =item * C<template/webpages/order/tabs/_multi_items_result.html>
1884
1885 Results for the filter in the multi items dialog
1886
1887 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
1888
1889 Dialog for selecting price and discount sources
1890
1891 =back
1892
1893 =item * C<js/kivi.Order.js>
1894
1895 java script functions
1896
1897 =back
1898
1899 =head1 TODO
1900
1901 =over 4
1902
1903 =item * testing
1904
1905 =item * currency
1906
1907 =item * credit limit
1908
1909 =item * more workflows (quotation, rfq)
1910
1911 =item * price sources: little symbols showing better price / better discount
1912
1913 =item * select units in input row?
1914
1915 =item * custom shipto address
1916
1917 =item * check for direct delivery (workflow sales order -> purchase order)
1918
1919 =item * language / part translations
1920
1921 =item * access rights
1922
1923 =item * display weights
1924
1925 =item * history
1926
1927 =item * mtime check
1928
1929 =item * optional client/user behaviour
1930
1931 (transactions has to be set - department has to be set -
1932  force project if enabled in client config - transport cost reminder)
1933
1934 =back
1935
1936 =head1 KNOWN BUGS AND CAVEATS
1937
1938 =over 4
1939
1940 =item *
1941
1942 Customer discount is not displayed as a valid discount in price source popup
1943 (this might be a bug in price sources)
1944
1945 (I cannot reproduce this (Bernd))
1946
1947 =item *
1948
1949 No indication that <shift>-up/down expands/collapses second row.
1950
1951 =item *
1952
1953 Inline creation of parts is not currently supported
1954
1955 =item *
1956
1957 Table header is not sticky in the scrolling area.
1958
1959 =item *
1960
1961 Sorting does not include C<position>, neither does reordering.
1962
1963 This behavior was implemented intentionally. But we can discuss, which behavior
1964 should be implemented.
1965
1966 =item *
1967
1968 C<show_multi_items_dialog> does not use the currently inserted string for
1969 filtering.
1970
1971 =item *
1972
1973 The language selected in print or email dialog is not saved when the order is saved.
1974
1975 =back
1976
1977 =head1 To discuss / Nice to have
1978
1979 =over 4
1980
1981 =item *
1982
1983 How to expand/collapse second row. Now it can be done clicking the icon or
1984 <shift>-up/down.
1985
1986 =item *
1987
1988 Possibility to change longdescription in input row?
1989
1990 =item *
1991
1992 Possibility to select PriceSources in input row?
1993
1994 =item *
1995
1996 This controller uses a (changed) copy of the template for the PriceSource
1997 dialog. Maybe there could be used one code source.
1998
1999 =item *
2000
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.
2004
2005 =item *
2006
2007 An indicator, if the actual inputs are saved (like in an
2008 editor or on text processing application).
2009
2010 =item *
2011
2012 A warning when leaving the page without saveing unchanged inputs.
2013
2014
2015 =back
2016
2017 =head1 AUTHOR
2018
2019 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>
2020
2021 =cut