87a9e9cf4f836c36852ce3156b140c5bf26461a3
[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::HTML::Util;
8 use SL::Presenter::Tag qw(select_tag hidden_tag div_tag);
9 use SL::Locale::String qw(t8);
10 use SL::SessionFile::Random;
11 use SL::PriceSource;
12 use SL::Webdav;
13 use SL::File;
14 use SL::MIME;
15 use SL::Util qw(trim);
16 use SL::YAML;
17 use SL::DB::AdditionalBillingAddress;
18 use SL::DB::AuthUser;
19 use SL::DB::History;
20 use SL::DB::Order;
21 use SL::DB::Default;
22 use SL::DB::Unit;
23 use SL::DB::Part;
24 use SL::DB::PartClassification;
25 use SL::DB::PartsGroup;
26 use SL::DB::Printer;
27 use SL::DB::Language;
28 use SL::DB::RecordLink;
29 use SL::DB::RequirementSpec;
30 use SL::DB::Shipto;
31 use SL::DB::Translation;
32
33 use SL::Helper::CreatePDF qw(:all);
34 use SL::Helper::PrintOptions;
35 use SL::Helper::ShippedQty;
36 use SL::Helper::UserPreferences::PositionsScrollbar;
37 use SL::Helper::UserPreferences::UpdatePositions;
38
39 use SL::Controller::Helper::GetModels;
40
41 use List::Util qw(first sum0);
42 use List::UtilsBy qw(sort_by uniq_by);
43 use List::MoreUtils qw(any none pairwise first_index);
44 use English qw(-no_match_vars);
45 use File::Spec;
46 use Cwd;
47 use Sort::Naturally;
48
49 use Rose::Object::MakeMethods::Generic
50 (
51  scalar => [ qw(item_ids_to_delete is_custom_shipto_to_delete) ],
52  'scalar --get_set_init' => [ qw(order valid_types type cv p all_price_factors search_cvpartnumber show_update_button part_picker_classification_ids) ],
53 );
54
55
56 # safety
57 __PACKAGE__->run_before('check_auth');
58
59 __PACKAGE__->run_before('check_auth_save',
60                         except => [ qw(edit show_customer_vendor_details_dialog price_popup load_second_rows) ]);
61
62 __PACKAGE__->run_before('recalc',
63                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice save_and_invoice_for_advance_payment save_and_final_invoice save_and_ap_transaction
64                                      print send_email) ]);
65
66 __PACKAGE__->run_before('get_unalterable_data',
67                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice save_and_invoice_for_advance_payment save_and_final_invoice save_and_ap_transaction
68                                      print send_email) ]);
69
70 #
71 # actions
72 #
73
74 # add a new order
75 sub action_add {
76   my ($self) = @_;
77
78   $self->order->transdate(DateTime->now_local());
79   my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval       :
80                    $self->type eq sales_order_type()     ? $::instance_conf->get_delivery_date_interval : 1;
81
82   if (   ($self->type eq sales_order_type()     &&  $::instance_conf->get_deliverydate_on)
83       || ($self->type eq sales_quotation_type() &&  $::instance_conf->get_reqdate_on)
84       && (!$self->order->reqdate)) {
85     $self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days));
86   }
87
88
89   $self->pre_render();
90   $self->render(
91     'order/form',
92     title => $self->get_title_for('add'),
93     %{$self->{template_args}}
94   );
95 }
96
97 # edit an existing order
98 sub action_edit {
99   my ($self) = @_;
100
101   if ($::form->{id}) {
102     $self->load_order;
103
104   } else {
105     # this is to edit an order from an unsaved order object
106
107     # set item ids to new fake id, to identify them as new items
108     foreach my $item (@{$self->order->items_sorted}) {
109       $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
110     }
111     # trigger rendering values for second row as hidden, because they
112     # are loaded only on demand. So we need to keep the values from
113     # the source.
114     $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
115   }
116
117   $self->recalc();
118   $self->pre_render();
119   $self->render(
120     'order/form',
121     title => $self->get_title_for('edit'),
122     %{$self->{template_args}}
123   );
124 }
125
126 # edit a collective order (consisting of one or more existing orders)
127 sub action_edit_collective {
128   my ($self) = @_;
129
130   # collect order ids
131   my @multi_ids = map {
132     $_ =~ m{^multi_id_(\d+)$} && $::form->{'multi_id_' . $1} && $::form->{'trans_id_' . $1} && $::form->{'trans_id_' . $1}
133   } grep { $_ =~ m{^multi_id_\d+$} } keys %$::form;
134
135   # fall back to add if no ids are given
136   if (scalar @multi_ids == 0) {
137     $self->action_add();
138     return;
139   }
140
141   # fall back to save as new if only one id is given
142   if (scalar @multi_ids == 1) {
143     $self->order(SL::DB::Order->new(id => $multi_ids[0])->load);
144     $self->action_save_as_new();
145     return;
146   }
147
148   # make new order from given orders
149   my @multi_orders = map { SL::DB::Order->new(id => $_)->load } @multi_ids;
150   $self->{converted_from_oe_id} = join ' ', map { $_->id } @multi_orders;
151   $self->order(SL::DB::Order->new_from_multi(\@multi_orders, sort_sources_by => 'transdate'));
152
153   $self->action_edit();
154 }
155
156 # delete the order
157 sub action_delete {
158   my ($self) = @_;
159
160   my $errors = $self->delete();
161
162   if (scalar @{ $errors }) {
163     $self->js->flash('error', $_) foreach @{ $errors };
164     return $self->js->render();
165   }
166
167   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been deleted')
168            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been deleted')
169            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been deleted')
170            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been deleted')
171            : '';
172   flash_later('info', $text);
173
174   my @redirect_params = (
175     action => 'add',
176     type   => $self->type,
177   );
178
179   $self->redirect_to(@redirect_params);
180 }
181
182 # save the order
183 sub action_save {
184   my ($self) = @_;
185
186   my $errors = $self->save();
187
188   if (scalar @{ $errors }) {
189     $self->js->flash('error', $_) foreach @{ $errors };
190     return $self->js->render();
191   }
192
193   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been saved')
194            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been saved')
195            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been saved')
196            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
197            : '';
198   flash_later('info', $text);
199
200   my @redirect_params = (
201     action => 'edit',
202     type   => $self->type,
203     id     => $self->order->id,
204   );
205
206   $self->redirect_to(@redirect_params);
207 }
208
209 # save the order as new document an open it for edit
210 sub action_save_as_new {
211   my ($self) = @_;
212
213   my $order = $self->order;
214
215   if (!$order->id) {
216     $self->js->flash('error', t8('This object has not been saved yet.'));
217     return $self->js->render();
218   }
219
220   # load order from db to check if values changed
221   my $saved_order = SL::DB::Order->new(id => $order->id)->load;
222
223   my %new_attrs;
224   # Lets assign a new number if the user hasn't changed the previous one.
225   # If it has been changed manually then use it as-is.
226   $new_attrs{number}    = (trim($order->number) eq $saved_order->number)
227                         ? ''
228                         : trim($order->number);
229
230   # Clear transdate unless changed
231   $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
232                         ? DateTime->today_local
233                         : $order->transdate;
234
235   # Set new reqdate unless changed if it is enabled in client config
236   if ($order->reqdate == $saved_order->reqdate) {
237     my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval       :
238                      $self->type eq sales_order_type()     ? $::instance_conf->get_delivery_date_interval : 1;
239
240     if (   ($self->type eq sales_order_type()     &&  !$::instance_conf->get_deliverydate_on)
241         || ($self->type eq sales_quotation_type() &&  !$::instance_conf->get_reqdate_on)) {
242       $new_attrs{reqdate} = '';
243     } else {
244       $new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
245     }
246   } else {
247     $new_attrs{reqdate} = $order->reqdate;
248   }
249
250   # Update employee
251   $new_attrs{employee}  = SL::DB::Manager::Employee->current;
252
253   # Create new record from current one
254   $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
255
256   # no linked records on save as new
257   delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
258
259   # save
260   $self->action_save();
261 }
262
263 # print the order
264 #
265 # This is called if "print" is pressed in the print dialog.
266 # If PDF creation was requested and succeeded, the pdf is offered for download
267 # via send_file (which uses ajax in this case).
268 sub action_print {
269   my ($self) = @_;
270
271   my $errors = $self->save();
272
273   if (scalar @{ $errors }) {
274     $self->js->flash('error', $_) foreach @{ $errors };
275     return $self->js->render();
276   }
277
278   $self->js_reset_order_and_item_ids_after_save;
279
280   my $format      = $::form->{print_options}->{format};
281   my $media       = $::form->{print_options}->{media};
282   my $formname    = $::form->{print_options}->{formname};
283   my $copies      = $::form->{print_options}->{copies};
284   my $groupitems  = $::form->{print_options}->{groupitems};
285   my $printer_id  = $::form->{print_options}->{printer_id};
286
287   # only PDF, OpenDocument & HTML for now
288   if (none { $format eq $_ } qw(pdf opendocument opendocument_pdf html)) {
289     return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
290   }
291
292   # only screen or printer by now
293   if (none { $media eq $_ } qw(screen printer)) {
294     return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
295   }
296
297   # create a form for generate_attachment_filename
298   my $form   = Form->new;
299   $form->{$self->nr_key()}  = $self->order->number;
300   $form->{type}             = $self->type;
301   $form->{format}           = $format;
302   $form->{formname}         = $formname;
303   $form->{language}         = '_' . $self->order->language->template_code if $self->order->language;
304   my $doc_filename          = $form->generate_attachment_filename();
305
306   my $doc;
307   my @errors = $self->generate_doc(\$doc, { media      => $media,
308                                             format     => $format,
309                                             formname   => $formname,
310                                             language   => $self->order->language,
311                                             printer_id => $printer_id,
312                                             groupitems => $groupitems });
313   if (scalar @errors) {
314     return $self->js->flash('error', t8('Generating the document failed: #1', $errors[0]))->render;
315   }
316
317   if ($media eq 'screen') {
318     # screen/download
319     $self->js->flash('info', t8('The document has been created.'));
320     $self->send_file(
321       \$doc,
322       type         => SL::MIME->mime_type_from_ext($doc_filename),
323       name         => $doc_filename,
324       js_no_render => 1,
325     );
326
327   } elsif ($media eq 'printer') {
328     # printer
329     my $printer_id = $::form->{print_options}->{printer_id};
330     SL::DB::Printer->new(id => $printer_id)->load->print_document(
331       copies  => $copies,
332       content => $doc,
333     );
334
335     $self->js->flash('info', t8('The document has been printed.'));
336   }
337
338   my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $doc_filename, $formname);
339   if (scalar @warnings) {
340     $self->js->flash('warning', $_) for @warnings;
341   }
342
343   $self->save_history('PRINTED');
344
345   $self->js
346     ->run('kivi.ActionBar.setEnabled', '#save_and_email_action')
347     ->render;
348 }
349 sub action_preview_pdf {
350   my ($self) = @_;
351
352   my $errors = $self->save();
353   if (scalar @{ $errors }) {
354     $self->js->flash('error', $_) foreach @{ $errors };
355     return $self->js->render();
356   }
357
358   $self->js_reset_order_and_item_ids_after_save;
359
360   my $format      = 'pdf';
361   my $media       = 'screen';
362   my $formname    = $self->type;
363
364   # only pdf
365   # create a form for generate_attachment_filename
366   my $form   = Form->new;
367   $form->{$self->nr_key()}  = $self->order->number;
368   $form->{type}             = $self->type;
369   $form->{format}           = $format;
370   $form->{formname}         = $formname;
371   $form->{language}         = '_' . $self->order->language->template_code if $self->order->language;
372   my $pdf_filename          = $form->generate_attachment_filename();
373
374   my $pdf;
375   my @errors = $self->generate_doc(\$pdf, { media      => $media,
376                                             format     => $format,
377                                             formname   => $formname,
378                                             language   => $self->order->language,
379                                           });
380   if (scalar @errors) {
381     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
382   }
383   $self->save_history('PREVIEWED');
384   $self->js->flash('info', t8('The PDF has been previewed'));
385   # screen/download
386   $self->send_file(
387     \$pdf,
388     type         => SL::MIME->mime_type_from_ext($pdf_filename),
389     name         => $pdf_filename,
390     js_no_render => 0,
391   );
392 }
393
394 # open the email dialog
395 sub action_save_and_show_email_dialog {
396   my ($self) = @_;
397
398   my $errors = $self->save();
399
400   if (scalar @{ $errors }) {
401     $self->js->flash('error', $_) foreach @{ $errors };
402     return $self->js->render();
403   }
404
405   my $cv_method = $self->cv;
406
407   if (!$self->order->$cv_method) {
408     return $self->js->flash('error', $self->cv eq 'customer' ? t8('Cannot send E-mail without customer given') : t8('Cannot send E-mail without vendor given'))
409                     ->render($self);
410   }
411
412   my $email_form;
413   $email_form->{to}   = $self->order->contact->cp_email if $self->order->contact;
414   $email_form->{to} ||= $self->order->$cv_method->email;
415   $email_form->{cc}   = $self->order->$cv_method->cc;
416   $email_form->{bcc}  = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
417   # Todo: get addresses from shipto, if any
418
419   my $form = Form->new;
420   $form->{$self->nr_key()}  = $self->order->number;
421   $form->{cusordnumber}     = $self->order->cusordnumber;
422   $form->{formname}         = $self->type;
423   $form->{type}             = $self->type;
424   $form->{language}         = '_' . $self->order->language->template_code if $self->order->language;
425   $form->{language_id}      = $self->order->language->id                  if $self->order->language;
426   $form->{format}           = 'pdf';
427   $form->{cp_id}            = $self->order->contact->cp_id if $self->order->contact;
428
429   $email_form->{subject}             = $form->generate_email_subject();
430   $email_form->{attachment_filename} = $form->generate_attachment_filename();
431   $email_form->{message}             = $form->generate_email_body();
432   $email_form->{js_send_function}    = 'kivi.Order.send_email()';
433
434   my %files = $self->get_files_for_email_dialog();
435
436   my @employees_with_email = grep {
437     my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
438     $user && !!trim($user->get_config_value('email'));
439   } @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
440
441   my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
442                                   email_form    => $email_form,
443                                   show_bcc      => $::auth->assert('email_bcc', 'may fail'),
444                                   FILES         => \%files,
445                                   is_customer   => $self->cv eq 'customer',
446                                   ALL_EMPLOYEES => \@employees_with_email,
447   );
448
449   $self->js
450       ->run('kivi.Order.show_email_dialog', $dialog_html)
451       ->reinit_widgets
452       ->render($self);
453 }
454
455 # send email
456 #
457 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
458 sub action_send_email {
459   my ($self) = @_;
460
461   my $errors = $self->save();
462
463   if (scalar @{ $errors }) {
464     $self->js->run('kivi.Order.close_email_dialog');
465     $self->js->flash('error', $_) foreach @{ $errors };
466     return $self->js->render();
467   }
468
469   $self->js_reset_order_and_item_ids_after_save;
470
471   my $email_form  = delete $::form->{email_form};
472   my %field_names = (to => 'email');
473
474   $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
475
476   # for Form::cleanup which may be called in Form::send_email
477   $::form->{cwd}    = getcwd();
478   $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
479
480   $::form->{$_}     = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
481   $::form->{media}  = 'email';
482
483   $::form->{attachment_policy} //= '';
484
485   # Is an old file version available?
486   my $attfile;
487   if ($::form->{attachment_policy} eq 'old_file') {
488     $attfile = SL::File->get_all(object_id     => $self->order->id,
489                                  object_type   => $self->type,
490                                  file_type     => 'document',
491                                  print_variant => $::form->{formname});
492   }
493
494   if ($::form->{attachment_policy} ne 'no_file' && !($::form->{attachment_policy} eq 'old_file' && $attfile)) {
495     my $doc;
496     my @errors = $self->generate_doc(\$doc, {media      => $::form->{media},
497                                              format     => $::form->{print_options}->{format},
498                                              formname   => $::form->{print_options}->{formname},
499                                              language   => $self->order->language,
500                                              printer_id => $::form->{print_options}->{printer_id},
501                                              groupitems => $::form->{print_options}->{groupitems}});
502     if (scalar @errors) {
503       return $self->js->flash('error', t8('Generating the document failed: #1', $errors[0]))->render($self);
504     }
505
506     my @warnings = $self->store_doc_to_webdav_and_filemanagement($doc, $::form->{attachment_filename}, $::form->{formname});
507     if (scalar @warnings) {
508       flash_later('warning', $_) for @warnings;
509     }
510
511     my $sfile = SL::SessionFile::Random->new(mode => "w");
512     $sfile->fh->print($doc);
513     $sfile->fh->close;
514
515     $::form->{tmpfile} = $sfile->file_name;
516     $::form->{tmpdir}  = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
517   }
518
519   $::form->{id} = $self->order->id; # this is used in SL::Mailer to create a linked record to the mail
520   $::form->send_email(\%::myconfig, $::form->{print_options}->{format});
521
522   # internal notes
523   my $intnotes = $self->order->intnotes;
524   $intnotes   .= "\n\n" if $self->order->intnotes;
525   $intnotes   .= t8('[email]')                                                                                        . "\n";
526   $intnotes   .= t8('Date')       . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
527   $intnotes   .= t8('To (email)') . ": " . $::form->{email}                                                           . "\n";
528   $intnotes   .= t8('Cc')         . ": " . $::form->{cc}                                                              . "\n"    if $::form->{cc};
529   $intnotes   .= t8('Bcc')        . ": " . $::form->{bcc}                                                             . "\n"    if $::form->{bcc};
530   $intnotes   .= t8('Subject')    . ": " . $::form->{subject}                                                         . "\n\n";
531   $intnotes   .= t8('Message')    . ": " . SL::HTML::Util->strip($::form->{message});
532
533   $self->order->update_attributes(intnotes => $intnotes);
534
535   $self->save_history('MAILED');
536
537   flash_later('info', t8('The email has been sent.'));
538
539   my @redirect_params = (
540     action => 'edit',
541     type   => $self->type,
542     id     => $self->order->id,
543   );
544
545   $self->redirect_to(@redirect_params);
546 }
547
548 # open the periodic invoices config dialog
549 #
550 # If there are values in the form (i.e. dialog was opened before),
551 # then use this values. Create new ones, else.
552 sub action_show_periodic_invoices_config_dialog {
553   my ($self) = @_;
554
555   my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
556   $config  ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
557   $config  ||= SL::DB::PeriodicInvoicesConfig->new(periodicity             => 'm',
558                                                    order_value_periodicity => 'p', # = same as periodicity
559                                                    start_date_as_date      => $::form->{transdate_as_date} || $::form->current_date,
560                                                    extend_automatically_by => 12,
561                                                    active                  => 1,
562                                                    email_subject           => GenericTranslations->get(
563                                                                                 language_id      => $::form->{language_id},
564                                                                                 translation_type =>"preset_text_periodic_invoices_email_subject"),
565                                                    email_body              => GenericTranslations->get(
566                                                                                 language_id      => $::form->{language_id},
567                                                                                 translation_type => "salutation_general")
568                                                                             . GenericTranslations->get(
569                                                                                 language_id      => $::form->{language_id},
570                                                                                 translation_type => "salutation_punctuation_mark") . "\n\n"
571                                                                             . GenericTranslations->get(
572                                                                                 language_id      => $::form->{language_id},
573                                                                                 translation_type =>"preset_text_periodic_invoices_email_body"),
574   );
575   # for older configs, replace email preset text if not yet set.
576   $config->email_subject(GenericTranslations->get(
577                                               language_id      => $::form->{language_id},
578                                               translation_type =>"preset_text_periodic_invoices_email_subject")
579                         ) unless $config->email_subject;
580
581   $config->email_body(GenericTranslations->get(
582                                               language_id      => $::form->{language_id},
583                                               translation_type => "salutation_general")
584                     . GenericTranslations->get(
585                                               language_id      => $::form->{language_id},
586                                               translation_type => "salutation_punctuation_mark") . "\n\n"
587                     . GenericTranslations->get(
588                                               language_id      => $::form->{language_id},
589                                               translation_type =>"preset_text_periodic_invoices_email_body")
590                      ) unless $config->email_body;
591
592   $config->periodicity('m')             if none { $_ eq $config->periodicity             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
593   $config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
594
595   $::form->get_lists(printers => "ALL_PRINTERS",
596                      charts   => { key       => 'ALL_CHARTS',
597                                    transdate => 'current_date' });
598
599   $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
600
601   if ($::form->{customer_id}) {
602     $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
603     my $customer_object = SL::DB::Manager::Customer->find_by(id => $::form->{customer_id});
604     $::form->{postal_invoice}                  = $customer_object->postal_invoice;
605     $::form->{email_recipient_invoice_address} = $::form->{postal_invoice} ? '' : $customer_object->invoice_mail;
606     $config->send_email(0) if $::form->{postal_invoice};
607   }
608
609   $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
610                 popup_dialog             => 1,
611                 popup_js_close_function  => 'kivi.Order.close_periodic_invoices_config_dialog()',
612                 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
613                 config                   => $config,
614                 %$::form);
615 }
616
617 # assign the values of the periodic invoices config dialog
618 # as yaml in the hidden tag and set the status.
619 sub action_assign_periodic_invoices_config {
620   my ($self) = @_;
621
622   $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
623
624   my $config = { active                     => $::form->{active}       ? 1 : 0,
625                  terminated                 => $::form->{terminated}   ? 1 : 0,
626                  direct_debit               => $::form->{direct_debit} ? 1 : 0,
627                  periodicity                => (any { $_ eq $::form->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES)              ? $::form->{periodicity}             : 'm',
628                  order_value_periodicity    => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
629                  start_date_as_date         => $::form->{start_date_as_date},
630                  end_date_as_date           => $::form->{end_date_as_date},
631                  first_billing_date_as_date => $::form->{first_billing_date_as_date},
632                  print                      => $::form->{print}      ? 1                         : 0,
633                  printer_id                 => $::form->{print}      ? $::form->{printer_id} * 1 : undef,
634                  copies                     => $::form->{copies} * 1 ? $::form->{copies}         : 1,
635                  extend_automatically_by    => $::form->{extend_automatically_by}    * 1 || undef,
636                  ar_chart_id                => $::form->{ar_chart_id} * 1,
637                  send_email                 => $::form->{send_email} ? 1 : 0,
638                  email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
639                  email_recipient_address    => $::form->{email_recipient_address},
640                  email_sender               => $::form->{email_sender},
641                  email_subject              => $::form->{email_subject},
642                  email_body                 => $::form->{email_body},
643                };
644
645   my $periodic_invoices_config = SL::YAML::Dump($config);
646
647   my $status = $self->get_periodic_invoices_status($config);
648
649   $self->js
650     ->remove('#order_periodic_invoices_config')
651     ->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
652     ->run('kivi.Order.close_periodic_invoices_config_dialog')
653     ->html('#periodic_invoices_status', $status)
654     ->flash('info', t8('The periodic invoices config has been assigned.'))
655     ->render($self);
656 }
657
658 sub action_get_has_active_periodic_invoices {
659   my ($self) = @_;
660
661   my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
662   $config  ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
663
664   my $has_active_periodic_invoices =
665        $self->type eq sales_order_type()
666     && $config
667     && $config->active
668     && (!$config->end_date || ($config->end_date > DateTime->today_local))
669     && $config->get_previous_billed_period_start_date;
670
671   $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
672 }
673
674 # save the order and redirect to the frontend subroutine for a new
675 # delivery order
676 sub action_save_and_delivery_order {
677   my ($self) = @_;
678
679   $self->save_and_redirect_to(
680     controller => 'oe.pl',
681     action     => 'oe_delivery_order_from_order',
682   );
683 }
684
685 sub action_save_and_supplier_delivery_order {
686   my ($self) = @_;
687
688   $self->save_and_redirect_to(
689     controller => 'controller.pl',
690     action     => 'DeliveryOrder/add_from_order',
691     type       => 'supplier_delivery_order',
692   );
693 }
694
695 # save the order and redirect to the frontend subroutine for a new
696 # invoice
697 sub action_save_and_invoice {
698   my ($self) = @_;
699
700   $self->save_and_redirect_to(
701     controller => 'oe.pl',
702     action     => 'oe_invoice_from_order',
703   );
704 }
705
706 sub action_save_and_invoice_for_advance_payment {
707   my ($self) = @_;
708
709   $self->save_and_redirect_to(
710     controller       => 'oe.pl',
711     action           => 'oe_invoice_from_order',
712     new_invoice_type => 'invoice_for_advance_payment',
713   );
714 }
715
716 sub action_save_and_final_invoice {
717   my ($self) = @_;
718
719   $self->save_and_redirect_to(
720     controller       => 'oe.pl',
721     action           => 'oe_invoice_from_order',
722     new_invoice_type => 'final_invoice',
723   );
724 }
725
726 # workflow from sales order to sales quotation
727 sub action_sales_quotation {
728   $_[0]->workflow_sales_or_request_for_quotation();
729 }
730
731 # workflow from sales order to sales quotation
732 sub action_request_for_quotation {
733   $_[0]->workflow_sales_or_request_for_quotation();
734 }
735
736 # workflow from sales quotation to sales order
737 sub action_sales_order {
738   $_[0]->workflow_sales_or_purchase_order();
739 }
740
741 # workflow from rfq to purchase order
742 sub action_purchase_order {
743   $_[0]->workflow_sales_or_purchase_order();
744 }
745
746 # workflow from purchase order to ap transaction
747 sub action_save_and_ap_transaction {
748   my ($self) = @_;
749
750   $self->save_and_redirect_to(
751     controller => 'ap.pl',
752     action     => 'add_from_purchase_order',
753   );
754 }
755
756 # set form elements in respect to a changed customer or vendor
757 #
758 # This action is called on an change of the customer/vendor picker.
759 sub action_customer_vendor_changed {
760   my ($self) = @_;
761
762   setup_order_from_cv($self->order);
763   $self->recalc();
764
765   my $cv_method = $self->cv;
766
767   if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
768     $self->js->show('#cp_row');
769   } else {
770     $self->js->hide('#cp_row');
771   }
772
773   if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
774     $self->js->show('#shipto_selection');
775   } else {
776     $self->js->hide('#shipto_selection');
777   }
778
779   if ($cv_method eq 'customer') {
780     my $show_hide = scalar @{ $self->order->customer->additional_billing_addresses } > 0 ? 'show' : 'hide';
781     $self->js->$show_hide('#billing_address_row');
782   }
783
784   $self->js->val( '#order_salesman_id',      $self->order->salesman_id)        if $self->order->is_sales;
785
786   $self->js
787     ->replaceWith('#order_cp_id',              $self->build_contact_select)
788     ->replaceWith('#order_shipto_id',          $self->build_shipto_select)
789     ->replaceWith('#shipto_inputs  ',          $self->build_shipto_inputs)
790     ->replaceWith('#order_billing_address_id', $self->build_billing_address_select)
791     ->replaceWith('#business_info_row',        $self->build_business_info_row)
792     ->val(        '#order_taxzone_id',         $self->order->taxzone_id)
793     ->val(        '#order_taxincluded',        $self->order->taxincluded)
794     ->val(        '#order_currency_id',        $self->order->currency_id)
795     ->val(        '#order_payment_id',         $self->order->payment_id)
796     ->val(        '#order_delivery_term_id',   $self->order->delivery_term_id)
797     ->val(        '#order_intnotes',           $self->order->intnotes)
798     ->val(        '#order_language_id',        $self->order->$cv_method->language_id)
799     ->focus(      '#order_' . $self->cv . '_id')
800     ->run('kivi.Order.update_exchangerate');
801
802   $self->js_redisplay_amounts_and_taxes;
803   $self->js_redisplay_cvpartnumbers;
804   $self->js->render();
805 }
806
807 # open the dialog for customer/vendor details
808 sub action_show_customer_vendor_details_dialog {
809   my ($self) = @_;
810
811   my $is_customer = 'customer' eq $::form->{vc};
812   my $cv;
813   if ($is_customer) {
814     $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
815   } else {
816     $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
817   }
818
819   my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
820   $details{discount_as_percent} = $cv->discount_as_percent;
821   $details{creditlimt}          = $cv->creditlimit_as_number;
822   $details{business}            = $cv->business->description      if $cv->business;
823   $details{language}            = $cv->language_obj->description  if $cv->language_obj;
824   $details{delivery_terms}      = $cv->delivery_term->description if $cv->delivery_term;
825   $details{payment_terms}       = $cv->payment->description       if $cv->payment;
826   $details{pricegroup}          = $cv->pricegroup->pricegroup     if $is_customer && $cv->pricegroup;
827
828   if ($is_customer) {
829     foreach my $entry (@{ $cv->additional_billing_addresses }) {
830       push @{ $details{ADDITIONAL_BILLING_ADDRESSES} },   { map { $_ => $entry->$_ } @{$entry->meta->columns} };
831     }
832   }
833   foreach my $entry (@{ $cv->shipto }) {
834     push @{ $details{SHIPTO} },   { map { $_ => $entry->$_ } @{$entry->meta->columns} };
835   }
836   foreach my $entry (@{ $cv->contacts }) {
837     push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
838   }
839
840   $_[0]->render('common/show_vc_details', { layout => 0 },
841                 is_customer => $is_customer,
842                 %details);
843
844 }
845
846 # called if a unit in an existing item row is changed
847 sub action_unit_changed {
848   my ($self) = @_;
849
850   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
851   my $item = $self->order->items_sorted->[$idx];
852
853   my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
854   $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
855
856   $self->recalc();
857
858   $self->js
859     ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
860   $self->js_redisplay_line_values;
861   $self->js_redisplay_amounts_and_taxes;
862   $self->js->render();
863 }
864
865 # add an item row for a new item entered in the input row
866 sub action_add_item {
867   my ($self) = @_;
868
869   delete $::form->{add_item}->{create_part_type};
870
871   my $form_attr = $::form->{add_item};
872
873   return unless $form_attr->{parts_id};
874
875   my $item = new_item($self->order, $form_attr);
876
877   $self->order->add_items($item);
878
879   $self->recalc();
880
881   $self->get_item_cvpartnumber($item);
882
883   my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
884   my $row_as_html = $self->p->render('order/tabs/_row',
885                                      ITEM => $item,
886                                      ID   => $item_id,
887                                      SELF => $self,
888   );
889
890   if ($::form->{insert_before_item_id}) {
891     $self->js
892       ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
893   } else {
894     $self->js
895       ->append('#row_table_id', $row_as_html);
896   }
897
898   if ( $item->part->is_assortment ) {
899     $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
900     foreach my $assortment_item ( @{$item->part->assortment_items} ) {
901       my $attr = { parts_id => $assortment_item->parts_id,
902                    qty      => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
903                    unit     => $assortment_item->unit,
904                    description => $assortment_item->part->description,
905                  };
906       my $item = new_item($self->order, $attr);
907
908       # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
909       $item->discount(1) unless $assortment_item->charge;
910
911       $self->order->add_items( $item );
912       $self->recalc();
913       $self->get_item_cvpartnumber($item);
914       my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
915       my $row_as_html = $self->p->render('order/tabs/_row',
916                                          ITEM => $item,
917                                          ID   => $item_id,
918                                          SELF => $self,
919       );
920       if ($::form->{insert_before_item_id}) {
921         $self->js
922           ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
923       } else {
924         $self->js
925           ->append('#row_table_id', $row_as_html);
926       }
927     };
928   };
929
930   $self->js
931     ->val('.add_item_input', '')
932     ->run('kivi.Order.init_row_handlers')
933     ->run('kivi.Order.renumber_positions')
934     ->focus('#add_item_parts_id_name');
935
936   $self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};
937
938   $self->js_redisplay_amounts_and_taxes;
939   $self->js->render();
940 }
941
942 # add item rows for multiple items at once
943 sub action_add_multi_items {
944   my ($self) = @_;
945
946   my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_items} };
947   return $self->js->render() unless scalar @form_attr;
948
949   my @items;
950   foreach my $attr (@form_attr) {
951     my $item = new_item($self->order, $attr);
952     push @items, $item;
953     if ( $item->part->is_assortment ) {
954       foreach my $assortment_item ( @{$item->part->assortment_items} ) {
955         my $attr = { parts_id => $assortment_item->parts_id,
956                      qty      => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
957                      unit     => $assortment_item->unit,
958                      description => $assortment_item->part->description,
959                    };
960         my $item = new_item($self->order, $attr);
961
962         # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
963         $item->discount(1) unless $assortment_item->charge;
964         push @items, $item;
965       }
966     }
967   }
968   $self->order->add_items(@items);
969
970   $self->recalc();
971
972   foreach my $item (@items) {
973     $self->get_item_cvpartnumber($item);
974     my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
975     my $row_as_html = $self->p->render('order/tabs/_row',
976                                        ITEM => $item,
977                                        ID   => $item_id,
978                                        SELF => $self,
979     );
980
981     if ($::form->{insert_before_item_id}) {
982       $self->js
983         ->before ('.row_entry:has(#item_' . $::form->{insert_before_item_id} . ')', $row_as_html);
984     } else {
985       $self->js
986         ->append('#row_table_id', $row_as_html);
987     }
988   }
989
990   $self->js
991     ->run('kivi.Part.close_picker_dialogs')
992     ->run('kivi.Order.init_row_handlers')
993     ->run('kivi.Order.renumber_positions')
994     ->focus('#add_item_parts_id_name');
995
996   $self->js->run('kivi.Order.row_table_scroll_down') if !$::form->{insert_before_item_id};
997
998   $self->js_redisplay_amounts_and_taxes;
999   $self->js->render();
1000 }
1001
1002 # recalculate all linetotals, amounts and taxes and redisplay them
1003 sub action_recalc_amounts_and_taxes {
1004   my ($self) = @_;
1005
1006   $self->recalc();
1007
1008   $self->js_redisplay_line_values;
1009   $self->js_redisplay_amounts_and_taxes;
1010   $self->js->render();
1011 }
1012
1013 sub action_update_exchangerate {
1014   my ($self) = @_;
1015
1016   my $data = {
1017     is_standard   => $self->order->currency_id == $::instance_conf->get_currency_id,
1018     currency_name => $self->order->currency->name,
1019     exchangerate  => $self->order->daily_exchangerate_as_null_number,
1020   };
1021
1022   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
1023 }
1024
1025 # redisplay item rows if they are sorted by an attribute
1026 sub action_reorder_items {
1027   my ($self) = @_;
1028
1029   my %sort_keys = (
1030     partnumber   => sub { $_[0]->part->partnumber },
1031     description  => sub { $_[0]->description },
1032     qty          => sub { $_[0]->qty },
1033     sellprice    => sub { $_[0]->sellprice },
1034     discount     => sub { $_[0]->discount },
1035     cvpartnumber => sub { $_[0]->{cvpartnumber} },
1036   );
1037
1038   $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
1039
1040   my $method = $sort_keys{$::form->{order_by}};
1041   my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
1042   if ($::form->{sort_dir}) {
1043     if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
1044       @to_sort = sort { $a->{order_by} <=> $b->{order_by} } @to_sort;
1045     } else {
1046       @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
1047     }
1048   } else {
1049     if ( $::form->{order_by} =~ m/qty|sellprice|discount/ ){
1050       @to_sort = sort { $b->{order_by} <=> $a->{order_by} } @to_sort;
1051     } else {
1052       @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
1053     }
1054   }
1055   $self->js
1056     ->run('kivi.Order.redisplay_items', \@to_sort)
1057     ->render;
1058 }
1059
1060 # show the popup to choose a price/discount source
1061 sub action_price_popup {
1062   my ($self) = @_;
1063
1064   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
1065   my $item = $self->order->items_sorted->[$idx];
1066
1067   $self->render_price_dialog($item);
1068 }
1069
1070 # save the order in a session variable and redirect to the part controller
1071 sub action_create_part {
1072   my ($self) = @_;
1073
1074   my $previousform = $::auth->save_form_in_session(non_scalars => 1);
1075
1076   my $callback     = $self->url_for(
1077     action       => 'return_from_create_part',
1078     type         => $self->type, # type is needed for check_auth on return
1079     previousform => $previousform,
1080   );
1081
1082   flash_later('info', t8('You are adding a new part while you are editing another document. You will be redirected to your document when saving the new part or aborting this form.'));
1083
1084   my @redirect_params = (
1085     controller => 'Part',
1086     action     => 'add',
1087     part_type  => $::form->{add_item}->{create_part_type},
1088     callback   => $callback,
1089     show_abort => 1,
1090   );
1091
1092   $self->redirect_to(@redirect_params);
1093 }
1094
1095 sub action_return_from_create_part {
1096   my ($self) = @_;
1097
1098   $self->{created_part} = SL::DB::Part->new(id => delete $::form->{new_parts_id})->load if $::form->{new_parts_id};
1099
1100   $::auth->restore_form_from_session(delete $::form->{previousform});
1101
1102   # set item ids to new fake id, to identify them as new items
1103   foreach my $item (@{$self->order->items_sorted}) {
1104     $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1105   }
1106
1107   $self->recalc();
1108   $self->get_unalterable_data();
1109   $self->pre_render();
1110
1111   # trigger rendering values for second row/longdescription as hidden,
1112   # because they are loaded only on demand. So we need to keep the values
1113   # from the source.
1114   $_->{render_second_row}      = 1 for @{ $self->order->items_sorted };
1115   $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1116
1117   $self->render(
1118     'order/form',
1119     title => $self->get_title_for('edit'),
1120     %{$self->{template_args}}
1121   );
1122
1123 }
1124
1125 # load the second row for one or more items
1126 #
1127 # This action gets the html code for all items second rows by rendering a template for
1128 # the second row and sets the html code via client js.
1129 sub action_load_second_rows {
1130   my ($self) = @_;
1131
1132   $self->recalc() if $self->order->is_sales; # for margin calculation
1133
1134   foreach my $item_id (@{ $::form->{item_ids} }) {
1135     my $idx  = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
1136     my $item = $self->order->items_sorted->[$idx];
1137
1138     $self->js_load_second_row($item, $item_id, 0);
1139   }
1140
1141   $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
1142
1143   $self->js->render();
1144 }
1145
1146 # update description, notes and sellprice from master data
1147 sub action_update_row_from_master_data {
1148   my ($self) = @_;
1149
1150   foreach my $item_id (@{ $::form->{item_ids} }) {
1151     my $idx   = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
1152     my $item  = $self->order->items_sorted->[$idx];
1153     my $texts = get_part_texts($item->part, $self->order->language_id);
1154
1155     $item->description($texts->{description});
1156     $item->longdescription($texts->{longdescription});
1157
1158     my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1159
1160     my $price_src;
1161     if ($item->part->is_assortment) {
1162     # add assortment items with price 0, as the components carry the price
1163       $price_src = $price_source->price_from_source("");
1164       $price_src->price(0);
1165     } else {
1166       $price_src = $price_source->best_price
1167                  ? $price_source->best_price
1168                  : $price_source->price_from_source("");
1169       $price_src->price($::form->round_amount($price_src->price / $self->order->exchangerate, 5)) if $self->order->exchangerate;
1170       $price_src->price(0) if !$price_source->best_price;
1171     }
1172
1173
1174     $item->sellprice($price_src->price);
1175     $item->active_price_source($price_src);
1176
1177     $self->js
1178       ->run('kivi.Order.update_sellprice', $item_id, $item->sellprice_as_number)
1179       ->html('.row_entry:has(#item_' . $item_id . ') [name = "partnumber"] a', $item->part->partnumber)
1180       ->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].description"]', $item->description)
1181       ->val ('.row_entry:has(#item_' . $item_id . ') [name = "order.orderitems[].longdescription"]', $item->longdescription);
1182
1183     if ($self->search_cvpartnumber) {
1184       $self->get_item_cvpartnumber($item);
1185       $self->js->html('.row_entry:has(#item_' . $item_id . ') [name = "cvpartnumber"]', $item->{cvpartnumber});
1186     }
1187   }
1188
1189   $self->recalc();
1190   $self->js_redisplay_line_values;
1191   $self->js_redisplay_amounts_and_taxes;
1192
1193   $self->js->render();
1194 }
1195
1196 sub js_load_second_row {
1197   my ($self, $item, $item_id, $do_parse) = @_;
1198
1199   if ($do_parse) {
1200     # Parse values from form (they are formated while rendering (template)).
1201     # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1202     # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
1203     foreach my $var (@{ $item->cvars_by_config }) {
1204       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1205     }
1206     $item->parse_custom_variable_values;
1207   }
1208
1209   my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);
1210
1211   $self->js
1212     ->html('#second_row_' . $item_id, $row_as_html)
1213     ->data('#second_row_' . $item_id, 'loaded', 1);
1214 }
1215
1216 sub js_redisplay_line_values {
1217   my ($self) = @_;
1218
1219   my $is_sales = $self->order->is_sales;
1220
1221   # sales orders with margins
1222   my @data;
1223   if ($is_sales) {
1224     @data = map {
1225       [
1226        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
1227        $::form->format_amount(\%::myconfig, $_->{marge_total},   2, 0),
1228        $::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
1229       ]} @{ $self->order->items_sorted };
1230   } else {
1231     @data = map {
1232       [
1233        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
1234       ]} @{ $self->order->items_sorted };
1235   }
1236
1237   $self->js
1238     ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
1239 }
1240
1241 sub js_redisplay_amounts_and_taxes {
1242   my ($self) = @_;
1243
1244   if (scalar @{ $self->{taxes} }) {
1245     $self->js->show('#taxincluded_row_id');
1246   } else {
1247     $self->js->hide('#taxincluded_row_id');
1248   }
1249
1250   if ($self->order->taxincluded) {
1251     $self->js->hide('#subtotal_row_id');
1252   } else {
1253     $self->js->show('#subtotal_row_id');
1254   }
1255
1256   if ($self->order->is_sales) {
1257     my $is_neg = $self->order->marge_total < 0;
1258     $self->js
1259       ->html('#marge_total_id',   $::form->format_amount(\%::myconfig, $self->order->marge_total,   2))
1260       ->html('#marge_percent_id', $::form->format_amount(\%::myconfig, $self->order->marge_percent, 2))
1261       ->action_if( $is_neg, 'addClass',    '#marge_total_id',        'plus0')
1262       ->action_if( $is_neg, 'addClass',    '#marge_percent_id',      'plus0')
1263       ->action_if( $is_neg, 'addClass',    '#marge_percent_sign_id', 'plus0')
1264       ->action_if(!$is_neg, 'removeClass', '#marge_total_id',        'plus0')
1265       ->action_if(!$is_neg, 'removeClass', '#marge_percent_id',      'plus0')
1266       ->action_if(!$is_neg, 'removeClass', '#marge_percent_sign_id', 'plus0');
1267   }
1268
1269   $self->js
1270     ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
1271     ->html('#amount_id',    $::form->format_amount(\%::myconfig, $self->order->amount,    -2))
1272     ->remove('.tax_row')
1273     ->insertBefore($self->build_tax_rows, '#amount_row_id');
1274 }
1275
1276 sub js_redisplay_cvpartnumbers {
1277   my ($self) = @_;
1278
1279   $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
1280
1281   my @data = map {[$_->{cvpartnumber}]} @{ $self->order->items_sorted };
1282
1283   $self->js
1284     ->run('kivi.Order.redisplay_cvpartnumbers', \@data);
1285 }
1286
1287 sub js_reset_order_and_item_ids_after_save {
1288   my ($self) = @_;
1289
1290   $self->js
1291     ->val('#id', $self->order->id)
1292     ->val('#converted_from_oe_id', '')
1293     ->val('#order_' . $self->nr_key(), $self->order->number);
1294
1295   my $idx = 0;
1296   foreach my $form_item_id (@{ $::form->{orderitem_ids} }) {
1297     next if !$self->order->items_sorted->[$idx]->id;
1298     next if $form_item_id !~ m{^new};
1299     $self->js
1300       ->val ('[name="orderitem_ids[+]"][value="' . $form_item_id . '"]', $self->order->items_sorted->[$idx]->id)
1301       ->val ('#item_' . $form_item_id, $self->order->items_sorted->[$idx]->id)
1302       ->attr('#item_' . $form_item_id, "id", 'item_' . $self->order->items_sorted->[$idx]->id);
1303   } continue {
1304     $idx++;
1305   }
1306   $self->js->val('[name="converted_from_orderitems_ids[+]"]', '');
1307 }
1308
1309 #
1310 # helpers
1311 #
1312
1313 sub init_valid_types {
1314   [ sales_order_type(), purchase_order_type(), sales_quotation_type(), request_quotation_type() ];
1315 }
1316
1317 sub init_type {
1318   my ($self) = @_;
1319
1320   if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
1321     die "Not a valid type for order";
1322   }
1323
1324   $self->type($::form->{type});
1325 }
1326
1327 sub init_cv {
1328   my ($self) = @_;
1329
1330   my $cv = (any { $self->type eq $_ } (sales_order_type(),    sales_quotation_type()))   ? 'customer'
1331          : (any { $self->type eq $_ } (purchase_order_type(), request_quotation_type())) ? 'vendor'
1332          : die "Not a valid type for order";
1333
1334   return $cv;
1335 }
1336
1337 sub init_search_cvpartnumber {
1338   my ($self) = @_;
1339
1340   my $user_prefs = SL::Helper::UserPreferences::PartPickerSearch->new();
1341   my $search_cvpartnumber;
1342   $search_cvpartnumber = !!$user_prefs->get_sales_search_customer_partnumber() if $self->cv eq 'customer';
1343   $search_cvpartnumber = !!$user_prefs->get_purchase_search_makemodel()        if $self->cv eq 'vendor';
1344
1345   return $search_cvpartnumber;
1346 }
1347
1348 sub init_show_update_button {
1349   my ($self) = @_;
1350
1351   !!SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
1352 }
1353
1354 sub init_p {
1355   SL::Presenter->get;
1356 }
1357
1358 sub init_order {
1359   $_[0]->make_order;
1360 }
1361
1362 sub init_all_price_factors {
1363   SL::DB::Manager::PriceFactor->get_all;
1364 }
1365
1366 sub init_part_picker_classification_ids {
1367   my ($self)    = @_;
1368   my $attribute = 'used_for_' . ($self->type =~ m{sales} ? 'sale' : 'purchase');
1369
1370   return [ map { $_->id } @{ SL::DB::Manager::PartClassification->get_all(where => [ $attribute => 1 ]) } ];
1371 }
1372
1373 sub check_auth {
1374   my ($self) = @_;
1375
1376   my $right_for = { map { $_ => $_.'_edit' . ' | ' . $_.'_view' } @{$self->valid_types} };
1377
1378   my $right   = $right_for->{ $self->type };
1379   $right    ||= 'DOES_NOT_EXIST';
1380
1381   $::auth->assert($right);
1382 }
1383
1384 sub check_auth_save {
1385   my ($self) = @_;
1386
1387   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
1388
1389   my $right   = $right_for->{ $self->type };
1390   $right    ||= 'DOES_NOT_EXIST';
1391
1392   $::auth->assert($right);
1393 }
1394
1395 # build the selection box for contacts
1396 #
1397 # Needed, if customer/vendor changed.
1398 sub build_contact_select {
1399   my ($self) = @_;
1400
1401   select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
1402     value_key  => 'cp_id',
1403     title_key  => 'full_name_dep',
1404     default    => $self->order->cp_id,
1405     with_empty => 1,
1406     style      => 'width: 300px',
1407   );
1408 }
1409
1410 # build the selection box for the additional billing address
1411 #
1412 # Needed, if customer/vendor changed.
1413 sub build_billing_address_select {
1414   my ($self) = @_;
1415
1416   return '' if $self->cv ne 'customer';
1417
1418   select_tag('order.billing_address_id',
1419              [ {displayable_id => '', id => ''}, $self->order->{$self->cv}->additional_billing_addresses ],
1420              value_key  => 'id',
1421              title_key  => 'displayable_id',
1422              default    => $self->order->billing_address_id,
1423              with_empty => 0,
1424              style      => 'width: 300px',
1425   );
1426 }
1427
1428 # build the selection box for shiptos
1429 #
1430 # Needed, if customer/vendor changed.
1431 sub build_shipto_select {
1432   my ($self) = @_;
1433
1434   select_tag('order.shipto_id',
1435              [ {displayable_id => t8("No/individual shipping address"), shipto_id => ''}, $self->order->{$self->cv}->shipto ],
1436              value_key  => 'shipto_id',
1437              title_key  => 'displayable_id',
1438              default    => $self->order->shipto_id,
1439              with_empty => 0,
1440              style      => 'width: 300px',
1441   );
1442 }
1443
1444 # build the inputs for the cusom shipto dialog
1445 #
1446 # Needed, if customer/vendor changed.
1447 sub build_shipto_inputs {
1448   my ($self) = @_;
1449
1450   my $content = $self->p->render('common/_ship_to_dialog',
1451                                  vc_obj      => $self->order->customervendor,
1452                                  cs_obj      => $self->order->custom_shipto,
1453                                  cvars       => $self->order->custom_shipto->cvars_by_config,
1454                                  id_selector => '#order_shipto_id');
1455
1456   div_tag($content, id => 'shipto_inputs');
1457 }
1458
1459 # render the info line for business
1460 #
1461 # Needed, if customer/vendor changed.
1462 sub build_business_info_row
1463 {
1464   $_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
1465 }
1466
1467 # build the rows for displaying taxes
1468 #
1469 # Called if amounts where recalculated and redisplayed.
1470 sub build_tax_rows {
1471   my ($self) = @_;
1472
1473   my $rows_as_html;
1474   foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
1475     $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
1476   }
1477   return $rows_as_html;
1478 }
1479
1480
1481 sub render_price_dialog {
1482   my ($self, $record_item) = @_;
1483
1484   my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
1485
1486   $self->js
1487     ->run(
1488       'kivi.io.price_chooser_dialog',
1489       t8('Available Prices'),
1490       $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
1491     )
1492     ->reinit_widgets;
1493
1494 #   if (@errors) {
1495 #     $self->js->text('#dialog_flash_error_content', join ' ', @errors);
1496 #     $self->js->show('#dialog_flash_error');
1497 #   }
1498
1499   $self->js->render;
1500 }
1501
1502 sub load_order {
1503   my ($self) = @_;
1504
1505   return if !$::form->{id};
1506
1507   $self->order(SL::DB::Order->new(id => $::form->{id})->load);
1508
1509   # Add an empty custom shipto to the order, so that the dialog can render the cvar inputs.
1510   # You need a custom shipto object to call cvars_by_config to get the cvars.
1511   $self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => [])) if !$self->order->custom_shipto;
1512
1513   return $self->order;
1514 }
1515
1516 # load or create a new order object
1517 #
1518 # And assign changes from the form to this object.
1519 # If the order is loaded from db, check if items are deleted in the form,
1520 # remove them form the object and collect them for removing from db on saving.
1521 # Then create/update items from form (via make_item) and add them.
1522 sub make_order {
1523   my ($self) = @_;
1524
1525   # add_items adds items to an order with no items for saving, but they cannot
1526   # be retrieved via items until the order is saved. Adding empty items to new
1527   # order here solves this problem.
1528   my $order;
1529   $order   = SL::DB::Order->new(id => $::form->{id})->load(with => [ 'orderitems', 'orderitems.part' ]) if $::form->{id};
1530   $order ||= SL::DB::Order->new(orderitems  => [],
1531                                 quotation   => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type())),
1532                                 currency_id => $::instance_conf->get_currency_id(),);
1533
1534   my $cv_id_method = $self->cv . '_id';
1535   if (!$::form->{id} && $::form->{$cv_id_method}) {
1536     $order->$cv_id_method($::form->{$cv_id_method});
1537     setup_order_from_cv($order);
1538   }
1539
1540   my $form_orderitems                  = delete $::form->{order}->{orderitems};
1541   my $form_periodic_invoices_config    = delete $::form->{order}->{periodic_invoices_config};
1542
1543   $order->assign_attributes(%{$::form->{order}});
1544
1545   $self->setup_custom_shipto_from_form($order, $::form);
1546
1547   if (my $periodic_invoices_config_attrs = $form_periodic_invoices_config ? SL::YAML::Load($form_periodic_invoices_config) : undef) {
1548     my $periodic_invoices_config = $order->periodic_invoices_config || $order->periodic_invoices_config(SL::DB::PeriodicInvoicesConfig->new);
1549     $periodic_invoices_config->assign_attributes(%$periodic_invoices_config_attrs);
1550   }
1551
1552   # remove deleted items
1553   $self->item_ids_to_delete([]);
1554   foreach my $idx (reverse 0..$#{$order->orderitems}) {
1555     my $item = $order->orderitems->[$idx];
1556     if (none { $item->id == $_->{id} } @{$form_orderitems}) {
1557       splice @{$order->orderitems}, $idx, 1;
1558       push @{$self->item_ids_to_delete}, $item->id;
1559     }
1560   }
1561
1562   my @items;
1563   my $pos = 1;
1564   foreach my $form_attr (@{$form_orderitems}) {
1565     my $item = make_item($order, $form_attr);
1566     $item->position($pos);
1567     push @items, $item;
1568     $pos++;
1569   }
1570   $order->add_items(grep {!$_->id} @items);
1571
1572   return $order;
1573 }
1574
1575 # create or update items from form
1576 #
1577 # Make item objects from form values. For items already existing read from db.
1578 # Create a new item else. And assign attributes.
1579 sub make_item {
1580   my ($record, $attr) = @_;
1581
1582   my $item;
1583   $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
1584
1585   my $is_new = !$item;
1586
1587   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1588   # they cannot be retrieved via custom_variables until the order/orderitem is
1589   # saved. Adding empty custom_variables to new orderitem here solves this problem.
1590   $item ||= SL::DB::OrderItem->new(custom_variables => []);
1591
1592   $item->assign_attributes(%$attr);
1593
1594   if ($is_new) {
1595     my $texts = get_part_texts($item->part, $record->language_id);
1596     $item->longdescription($texts->{longdescription})              if !defined $attr->{longdescription};
1597     $item->project_id($record->globalproject_id)                   if !defined $attr->{project_id};
1598     $item->lastcost($record->is_sales ? $item->part->lastcost : 0) if !defined $attr->{lastcost_as_number};
1599   }
1600
1601   return $item;
1602 }
1603
1604 # create a new item
1605 #
1606 # This is used to add one item
1607 sub new_item {
1608   my ($record, $attr) = @_;
1609
1610   my $item = SL::DB::OrderItem->new;
1611
1612   # Remove attributes where the user left or set the inputs empty.
1613   # So these attributes will be undefined and we can distinguish them
1614   # from zero later on.
1615   for (qw(qty_as_number sellprice_as_number discount_as_percent)) {
1616     delete $attr->{$_} if $attr->{$_} eq '';
1617   }
1618
1619   $item->assign_attributes(%$attr);
1620
1621   my $part         = SL::DB::Part->new(id => $attr->{parts_id})->load;
1622   my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
1623
1624   $item->unit($part->unit) if !$item->unit;
1625
1626   my $price_src;
1627   if ( $part->is_assortment ) {
1628     # add assortment items with price 0, as the components carry the price
1629     $price_src = $price_source->price_from_source("");
1630     $price_src->price(0);
1631   } elsif (defined $item->sellprice) {
1632     $price_src = $price_source->price_from_source("");
1633     $price_src->price($item->sellprice);
1634   } else {
1635     $price_src = $price_source->best_price
1636                ? $price_source->best_price
1637                : $price_source->price_from_source("");
1638     $price_src->price($::form->round_amount($price_src->price / $record->exchangerate, 5)) if $record->exchangerate;
1639     $price_src->price(0) if !$price_source->best_price;
1640   }
1641
1642   my $discount_src;
1643   if (defined $item->discount) {
1644     $discount_src = $price_source->discount_from_source("");
1645     $discount_src->discount($item->discount);
1646   } else {
1647     $discount_src = $price_source->best_discount
1648                   ? $price_source->best_discount
1649                   : $price_source->discount_from_source("");
1650     $discount_src->discount(0) if !$price_source->best_discount;
1651   }
1652
1653   my %new_attr;
1654   $new_attr{part}                   = $part;
1655   $new_attr{description}            = $part->description     if ! $item->description;
1656   $new_attr{qty}                    = 1.0                    if ! $item->qty;
1657   $new_attr{price_factor_id}        = $part->price_factor_id if ! $item->price_factor_id;
1658   $new_attr{sellprice}              = $price_src->price;
1659   $new_attr{discount}               = $discount_src->discount;
1660   $new_attr{active_price_source}    = $price_src;
1661   $new_attr{active_discount_source} = $discount_src;
1662   $new_attr{longdescription}        = $part->notes           if ! defined $attr->{longdescription};
1663   $new_attr{project_id}             = $record->globalproject_id;
1664   $new_attr{lastcost}               = $record->is_sales ? $part->lastcost : 0;
1665
1666   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1667   # they cannot be retrieved via custom_variables until the order/orderitem is
1668   # saved. Adding empty custom_variables to new orderitem here solves this problem.
1669   $new_attr{custom_variables} = [];
1670
1671   my $texts = get_part_texts($part, $record->language_id, description => $new_attr{description}, longdescription => $new_attr{longdescription});
1672
1673   $item->assign_attributes(%new_attr, %{ $texts });
1674
1675   return $item;
1676 }
1677
1678 sub setup_order_from_cv {
1679   my ($order) = @_;
1680
1681   $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id currency_id));
1682
1683   $order->intnotes($order->customervendor->notes);
1684
1685   return if !$order->is_sales;
1686
1687   $order->salesman_id($order->customer->salesman_id || SL::DB::Manager::Employee->current->id);
1688   $order->taxincluded(defined($order->customer->taxincluded_checked)
1689                       ? $order->customer->taxincluded_checked
1690                       : $::myconfig{taxincluded_checked});
1691
1692   my $address = $order->customer->default_billing_address;;
1693   $order->billing_address_id($address ? $address->id : undef);
1694 }
1695
1696 # setup custom shipto from form
1697 #
1698 # The dialog returns form variables starting with 'shipto' and cvars starting
1699 # with 'shiptocvar_'.
1700 # Mark it to be deleted if a shipto from master data is selected
1701 # (i.e. order has a shipto).
1702 # Else, update or create a new custom shipto. If the fields are empty, it
1703 # will not be saved on save.
1704 sub setup_custom_shipto_from_form {
1705   my ($self, $order, $form) = @_;
1706
1707   if ($order->shipto) {
1708     $self->is_custom_shipto_to_delete(1);
1709   } else {
1710     my $custom_shipto = $order->custom_shipto || $order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
1711
1712     my $shipto_cvars  = {map { my ($key) = m{^shiptocvar_(.+)}; $key => delete $form->{$_}} grep { m{^shiptocvar_} } keys %$form};
1713     my $shipto_attrs  = {map {                                  $_   => delete $form->{$_}} grep { m{^shipto}      } keys %$form};
1714
1715     $custom_shipto->assign_attributes(%$shipto_attrs);
1716     $custom_shipto->cvar_by_name($_)->value($shipto_cvars->{$_}) for keys %$shipto_cvars;
1717   }
1718 }
1719
1720 # recalculate prices and taxes
1721 #
1722 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1723 sub recalc {
1724   my ($self) = @_;
1725
1726   my %pat = $self->order->calculate_prices_and_taxes();
1727
1728   $self->{taxes} = [];
1729   foreach my $tax_id (keys %{ $pat{taxes_by_tax_id} }) {
1730     my $netamount = sum0 map { $pat{amounts}->{$_}->{amount} } grep { $pat{amounts}->{$_}->{tax_id} == $tax_id } keys %{ $pat{amounts} };
1731
1732     push(@{ $self->{taxes} }, { amount    => $pat{taxes_by_tax_id}->{$tax_id},
1733                                 netamount => $netamount,
1734                                 tax       => SL::DB::Tax->new(id => $tax_id)->load });
1735   }
1736   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items_sorted}, @{$pat{items}};
1737 }
1738
1739 # get data for saving, printing, ..., that is not changed in the form
1740 #
1741 # Only cvars for now.
1742 sub get_unalterable_data {
1743   my ($self) = @_;
1744
1745   foreach my $item (@{ $self->order->items }) {
1746     # autovivify all cvars that are not in the form (cvars_by_config can do it).
1747     # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1748     foreach my $var (@{ $item->cvars_by_config }) {
1749       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1750     }
1751     $item->parse_custom_variable_values;
1752   }
1753 }
1754
1755 # delete the order
1756 #
1757 # And remove related files in the spool directory
1758 sub delete {
1759   my ($self) = @_;
1760
1761   my $errors = [];
1762   my $db     = $self->order->db;
1763
1764   $db->with_transaction(
1765     sub {
1766       my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
1767       $self->order->delete;
1768       my $spool = $::lx_office_conf{paths}->{spool};
1769       unlink map { "$spool/$_" } @spoolfiles if $spool;
1770
1771       $self->save_history('DELETED');
1772
1773       1;
1774   }) || push(@{$errors}, $db->error);
1775
1776   return $errors;
1777 }
1778
1779 # save the order
1780 #
1781 # And delete items that are deleted in the form.
1782 sub save {
1783   my ($self) = @_;
1784
1785   my $errors = [];
1786   my $db     = $self->order->db;
1787
1788   $db->with_transaction(sub {
1789     # delete custom shipto if it is to be deleted or if it is empty
1790     if ($self->order->custom_shipto && ($self->is_custom_shipto_to_delete || $self->order->custom_shipto->is_empty)) {
1791       $self->order->custom_shipto->delete if $self->order->custom_shipto->shipto_id;
1792       $self->order->custom_shipto(undef);
1793     }
1794
1795     SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete || []};
1796     $self->order->save(cascade => 1);
1797
1798     # link records
1799     if ($::form->{converted_from_oe_id}) {
1800       my @converted_from_oe_ids = split ' ', $::form->{converted_from_oe_id};
1801
1802       foreach my $converted_from_oe_id (@converted_from_oe_ids) {
1803         my $src = SL::DB::Order->new(id => $converted_from_oe_id)->load;
1804         $src->update_attributes(closed => 1) if $src->type =~ /_quotation$/;
1805         $src->link_to_record($self->order);
1806       }
1807       if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1808         my $idx = 0;
1809         foreach (@{ $self->order->items_sorted }) {
1810           my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1811           next if !$from_id;
1812           SL::DB::RecordLink->new(from_table => 'orderitems',
1813                                   from_id    => $from_id,
1814                                   to_table   => 'orderitems',
1815                                   to_id      => $_->id
1816           )->save;
1817           $idx++;
1818         }
1819       }
1820
1821       $self->link_requirement_specs_linking_to_created_from_objects(@converted_from_oe_ids);
1822     }
1823
1824     $self->set_project_in_linked_requirement_specs if $self->order->globalproject_id;
1825
1826     $self->save_history('SAVED');
1827
1828     1;
1829   }) || push(@{$errors}, $db->error);
1830
1831   return $errors;
1832 }
1833
1834 sub workflow_sales_or_request_for_quotation {
1835   my ($self) = @_;
1836
1837   # always save
1838   my $errors = $self->save();
1839
1840   if (scalar @{ $errors }) {
1841     $self->js->flash('error', $_) for @{ $errors };
1842     return $self->js->render();
1843   }
1844
1845   my $destination_type = $::form->{type} eq sales_order_type() ? sales_quotation_type() : request_quotation_type();
1846
1847   $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1848   $self->{converted_from_oe_id} = delete $::form->{id};
1849
1850   # set item ids to new fake id, to identify them as new items
1851   foreach my $item (@{$self->order->items_sorted}) {
1852     $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1853   }
1854
1855   # change form type
1856   $::form->{type} = $destination_type;
1857   $self->type($self->init_type);
1858   $self->cv  ($self->init_cv);
1859   $self->check_auth;
1860
1861   $self->recalc();
1862   $self->get_unalterable_data();
1863   $self->pre_render();
1864
1865   # trigger rendering values for second row as hidden, because they
1866   # are loaded only on demand. So we need to keep the values from the
1867   # source.
1868   $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1869
1870   $self->render(
1871     'order/form',
1872     title => $self->get_title_for('edit'),
1873     %{$self->{template_args}}
1874   );
1875 }
1876
1877 sub workflow_sales_or_purchase_order {
1878   my ($self) = @_;
1879
1880   # always save
1881   my $errors = $self->save();
1882
1883   if (scalar @{ $errors }) {
1884     $self->js->flash('error', $_) foreach @{ $errors };
1885     return $self->js->render();
1886   }
1887
1888   my $destination_type = $::form->{type} eq sales_quotation_type()   ? sales_order_type()
1889                        : $::form->{type} eq request_quotation_type() ? purchase_order_type()
1890                        : $::form->{type} eq purchase_order_type()    ? sales_order_type()
1891                        : $::form->{type} eq sales_order_type()       ? purchase_order_type()
1892                        : '';
1893
1894   # check for direct delivery
1895   # copy shipto in custom shipto (custom shipto will be copied by new_from() in case)
1896   my $custom_shipto;
1897   if (   $::form->{type} eq sales_order_type() && $destination_type eq purchase_order_type()
1898       && $::form->{use_shipto} && $self->order->shipto) {
1899     $custom_shipto = $self->order->shipto->clone('SL::DB::Order');
1900   }
1901
1902   $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1903   $self->{converted_from_oe_id} = delete $::form->{id};
1904
1905   # set item ids to new fake id, to identify them as new items
1906   foreach my $item (@{$self->order->items_sorted}) {
1907     $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1908   }
1909
1910   if ($::form->{type} eq sales_order_type() && $destination_type eq purchase_order_type()) {
1911     if ($::form->{use_shipto}) {
1912       $self->order->custom_shipto($custom_shipto) if $custom_shipto;
1913     } else {
1914       # remove any custom shipto if not wanted
1915       $self->order->custom_shipto(SL::DB::Shipto->new(module => 'OE', custom_variables => []));
1916     }
1917   }
1918
1919   # change form type
1920   $::form->{type} = $destination_type;
1921   $self->type($self->init_type);
1922   $self->cv  ($self->init_cv);
1923   $self->check_auth;
1924
1925   $self->recalc();
1926   $self->get_unalterable_data();
1927   $self->pre_render();
1928
1929   # trigger rendering values for second row as hidden, because they
1930   # are loaded only on demand. So we need to keep the values from the
1931   # source.
1932   $_->{render_second_row} = 1 for @{ $self->order->items_sorted };
1933
1934   $self->render(
1935     'order/form',
1936     title => $self->get_title_for('edit'),
1937     %{$self->{template_args}}
1938   );
1939 }
1940
1941
1942 sub pre_render {
1943   my ($self) = @_;
1944
1945   $self->{all_taxzones}               = SL::DB::Manager::TaxZone->get_all_sorted();
1946   $self->{all_currencies}             = SL::DB::Manager::Currency->get_all_sorted();
1947   $self->{all_departments}            = SL::DB::Manager::Department->get_all_sorted();
1948   $self->{all_languages}              = SL::DB::Manager::Language->get_all_sorted();
1949   $self->{all_employees}              = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1950                                                                                               deleted => 0 ] ],
1951                                                                            sort_by => 'name');
1952   $self->{all_salesmen}               = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1953                                                                                               deleted => 0 ] ],
1954                                                                            sort_by => 'name');
1955   $self->{all_payment_terms}          = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1956                                                                                                         obsolete => 0 ] ]);
1957   $self->{all_delivery_terms}         = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1958   $self->{current_employee_id}        = SL::DB::Manager::Employee->current->id;
1959   $self->{periodic_invoices_status}   = $self->get_periodic_invoices_status($self->order->periodic_invoices_config);
1960   $self->{order_probabilities}        = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
1961   $self->{positions_scrollbar_height} = SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
1962
1963   my $print_form = Form->new('');
1964   $print_form->{type}        = $self->type;
1965   $print_form->{printers}    = SL::DB::Manager::Printer->get_all_sorted;
1966   $self->{print_options}     = SL::Helper::PrintOptions->get_print_options(
1967     form => $print_form,
1968     options => {dialog_name_prefix => 'print_options.',
1969                 show_headers       => 1,
1970                 no_queue           => 1,
1971                 no_postscript      => 1,
1972                 no_opendocument    => 0,
1973                 no_html            => 0},
1974   );
1975
1976   foreach my $item (@{$self->order->orderitems}) {
1977     my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1978     $item->active_price_source(   $price_source->price_from_source(   $item->active_price_source   ));
1979     $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
1980   }
1981
1982   if (any { $self->type eq $_ } (sales_order_type(), purchase_order_type())) {
1983     # Calculate shipped qtys here to prevent calling calculate for every item via the items method.
1984     # Do not use write_to_objects to prevent order->delivered to be set, because this should be
1985     # the value from db, which can be set manually or is set when linked delivery orders are saved.
1986     SL::Helper::ShippedQty->new->calculate($self->order)->write_to(\@{$self->order->items});
1987   }
1988
1989   if ($self->order->number && $::instance_conf->get_webdav) {
1990     my $webdav = SL::Webdav->new(
1991       type     => $self->type,
1992       number   => $self->order->number,
1993     );
1994     my @all_objects = $webdav->get_all_objects;
1995     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1996                                                     type => t8('File'),
1997                                                     link => File::Spec->catfile($_->full_filedescriptor),
1998                                                 } } @all_objects;
1999   }
2000
2001   if (   (any { $self->type eq $_ } (sales_quotation_type(), sales_order_type()))
2002       && $::instance_conf->get_transport_cost_reminder_article_number_id ) {
2003     $self->{template_args}->{transport_cost_reminder_article} = SL::DB::Part->new(id => $::instance_conf->get_transport_cost_reminder_article_number_id)->load;
2004   }
2005
2006   $self->get_item_cvpartnumber($_) for @{$self->order->items_sorted};
2007
2008   $::request->{layout}->use_javascript("${_}.js") for qw(kivi.Validator kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery
2009                                                          edit_periodic_invoices_config calculate_qty follow_up show_history);
2010   $self->setup_edit_action_bar;
2011 }
2012
2013 sub setup_edit_action_bar {
2014   my ($self, %params) = @_;
2015
2016   my $deletion_allowed = (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type()))
2017                       || (($self->type eq sales_order_type())    && $::instance_conf->get_sales_order_show_delete)
2018                       || (($self->type eq purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);
2019
2020   my @req_trans_cost_art = qw(kivi.Order.check_transport_cost_article_presence) x!!$::instance_conf->get_transport_cost_reminder_article_number_id;
2021   my @req_cusordnumber   = qw(kivi.Order.check_cusordnumber_presence)           x($self->type eq sales_order_type() && $::instance_conf->get_order_warn_no_cusordnumber);
2022
2023   my $has_invoice_for_advance_payment;
2024   if ($self->order->id && $self->type eq sales_order_type()) {
2025     my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
2026     $has_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
2027   }
2028
2029   my $has_final_invoice;
2030   if ($self->order->id && $self->type eq sales_order_type()) {
2031     my $lr = $self->order->linked_records(direction => 'to', to => ['Invoice']);
2032     $has_final_invoice               = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->type} @$lr;
2033   }
2034
2035   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
2036   my $right     = $right_for->{ $self->type };
2037   $right      ||= 'DOES_NOT_EXIST';
2038
2039   if ($::auth->assert($right, 1)) {
2040   for my $bar ($::request->layout->get('actionbar')) {
2041     $bar->add(
2042       combobox => [
2043         action => [
2044           t8('Save'),
2045           call      => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
2046                                                     $::instance_conf->get_order_warn_no_deliverydate,
2047           ],
2048           checks    => [ 'kivi.Order.check_save_active_periodic_invoices', ['kivi.validate_form','#order_form'],
2049                          @req_trans_cost_art, @req_cusordnumber,
2050           ],
2051         ],
2052         action => [
2053           t8('Save as new'),
2054           call      => [ 'kivi.Order.save', 'save_as_new', $::instance_conf->get_order_warn_duplicate_parts ],
2055           checks    => [ 'kivi.Order.check_save_active_periodic_invoices',
2056                          @req_trans_cost_art, @req_cusordnumber,
2057           ],
2058           disabled  => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2059         ],
2060       ], # end of combobox "Save"
2061
2062       combobox => [
2063         action => [
2064           t8('Workflow'),
2065         ],
2066         action => [
2067           t8('Save and Quotation'),
2068           submit   => [ '#order_form', { action => "Order/sales_quotation" } ],
2069           checks   => [ @req_trans_cost_art, @req_cusordnumber ],
2070           only_if  => (any { $self->type eq $_ } (sales_order_type())),
2071         ],
2072         action => [
2073           t8('Save and RFQ'),
2074           submit   => [ '#order_form', { action => "Order/request_for_quotation" } ],
2075           only_if  => (any { $self->type eq $_ } (purchase_order_type())),
2076         ],
2077         action => [
2078           t8('Save and Sales Order'),
2079           submit   => [ '#order_form', { action => "Order/sales_order" } ],
2080           checks   => [ @req_trans_cost_art ],
2081           only_if  => (any { $self->type eq $_ } (sales_quotation_type(), purchase_order_type())),
2082         ],
2083         action => [
2084           t8('Save and Purchase Order'),
2085           call      => [ 'kivi.Order.purchase_order_check_for_direct_delivery' ],
2086           checks    => [ @req_trans_cost_art, @req_cusordnumber ],
2087           only_if   => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
2088         ],
2089         action => [
2090           t8('Save and Delivery Order'),
2091           call      => [ 'kivi.Order.save', 'save_and_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
2092                                                                        $::instance_conf->get_order_warn_no_deliverydate,
2093                                                                                                                         ],
2094           checks    => [ 'kivi.Order.check_save_active_periodic_invoices',
2095                          @req_trans_cost_art, @req_cusordnumber,
2096           ],
2097           only_if   => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type()))
2098         ],
2099         action => [
2100           t8('Save and Supplier Delivery Order'),
2101           call      => [ 'kivi.Order.save', 'save_and_supplier_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
2102                                                                        $::instance_conf->get_order_warn_no_deliverydate,
2103                                                                                                                         ],
2104           checks    => [ 'kivi.Order.check_save_active_periodic_invoices',
2105                          @req_trans_cost_art, @req_cusordnumber,
2106           ],
2107           only_if   => (any { $self->type eq $_ } (purchase_order_type()))
2108         ],
2109         action => [
2110           t8('Save and Invoice'),
2111           call      => [ 'kivi.Order.save', 'save_and_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
2112           checks    => [ 'kivi.Order.check_save_active_periodic_invoices',
2113                          @req_trans_cost_art, @req_cusordnumber,
2114           ],
2115         ],
2116         action => [
2117           ($has_invoice_for_advance_payment ? t8('Save and Further Invoice for Advance Payment') : t8('Save and Invoice for Advance Payment')),
2118           call      => [ 'kivi.Order.save', 'save_and_invoice_for_advance_payment', $::instance_conf->get_order_warn_duplicate_parts ],
2119           checks    => [ 'kivi.Order.check_save_active_periodic_invoices',
2120                          @req_trans_cost_art, @req_cusordnumber,
2121           ],
2122           disabled  => $has_final_invoice ? t8('This order has already a final invoice.')
2123                                           : undef,
2124           only_if   => (any { $self->type eq $_ } (sales_order_type())),
2125         ],
2126         action => [
2127           t8('Save and Final Invoice'),
2128           call      => [ 'kivi.Order.save', 'save_and_final_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
2129           checks    => [ 'kivi.Order.check_save_active_periodic_invoices',
2130                          @req_trans_cost_art, @req_cusordnumber,
2131           ],
2132           disabled  => $has_final_invoice ? t8('This order has already a final invoice.')
2133                                           : undef,
2134           only_if   => (any { $self->type eq $_ } (sales_order_type())) && $has_invoice_for_advance_payment,
2135         ],
2136         action => [
2137           t8('Save and AP Transaction'),
2138           call      => [ 'kivi.Order.save', 'save_and_ap_transaction', $::instance_conf->get_order_warn_duplicate_parts ],
2139           only_if   => (any { $self->type eq $_ } (purchase_order_type()))
2140         ],
2141
2142       ], # end of combobox "Workflow"
2143
2144       combobox => [
2145         action => [
2146           t8('Export'),
2147         ],
2148         action => [
2149           t8('Save and preview PDF'),
2150           call   => [ 'kivi.Order.save', 'preview_pdf', $::instance_conf->get_order_warn_duplicate_parts,
2151                                                         $::instance_conf->get_order_warn_no_deliverydate,
2152                     ],
2153           checks => [ @req_trans_cost_art, @req_cusordnumber ],
2154         ],
2155         action => [
2156           t8('Save and print'),
2157           call   => [ 'kivi.Order.show_print_options', $::instance_conf->get_order_warn_duplicate_parts,
2158                                                        $::instance_conf->get_order_warn_no_deliverydate,
2159                     ],
2160           checks => [ @req_trans_cost_art, @req_cusordnumber ],
2161         ],
2162         action => [
2163           t8('Save and E-mail'),
2164           id   => 'save_and_email_action',
2165           call => [ 'kivi.Order.save', 'save_and_show_email_dialog', $::instance_conf->get_order_warn_duplicate_parts,
2166                                                                      $::instance_conf->get_order_warn_no_deliverydate,
2167                   ],
2168           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2169         ],
2170         action => [
2171           t8('Download attachments of all parts'),
2172           call     => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
2173           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2174           only_if  => $::instance_conf->get_doc_storage,
2175         ],
2176       ], # end of combobox "Export"
2177
2178       action => [
2179         t8('Delete'),
2180         call     => [ 'kivi.Order.delete_order' ],
2181         confirm  => $::locale->text('Do you really want to delete this object?'),
2182         disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2183         only_if  => $deletion_allowed,
2184       ],
2185
2186     );
2187   }
2188   }
2189
2190   for my $bar ($::request->layout->get('actionbar')) {
2191     $bar->add(
2192       combobox => [
2193         action => [
2194           t8('more')
2195         ],
2196         action => [
2197           t8('History'),
2198           call     => [ 'set_history_window', $self->order->id, 'id' ],
2199           disabled => !$self->order->id ? t8('This record has not been saved yet.') : undef,
2200         ],
2201         action => [
2202           t8('Follow-Up'),
2203           call     => [ 'kivi.Order.follow_up_window' ],
2204           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
2205           only_if  => $::auth->assert('productivity', 1),
2206         ],
2207       ], # end of combobox "more"
2208     );
2209   }
2210
2211 }
2212
2213 sub generate_doc {
2214   my ($self, $doc_ref, $params) = @_;
2215
2216   my $order  = $self->order;
2217   my @errors = ();
2218
2219   my $print_form = Form->new('');
2220   $print_form->{type}        = $order->type;
2221   $print_form->{formname}    = $params->{formname} || $order->type;
2222   $print_form->{format}      = $params->{format}   || 'pdf';
2223   $print_form->{media}       = $params->{media}    || 'file';
2224   $print_form->{groupitems}  = $params->{groupitems};
2225   $print_form->{printer_id}  = $params->{printer_id};
2226   $print_form->{media}       = 'file'                             if $print_form->{media} eq 'screen';
2227
2228   $order->language($params->{language});
2229   $order->flatten_to_form($print_form, format_amounts => 1);
2230
2231   my $template_ext;
2232   my $template_type;
2233   if ($print_form->{format} =~ /(opendocument|oasis)/i) {
2234     $template_ext  = 'odt';
2235     $template_type = 'OpenDocument';
2236   } elsif ($print_form->{format} =~ m{html}i) {
2237     $template_ext  = 'html';
2238     $template_type = 'HTML';
2239   }
2240
2241   # search for the template
2242   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
2243     name        => $print_form->{formname},
2244     extension   => $template_ext,
2245     email       => $print_form->{media} eq 'email',
2246     language    => $params->{language},
2247     printer_id  => $print_form->{printer_id},
2248   );
2249
2250   if (!defined $template_file) {
2251     push @errors, $::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files);
2252   }
2253
2254   return @errors if scalar @errors;
2255
2256   $print_form->throw_on_error(sub {
2257     eval {
2258       $print_form->prepare_for_printing;
2259
2260       $$doc_ref = SL::Helper::CreatePDF->create_pdf(
2261         format        => $print_form->{format},
2262         template_type => $template_type,
2263         template      => $template_file,
2264         variables     => $print_form,
2265         variable_content_types => {
2266           longdescription => 'html',
2267           partnotes       => 'html',
2268           notes           => 'html',
2269           $::form->get_variable_content_types_for_cvars,
2270         },
2271       );
2272       1;
2273     } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->error : $EVAL_ERROR;
2274   });
2275
2276   return @errors;
2277 }
2278
2279 sub get_files_for_email_dialog {
2280   my ($self) = @_;
2281
2282   my %files = map { ($_ => []) } qw(versions files vc_files part_files);
2283
2284   return %files if !$::instance_conf->get_doc_storage;
2285
2286   if ($self->order->id) {
2287     $files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id,              object_type => $self->order->type, file_type => 'document') ];
2288     $files{files}    = [ SL::File->get_all(         object_id => $self->order->id,              object_type => $self->order->type, file_type => 'attachment') ];
2289     $files{vc_files} = [ SL::File->get_all(         object_id => $self->order->{$self->cv}->id, object_type => $self->cv,          file_type => 'attachment') ];
2290     $files{project_files} = [ SL::File->get_all(    object_id => $self->order->globalproject_id, object_type => 'project',         file_type => 'attachment') ];
2291   }
2292
2293   my @parts =
2294     uniq_by { $_->{id} }
2295     map {
2296       +{ id         => $_->part->id,
2297          partnumber => $_->part->partnumber }
2298     } @{$self->order->items_sorted};
2299
2300   foreach my $part (@parts) {
2301     my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
2302     push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
2303   }
2304
2305   foreach my $key (keys %files) {
2306     $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
2307   }
2308
2309   return %files;
2310 }
2311
2312 sub make_periodic_invoices_config_from_yaml {
2313   my ($yaml_config) = @_;
2314
2315   return if !$yaml_config;
2316   my $attr = SL::YAML::Load($yaml_config);
2317   return if 'HASH' ne ref $attr;
2318   return SL::DB::PeriodicInvoicesConfig->new(%$attr);
2319 }
2320
2321
2322 sub get_periodic_invoices_status {
2323   my ($self, $config) = @_;
2324
2325   return                      if $self->type ne sales_order_type();
2326   return t8('not configured') if !$config;
2327
2328   my $active = ('HASH' eq ref $config)                           ? $config->{active}
2329              : ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
2330              :                                                     die "Cannot get status of periodic invoices config";
2331
2332   return $active ? t8('active') : t8('inactive');
2333 }
2334
2335 sub get_title_for {
2336   my ($self, $action) = @_;
2337
2338   return '' if none { lc($action)} qw(add edit);
2339
2340   # for locales:
2341   # $::locale->text("Add Sales Order");
2342   # $::locale->text("Add Purchase Order");
2343   # $::locale->text("Add Quotation");
2344   # $::locale->text("Add Request for Quotation");
2345   # $::locale->text("Edit Sales Order");
2346   # $::locale->text("Edit Purchase Order");
2347   # $::locale->text("Edit Quotation");
2348   # $::locale->text("Edit Request for Quotation");
2349
2350   $action = ucfirst(lc($action));
2351   return $self->type eq sales_order_type()       ? $::locale->text("$action Sales Order")
2352        : $self->type eq purchase_order_type()    ? $::locale->text("$action Purchase Order")
2353        : $self->type eq sales_quotation_type()   ? $::locale->text("$action Quotation")
2354        : $self->type eq request_quotation_type() ? $::locale->text("$action Request for Quotation")
2355        : '';
2356 }
2357
2358 sub get_item_cvpartnumber {
2359   my ($self, $item) = @_;
2360
2361   return if !$self->search_cvpartnumber;
2362   return if !$self->order->customervendor;
2363
2364   if ($self->cv eq 'vendor') {
2365     my @mms = grep { $_->make eq $self->order->customervendor->id } @{$item->part->makemodels};
2366     $item->{cvpartnumber} = $mms[0]->model if scalar @mms;
2367   } elsif ($self->cv eq 'customer') {
2368     my @cps = grep { $_->customer_id eq $self->order->customervendor->id } @{$item->part->customerprices};
2369     $item->{cvpartnumber} = $cps[0]->customer_partnumber if scalar @cps;
2370   }
2371 }
2372
2373 sub get_part_texts {
2374   my ($part_or_id, $language_or_id, %defaults) = @_;
2375
2376   my $part        = ref($part_or_id)     ? $part_or_id         : SL::DB::Part->load_cached($part_or_id);
2377   my $language_id = ref($language_or_id) ? $language_or_id->id : $language_or_id;
2378   my $texts       = {
2379     description     => $defaults{description}     // $part->description,
2380     longdescription => $defaults{longdescription} // $part->notes,
2381   };
2382
2383   return $texts unless $language_id;
2384
2385   my $translation = SL::DB::Manager::Translation->get_first(
2386     where => [
2387       parts_id    => $part->id,
2388       language_id => $language_id,
2389     ]);
2390
2391   $texts->{description}     = $translation->translation     if $translation && $translation->translation;
2392   $texts->{longdescription} = $translation->longdescription if $translation && $translation->longdescription;
2393
2394   return $texts;
2395 }
2396
2397 sub sales_order_type {
2398   'sales_order';
2399 }
2400
2401 sub purchase_order_type {
2402   'purchase_order';
2403 }
2404
2405 sub sales_quotation_type {
2406   'sales_quotation';
2407 }
2408
2409 sub request_quotation_type {
2410   'request_quotation';
2411 }
2412
2413 sub nr_key {
2414   return $_[0]->type eq sales_order_type()       ? 'ordnumber'
2415        : $_[0]->type eq purchase_order_type()    ? 'ordnumber'
2416        : $_[0]->type eq sales_quotation_type()   ? 'quonumber'
2417        : $_[0]->type eq request_quotation_type() ? 'quonumber'
2418        : '';
2419 }
2420
2421 sub save_and_redirect_to {
2422   my ($self, %params) = @_;
2423
2424   my $errors = $self->save();
2425
2426   if (scalar @{ $errors }) {
2427     $self->js->flash('error', $_) foreach @{ $errors };
2428     return $self->js->render();
2429   }
2430
2431   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been saved')
2432            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been saved')
2433            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been saved')
2434            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
2435            : '';
2436   flash_later('info', $text);
2437
2438   $self->redirect_to(%params, id => $self->order->id);
2439 }
2440
2441 sub save_history {
2442   my ($self, $addition) = @_;
2443
2444   my $number_type = $self->order->type =~ m{order} ? 'ordnumber' : 'quonumber';
2445   my $snumbers    = $number_type . '_' . $self->order->$number_type;
2446
2447   SL::DB::History->new(
2448     trans_id    => $self->order->id,
2449     employee_id => SL::DB::Manager::Employee->current->id,
2450     what_done   => $self->order->type,
2451     snumbers    => $snumbers,
2452     addition    => $addition,
2453   )->save;
2454 }
2455
2456 sub store_doc_to_webdav_and_filemanagement {
2457   my ($self, $content, $filename, $variant) = @_;
2458
2459   my $order = $self->order;
2460   my @errors;
2461
2462   # copy file to webdav folder
2463   if ($order->number && $::instance_conf->get_webdav_documents) {
2464     my $webdav = SL::Webdav->new(
2465       type     => $order->type,
2466       number   => $order->number,
2467     );
2468     my $webdav_file = SL::Webdav::File->new(
2469       webdav   => $webdav,
2470       filename => $filename,
2471     );
2472     eval {
2473       $webdav_file->store(data => \$content);
2474       1;
2475     } or do {
2476       push @errors, t8('Storing the document to the WebDAV folder failed: #1', $@);
2477     };
2478   }
2479   if ($order->id && $::instance_conf->get_doc_storage) {
2480     eval {
2481       SL::File->save(object_id     => $order->id,
2482                      object_type   => $order->type,
2483                      mime_type     => SL::MIME->mime_type_from_ext($filename),
2484                      source        => 'created',
2485                      file_type     => 'document',
2486                      file_name     => $filename,
2487                      file_contents => $content,
2488                      print_variant => $variant);
2489       1;
2490     } or do {
2491       push @errors, t8('Storing the document in the storage backend failed: #1', $@);
2492     };
2493   }
2494
2495   return @errors;
2496 }
2497
2498 sub link_requirement_specs_linking_to_created_from_objects {
2499   my ($self, @converted_from_oe_ids) = @_;
2500
2501   return unless @converted_from_oe_ids;
2502
2503   my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => \@converted_from_oe_ids ]);
2504   foreach my $rs_order (@{ $rs_orders }) {
2505     SL::DB::RequirementSpecOrder->new(
2506       order_id            => $self->order->id,
2507       requirement_spec_id => $rs_order->requirement_spec_id,
2508       version_id          => $rs_order->version_id,
2509     )->save;
2510   }
2511 }
2512
2513 sub set_project_in_linked_requirement_specs {
2514   my ($self) = @_;
2515
2516   my $rs_orders = SL::DB::Manager::RequirementSpecOrder->get_all(where => [ order_id => $self->order->id ]);
2517   foreach my $rs_order (@{ $rs_orders }) {
2518     next if $rs_order->requirement_spec->project_id == $self->order->globalproject_id;
2519
2520     $rs_order->requirement_spec->update_attributes(project_id => $self->order->globalproject_id);
2521   }
2522 }
2523
2524 1;
2525
2526 __END__
2527
2528 =encoding utf-8
2529
2530 =head1 NAME
2531
2532 SL::Controller::Order - controller for orders
2533
2534 =head1 SYNOPSIS
2535
2536 This is a new form to enter orders, completely rewritten with the use
2537 of controller and java script techniques.
2538
2539 The aim is to provide the user a better experience and a faster workflow. Also
2540 the code should be more readable, more reliable and better to maintain.
2541
2542 =head2 Key Features
2543
2544 =over 4
2545
2546 =item *
2547
2548 One input row, so that input happens every time at the same place.
2549
2550 =item *
2551
2552 Use of pickers where possible.
2553
2554 =item *
2555
2556 Possibility to enter more than one item at once.
2557
2558 =item *
2559
2560 Item list in a scrollable area, so that the workflow buttons stay at
2561 the bottom.
2562
2563 =item *
2564
2565 Reordering item rows with drag and drop is possible. Sorting item rows is
2566 possible (by partnumber, description, qty, sellprice and discount for now).
2567
2568 =item *
2569
2570 No C<update> is necessary. All entries and calculations are managed
2571 with ajax-calls and the page only reloads on C<save>.
2572
2573 =item *
2574
2575 User can see changes immediately, because of the use of java script
2576 and ajax.
2577
2578 =back
2579
2580 =head1 CODE
2581
2582 =head2 Layout
2583
2584 =over 4
2585
2586 =item * C<SL/Controller/Order.pm>
2587
2588 the controller
2589
2590 =item * C<template/webpages/order/form.html>
2591
2592 main form
2593
2594 =item * C<template/webpages/order/tabs/basic_data.html>
2595
2596 Main tab for basic_data.
2597
2598 This is the only tab here for now. "linked records" and "webdav" tabs are
2599 reused from generic code.
2600
2601 =over 4
2602
2603 =item * C<template/webpages/order/tabs/_business_info_row.html>
2604
2605 For displaying information on business type
2606
2607 =item * C<template/webpages/order/tabs/_item_input.html>
2608
2609 The input line for items
2610
2611 =item * C<template/webpages/order/tabs/_row.html>
2612
2613 One row for already entered items
2614
2615 =item * C<template/webpages/order/tabs/_tax_row.html>
2616
2617 Displaying tax information
2618
2619 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
2620
2621 Dialog for selecting price and discount sources
2622
2623 =back
2624
2625 =item * C<js/kivi.Order.js>
2626
2627 java script functions
2628
2629 =back
2630
2631 =head1 TODO
2632
2633 =over 4
2634
2635 =item * testing
2636
2637 =item * price sources: little symbols showing better price / better discount
2638
2639 =item * select units in input row?
2640
2641 =item * check for direct delivery (workflow sales order -> purchase order)
2642
2643 =item * access rights
2644
2645 =item * display weights
2646
2647 =item * mtime check
2648
2649 =item * optional client/user behaviour
2650
2651 (transactions has to be set - department has to be set -
2652  force project if enabled in client config)
2653
2654 =back
2655
2656 =head1 KNOWN BUGS AND CAVEATS
2657
2658 =over 4
2659
2660 =item *
2661
2662 Customer discount is not displayed as a valid discount in price source popup
2663 (this might be a bug in price sources)
2664
2665 (I cannot reproduce this (Bernd))
2666
2667 =item *
2668
2669 No indication that <shift>-up/down expands/collapses second row.
2670
2671 =item *
2672
2673 Inline creation of parts is not currently supported
2674
2675 =item *
2676
2677 Table header is not sticky in the scrolling area.
2678
2679 =item *
2680
2681 Sorting does not include C<position>, neither does reordering.
2682
2683 This behavior was implemented intentionally. But we can discuss, which behavior
2684 should be implemented.
2685
2686 =back
2687
2688 =head1 To discuss / Nice to have
2689
2690 =over 4
2691
2692 =item *
2693
2694 How to expand/collapse second row. Now it can be done clicking the icon or
2695 <shift>-up/down.
2696
2697 =item *
2698
2699 Possibility to select PriceSources in input row?
2700
2701 =item *
2702
2703 This controller uses a (changed) copy of the template for the PriceSource
2704 dialog. Maybe there could be used one code source.
2705
2706 =item *
2707
2708 Rounding-differences between this controller (PriceTaxCalculator) and the old
2709 form. This is not only a problem here, but also in all parts using the PTC.
2710 There exists a ticket and a patch. This patch should be testet.
2711
2712 =item *
2713
2714 An indicator, if the actual inputs are saved (like in an
2715 editor or on text processing application).
2716
2717 =item *
2718
2719 A warning when leaving the page without saveing unchanged inputs.
2720
2721
2722 =back
2723
2724 =head1 AUTHOR
2725
2726 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>
2727
2728 =cut