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