Auftrags-Controller: multi items dialog: JavaScript aus html-Template raus
[kivitendo-erp.git] / SL / Controller / Order.pm
1 package SL::Controller::Order;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use SL::Helper::Flash qw(flash_later);
7 use SL::Presenter::Tag qw(select_tag hidden_tag);
8 use SL::Locale::String qw(t8);
9 use SL::SessionFile::Random;
10 use SL::PriceSource;
11 use SL::Webdav;
12 use SL::File;
13 use SL::Util qw(trim);
14 use SL::DB::Order;
15 use SL::DB::Default;
16 use SL::DB::Unit;
17 use SL::DB::Part;
18 use SL::DB::PartsGroup;
19 use SL::DB::Printer;
20 use SL::DB::Language;
21 use SL::DB::RecordLink;
22
23 use SL::Helper::CreatePDF qw(:all);
24 use SL::Helper::PrintOptions;
25
26 use SL::Controller::Helper::GetModels;
27
28 use List::Util qw(first);
29 use List::UtilsBy qw(sort_by uniq_by);
30 use List::MoreUtils qw(any none pairwise first_index);
31 use English qw(-no_match_vars);
32 use File::Spec;
33 use Cwd;
34
35 use Rose::Object::MakeMethods::Generic
36 (
37  scalar => [ qw(item_ids_to_delete) ],
38  'scalar --get_set_init' => [ qw(order valid_types type cv p multi_items_models all_price_factors) ],
39 );
40
41
42 # safety
43 __PACKAGE__->run_before('check_auth');
44
45 __PACKAGE__->run_before('recalc',
46                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print send_email) ]);
47
48 __PACKAGE__->run_before('get_unalterable_data',
49                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print send_email) ]);
50
51 #
52 # actions
53 #
54
55 # add a new order
56 sub action_add {
57   my ($self) = @_;
58
59   $self->order->transdate(DateTime->now_local());
60   my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval : 1;
61   $self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days)) if !$self->order->reqdate;
62
63   $self->pre_render();
64   $self->render(
65     'order/form',
66     title => $self->get_title_for('add'),
67     %{$self->{template_args}}
68   );
69 }
70
71 # edit an existing order
72 sub action_edit {
73   my ($self) = @_;
74
75   $self->load_order;
76   $self->recalc();
77   $self->pre_render();
78   $self->render(
79     'order/form',
80     title => $self->get_title_for('edit'),
81     %{$self->{template_args}}
82   );
83 }
84
85 # delete the order
86 sub action_delete {
87   my ($self) = @_;
88
89   my $errors = $self->delete();
90
91   if (scalar @{ $errors }) {
92     $self->js->flash('error', $_) foreach @{ $errors };
93     return $self->js->render();
94   }
95
96   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been deleted')
97            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been deleted')
98            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been deleted')
99            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been deleted')
100            : '';
101   flash_later('info', $text);
102
103   my @redirect_params = (
104     action => 'add',
105     type   => $self->type,
106   );
107
108   $self->redirect_to(@redirect_params);
109 }
110
111 # save the order
112 sub action_save {
113   my ($self) = @_;
114
115   my $errors = $self->save();
116
117   if (scalar @{ $errors }) {
118     $self->js->flash('error', $_) foreach @{ $errors };
119     return $self->js->render();
120   }
121
122   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been saved')
123            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been saved')
124            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been saved')
125            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
126            : '';
127   flash_later('info', $text);
128
129   my @redirect_params = (
130     action => 'edit',
131     type   => $self->type,
132     id     => $self->order->id,
133   );
134
135   $self->redirect_to(@redirect_params);
136 }
137
138 # save the order as new document an open it for edit
139 sub action_save_as_new {
140   my ($self) = @_;
141
142   my $order = $self->order;
143
144   if (!$order->id) {
145     $self->js->flash('error', t8('This object has not been saved yet.'));
146     return $self->js->render();
147   }
148
149   # load order from db to check if values changed
150   my $saved_order = SL::DB::Order->new(id => $order->id)->load;
151
152   my %new_attrs;
153   # Lets assign a new number if the user hasn't changed the previous one.
154   # If it has been changed manually then use it as-is.
155   $new_attrs{number}    = (trim($order->number) eq $saved_order->number)
156                         ? ''
157                         : trim($order->number);
158
159   # Clear transdate unless changed
160   $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
161                         ? DateTime->today_local
162                         : $order->transdate;
163
164   # Set new reqdate unless changed
165   if ($order->reqdate == $saved_order->reqdate) {
166     my $extra_days = $self->type eq sales_quotation_type() ? $::instance_conf->get_reqdate_interval : 1;
167     $new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
168   } else {
169     $new_attrs{reqdate} = $order->reqdate;
170   }
171
172   # Update employee
173   $new_attrs{employee}  = SL::DB::Manager::Employee->current;
174
175   # Create new record from current one
176   $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
177
178   # no linked records on save as new
179   delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
180
181   # save
182   $self->action_save();
183 }
184
185 # print the order
186 #
187 # This is called if "print" is pressed in the print dialog.
188 # If PDF creation was requested and succeeded, the pdf is stored in a session
189 # file and the filename is stored as session value with an unique key. A
190 # javascript function with this key is then called. This function calls the
191 # download action below (action_download_pdf), which offers the file for
192 # download.
193 sub action_print {
194   my ($self) = @_;
195
196   my $format      = $::form->{print_options}->{format};
197   my $media       = $::form->{print_options}->{media};
198   my $formname    = $::form->{print_options}->{formname};
199   my $copies      = $::form->{print_options}->{copies};
200   my $groupitems  = $::form->{print_options}->{groupitems};
201
202   # only pdf by now
203   if (none { $format eq $_ } qw(pdf)) {
204     return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
205   }
206
207   # only screen or printer by now
208   if (none { $media eq $_ } qw(screen printer)) {
209     return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
210   }
211
212   my $language;
213   $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
214
215   # create a form for generate_attachment_filename
216   my $form   = Form->new;
217   $form->{$self->nr_key()}  = $self->order->number;
218   $form->{type}             = $self->type;
219   $form->{format}           = $format;
220   $form->{formname}         = $formname;
221   $form->{language}         = '_' . $language->template_code if $language;
222   my $pdf_filename          = $form->generate_attachment_filename();
223
224   my $pdf;
225   my @errors = generate_pdf($self->order, \$pdf, { format     => $format,
226                                                    formname   => $formname,
227                                                    language   => $language,
228                                                    groupitems => $groupitems });
229   if (scalar @errors) {
230     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
231   }
232
233   if ($media eq 'screen') {
234     # screen/download
235     my $sfile = SL::SessionFile::Random->new(mode => "w");
236     $sfile->fh->print($pdf);
237     $sfile->fh->close;
238
239     my $key = join('_', Time::HiRes::gettimeofday(), int rand 1000000000000);
240     $::auth->set_session_value("Order::print-${key}" => $sfile->file_name);
241
242     $self->js
243     ->run('kivi.Order.download_pdf', $pdf_filename, $key)
244     ->flash('info', t8('The PDF has been created'));
245
246   } elsif ($media eq 'printer') {
247     # printer
248     my $printer_id = $::form->{print_options}->{printer_id};
249     SL::DB::Printer->new(id => $printer_id)->load->print_document(
250       copies  => $copies,
251       content => $pdf,
252     );
253
254     $self->js->flash('info', t8('The PDF has been printed'));
255   }
256
257   # copy file to webdav folder
258   if ($self->order->number && $::instance_conf->get_webdav_documents) {
259     my $webdav = SL::Webdav->new(
260       type     => $self->type,
261       number   => $self->order->number,
262     );
263     my $webdav_file = SL::Webdav::File->new(
264       webdav   => $webdav,
265       filename => $pdf_filename,
266     );
267     eval {
268       $webdav_file->store(data => \$pdf);
269       1;
270     } or do {
271       $self->js->flash('error', t8('Storing PDF to webdav folder failed: #1', $@));
272     }
273   }
274   if ($self->order->number && $::instance_conf->get_doc_storage) {
275     eval {
276       SL::File->save(object_id     => $self->order->id,
277                      object_type   => $self->type,
278                      mime_type     => 'application/pdf',
279                      source        => 'created',
280                      file_type     => 'document',
281                      file_name     => $pdf_filename,
282                      file_contents => $pdf);
283       1;
284     } or do {
285       $self->js->flash('error', t8('Storing PDF in storage backend failed: #1', $@));
286     }
287   }
288   $self->js->render;
289 }
290
291 # offer pdf for download
292 #
293 # It needs to get the key for the session value to get the pdf file.
294 sub action_download_pdf {
295   my ($self) = @_;
296
297   my $key = $::form->{key};
298   my $tmp_filename = $::auth->get_session_value("Order::print-${key}");
299   return $self->send_file(
300     $tmp_filename,
301     type => 'application/pdf',
302     name => $::form->{pdf_filename},
303   );
304 }
305
306 # open the email dialog
307 sub action_show_email_dialog {
308   my ($self) = @_;
309
310   my $cv_method = $self->cv;
311
312   if (!$self->order->$cv_method) {
313     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'))
314                     ->render($self);
315   }
316
317   my $email_form;
318   $email_form->{to}   = $self->order->contact->cp_email if $self->order->contact;
319   $email_form->{to} ||= $self->order->$cv_method->email;
320   $email_form->{cc}   = $self->order->$cv_method->cc;
321   $email_form->{bcc}  = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
322   # Todo: get addresses from shipto, if any
323
324   my $form = Form->new;
325   $form->{$self->nr_key()}  = $self->order->number;
326   $form->{formname}         = $self->type;
327   $form->{type}             = $self->type;
328   $form->{language}         = 'de';
329   $form->{format}           = 'pdf';
330
331   $email_form->{subject}             = $form->generate_email_subject();
332   $email_form->{attachment_filename} = $form->generate_attachment_filename();
333   $email_form->{message}             = $form->generate_email_body();
334   $email_form->{js_send_function}    = 'kivi.Order.send_email()';
335
336   my %files = $self->get_files_for_email_dialog();
337   my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
338                                   email_form  => $email_form,
339                                   show_bcc    => $::auth->assert('email_bcc', 'may fail'),
340                                   FILES       => \%files,
341                                   is_customer => $self->cv eq 'customer',
342   );
343
344   $self->js
345       ->run('kivi.Order.show_email_dialog', $dialog_html)
346       ->reinit_widgets
347       ->render($self);
348 }
349
350 # send email
351 #
352 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
353 sub action_send_email {
354   my ($self) = @_;
355
356   my $email_form  = delete $::form->{email_form};
357   my %field_names = (to => 'email');
358
359   $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
360
361   # for Form::cleanup which may be called in Form::send_email
362   $::form->{cwd}    = getcwd();
363   $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
364
365   $::form->{$_}     = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
366   $::form->{media}  = 'email';
367
368   if (($::form->{attachment_policy} // '') !~ m{^(?:old_file|no_file)$}) {
369     my $language;
370     $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
371
372     my $pdf;
373     my @errors = genereate_pdf($self->order, \$pdf, {media      => $::form->{media},
374                                                      format     => $::form->{print_options}->{format},
375                                                      formname   => $::form->{print_options}->{formname},
376                                                      language   => $language,
377                                                      groupitems => $::form->{print_options}->{groupitems}});
378     if (scalar @errors) {
379       return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render($self);
380     }
381
382     my $sfile = SL::SessionFile::Random->new(mode => "w");
383     $sfile->fh->print($pdf);
384     $sfile->fh->close;
385
386     $::form->{tmpfile} = $sfile->file_name;
387     $::form->{tmpdir}  = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
388   }
389
390   $::form->send_email(\%::myconfig, 'pdf');
391
392   # internal notes
393   my $intnotes = $self->order->intnotes;
394   $intnotes   .= "\n\n" if $self->order->intnotes;
395   $intnotes   .= t8('[email]')                                                                                        . "\n";
396   $intnotes   .= t8('Date')       . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
397   $intnotes   .= t8('To (email)') . ": " . $::form->{email}                                                           . "\n";
398   $intnotes   .= t8('Cc')         . ": " . $::form->{cc}                                                              . "\n"    if $::form->{cc};
399   $intnotes   .= t8('Bcc')        . ": " . $::form->{bcc}                                                             . "\n"    if $::form->{bcc};
400   $intnotes   .= t8('Subject')    . ": " . $::form->{subject}                                                         . "\n\n";
401   $intnotes   .= t8('Message')    . ": " . $::form->{message};
402
403   $self->js
404       ->val('#order_intnotes', $intnotes)
405       ->run('kivi.Order.close_email_dialog')
406       ->flash('info', t8('The email has been sent.'))
407       ->render($self);
408 }
409
410 # open the periodic invoices config dialog
411 #
412 # If there are values in the form (i.e. dialog was opened before),
413 # then use this values. Create new ones, else.
414 sub action_show_periodic_invoices_config_dialog {
415   my ($self) = @_;
416
417   my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
418   $config  ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
419   $config  ||= SL::DB::PeriodicInvoicesConfig->new(periodicity             => 'm',
420                                                    order_value_periodicity => 'p', # = same as periodicity
421                                                    start_date_as_date      => $::form->{transdate} || $::form->current_date,
422                                                    extend_automatically_by => 12,
423                                                    active                  => 1,
424                                                    email_subject           => GenericTranslations->get(
425                                                                                 language_id      => $::form->{language_id},
426                                                                                 translation_type =>"preset_text_periodic_invoices_email_subject"),
427                                                    email_body              => GenericTranslations->get(
428                                                                                 language_id      => $::form->{language_id},
429                                                                                 translation_type =>"preset_text_periodic_invoices_email_body"),
430   );
431   $config->periodicity('m')             if none { $_ eq $config->periodicity             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
432   $config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
433
434   $::form->get_lists(printers => "ALL_PRINTERS",
435                      charts   => { key       => 'ALL_CHARTS',
436                                    transdate => 'current_date' });
437
438   $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
439
440   if ($::form->{customer_id}) {
441     $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
442   }
443
444   $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
445                 popup_dialog             => 1,
446                 popup_js_close_function  => 'kivi.Order.close_periodic_invoices_config_dialog()',
447                 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
448                 config                   => $config,
449                 %$::form);
450 }
451
452 # assign the values of the periodic invoices config dialog
453 # as yaml in the hidden tag and set the status.
454 sub action_assign_periodic_invoices_config {
455   my ($self) = @_;
456
457   $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
458
459   my $config = { active                     => $::form->{active}       ? 1 : 0,
460                  terminated                 => $::form->{terminated}   ? 1 : 0,
461                  direct_debit               => $::form->{direct_debit} ? 1 : 0,
462                  periodicity                => (any { $_ eq $::form->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES)              ? $::form->{periodicity}             : 'm',
463                  order_value_periodicity    => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
464                  start_date_as_date         => $::form->{start_date_as_date},
465                  end_date_as_date           => $::form->{end_date_as_date},
466                  first_billing_date_as_date => $::form->{first_billing_date_as_date},
467                  print                      => $::form->{print}      ? 1                         : 0,
468                  printer_id                 => $::form->{print}      ? $::form->{printer_id} * 1 : undef,
469                  copies                     => $::form->{copies} * 1 ? $::form->{copies}         : 1,
470                  extend_automatically_by    => $::form->{extend_automatically_by}    * 1 || undef,
471                  ar_chart_id                => $::form->{ar_chart_id} * 1,
472                  send_email                 => $::form->{send_email} ? 1 : 0,
473                  email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
474                  email_recipient_address    => $::form->{email_recipient_address},
475                  email_sender               => $::form->{email_sender},
476                  email_subject              => $::form->{email_subject},
477                  email_body                 => $::form->{email_body},
478                };
479
480   my $periodic_invoices_config = YAML::Dump($config);
481
482   my $status = $self->get_periodic_invoices_status($config);
483
484   $self->js
485     ->remove('#order_periodic_invoices_config')
486     ->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
487     ->run('kivi.Order.close_periodic_invoices_config_dialog')
488     ->html('#periodic_invoices_status', $status)
489     ->flash('info', t8('The periodic invoices config has been assigned.'))
490     ->render($self);
491 }
492
493 sub action_get_has_active_periodic_invoices {
494   my ($self) = @_;
495
496   my $config = make_periodic_invoices_config_from_yaml(delete $::form->{config});
497   $config  ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
498
499   my $has_active_periodic_invoices =
500        $self->type eq sales_order_type()
501     && $config
502     && $config->active
503     && (!$config->end_date || ($config->end_date > DateTime->today_local))
504     && $config->get_previous_billed_period_start_date;
505
506   $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
507 }
508
509 # save the order and redirect to the frontend subroutine for a new
510 # delivery order
511 sub action_save_and_delivery_order {
512   my ($self) = @_;
513
514   my $errors = $self->save();
515
516   if (scalar @{ $errors }) {
517     $self->js->flash('error', $_) foreach @{ $errors };
518     return $self->js->render();
519   }
520
521   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been saved')
522            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been saved')
523            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been saved')
524            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
525            : '';
526   flash_later('info', $text);
527
528   my @redirect_params = (
529     controller => 'oe.pl',
530     action     => 'oe_delivery_order_from_order',
531     id         => $self->order->id,
532   );
533
534   $self->redirect_to(@redirect_params);
535 }
536
537 # save the order and redirect to the frontend subroutine for a new
538 # invoice
539 sub action_save_and_invoice {
540   my ($self) = @_;
541
542   my $errors = $self->save();
543
544   if (scalar @{ $errors }) {
545     $self->js->flash('error', $_) foreach @{ $errors };
546     return $self->js->render();
547   }
548
549   my $text = $self->type eq sales_order_type()       ? $::locale->text('The order has been saved')
550            : $self->type eq purchase_order_type()    ? $::locale->text('The order has been saved')
551            : $self->type eq sales_quotation_type()   ? $::locale->text('The quotation has been saved')
552            : $self->type eq request_quotation_type() ? $::locale->text('The rfq has been saved')
553            : '';
554   flash_later('info', $text);
555
556   my @redirect_params = (
557     controller => 'oe.pl',
558     action     => 'oe_invoice_from_order',
559     id         => $self->order->id,
560   );
561
562   $self->redirect_to(@redirect_params);
563 }
564
565 # workflow from sales quotation to sales order
566 sub action_sales_order {
567   $_[0]->workflow_sales_or_purchase_order();
568 }
569
570 # workflow from rfq to purchase order
571 sub action_purchase_order {
572   $_[0]->workflow_sales_or_purchase_order();
573 }
574
575 # set form elements in respect to a changed customer or vendor
576 #
577 # This action is called on an change of the customer/vendor picker.
578 sub action_customer_vendor_changed {
579   my ($self) = @_;
580
581   setup_order_from_cv($self->order);
582   $self->recalc();
583
584   my $cv_method = $self->cv;
585
586   if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
587     $self->js->show('#cp_row');
588   } else {
589     $self->js->hide('#cp_row');
590   }
591
592   if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
593     $self->js->show('#shipto_row');
594   } else {
595     $self->js->hide('#shipto_row');
596   }
597
598   $self->js->val( '#order_salesman_id',      $self->order->salesman_id)        if $self->order->is_sales;
599
600   $self->js
601     ->replaceWith('#order_cp_id',            $self->build_contact_select)
602     ->replaceWith('#order_shipto_id',        $self->build_shipto_select)
603     ->replaceWith('#business_info_row',      $self->build_business_info_row)
604     ->val(        '#order_taxzone_id',       $self->order->taxzone_id)
605     ->val(        '#order_taxincluded',      $self->order->taxincluded)
606     ->val(        '#order_payment_id',       $self->order->payment_id)
607     ->val(        '#order_delivery_term_id', $self->order->delivery_term_id)
608     ->val(        '#order_intnotes',         $self->order->intnotes)
609     ->focus(      '#order_' . $self->cv . '_id');
610
611   $self->js_redisplay_amounts_and_taxes;
612   $self->js->render();
613 }
614
615 # open the dialog for customer/vendor details
616 sub action_show_customer_vendor_details_dialog {
617   my ($self) = @_;
618
619   my $is_customer = 'customer' eq $::form->{vc};
620   my $cv;
621   if ($is_customer) {
622     $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
623   } else {
624     $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
625   }
626
627   my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
628   $details{discount_as_percent} = $cv->discount_as_percent;
629   $details{creditlimt}          = $cv->creditlimit_as_number;
630   $details{business}            = $cv->business->description      if $cv->business;
631   $details{language}            = $cv->language_obj->description  if $cv->language_obj;
632   $details{delivery_terms}      = $cv->delivery_term->description if $cv->delivery_term;
633   $details{payment_terms}       = $cv->payment->description       if $cv->payment;
634   $details{pricegroup}          = $cv->pricegroup->pricegroup     if $is_customer && $cv->pricegroup;
635
636   foreach my $entry (@{ $cv->shipto }) {
637     push @{ $details{SHIPTO} },   { map { $_ => $entry->$_ } @{$entry->meta->columns} };
638   }
639   foreach my $entry (@{ $cv->contacts }) {
640     push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
641   }
642
643   $_[0]->render('common/show_vc_details', { layout => 0 },
644                 is_customer => $is_customer,
645                 %details);
646
647 }
648
649 # called if a unit in an existing item row is changed
650 sub action_unit_changed {
651   my ($self) = @_;
652
653   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
654   my $item = $self->order->items_sorted->[$idx];
655
656   my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
657   $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
658
659   $self->recalc();
660
661   $self->js
662     ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
663   $self->js_redisplay_line_values;
664   $self->js_redisplay_amounts_and_taxes;
665   $self->js->render();
666 }
667
668 # add an item row for a new item entered in the input row
669 sub action_add_item {
670   my ($self) = @_;
671
672   my $form_attr = $::form->{add_item};
673
674   return unless $form_attr->{parts_id};
675
676   my $item = new_item($self->order, $form_attr);
677
678   $self->order->add_items($item);
679
680   $self->recalc();
681
682   my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
683   my $row_as_html = $self->p->render('order/tabs/_row',
684                                      ITEM              => $item,
685                                      ID                => $item_id,
686                                      TYPE              => $self->type,
687                                      ALL_PRICE_FACTORS => $self->all_price_factors
688   );
689
690   $self->js
691     ->append('#row_table_id', $row_as_html);
692
693   if ( $item->part->is_assortment ) {
694     $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
695     foreach my $assortment_item ( @{$item->part->assortment_items} ) {
696       my $attr = { parts_id => $assortment_item->parts_id,
697                    qty      => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
698                    unit     => $assortment_item->unit,
699                    description => $assortment_item->part->description,
700                  };
701       my $item = new_item($self->order, $attr);
702
703       # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
704       $item->discount(1) unless $assortment_item->charge;
705
706       $self->order->add_items( $item );
707       $self->recalc();
708       my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
709       my $row_as_html = $self->p->render('order/tabs/_row',
710                                          ITEM              => $item,
711                                          ID                => $item_id,
712                                          TYPE              => $self->type,
713                                          ALL_PRICE_FACTORS => $self->all_price_factors
714       );
715       $self->js
716         ->append('#row_table_id', $row_as_html);
717     };
718   };
719
720   $self->js
721     ->val('.add_item_input', '')
722     ->run('kivi.Order.init_row_handlers')
723     ->run('kivi.Order.row_table_scroll_down')
724     ->run('kivi.Order.renumber_positions')
725     ->focus('#add_item_parts_id_name');
726
727   $self->js_redisplay_amounts_and_taxes;
728   $self->js->render();
729 }
730
731 # open the dialog for entering multiple items at once
732 sub action_show_multi_items_dialog {
733   $_[0]->render('order/tabs/_multi_items_dialog', { layout => 0 },
734                 all_partsgroups => SL::DB::Manager::PartsGroup->get_all);
735 }
736
737 # update the filter results in the multi item dialog
738 sub action_multi_items_update_result {
739   my $max_count = 100;
740
741   $::form->{multi_items}->{filter}->{obsolete} = 0;
742
743   my $count = $_[0]->multi_items_models->count;
744
745   if ($count == 0) {
746     my $text = SL::Presenter::EscapedText->new(text => $::locale->text('No results.'));
747     $_[0]->render($text, { layout => 0 });
748   } elsif ($count > $max_count) {
749     my $text = SL::Presenter::EscapedText->new(text => $::locale->text('Too many results (#1 from #2).', $count, $max_count));
750     $_[0]->render($text, { layout => 0 });
751   } else {
752     my $multi_items = $_[0]->multi_items_models->get;
753     $_[0]->render('order/tabs/_multi_items_result', { layout => 0 },
754                   multi_items => $multi_items);
755   }
756 }
757
758 # add item rows for multiple items at once
759 sub action_add_multi_items {
760   my ($self) = @_;
761
762   my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_multi_items} };
763   return $self->js->render() unless scalar @form_attr;
764
765   my @items;
766   foreach my $attr (@form_attr) {
767     my $item = new_item($self->order, $attr);
768     push @items, $item;
769     if ( $item->part->is_assortment ) {
770       foreach my $assortment_item ( @{$item->part->assortment_items} ) {
771         my $attr = { parts_id => $assortment_item->parts_id,
772                      qty      => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
773                      unit     => $assortment_item->unit,
774                      description => $assortment_item->part->description,
775                    };
776         my $item = new_item($self->order, $attr);
777
778         # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
779         $item->discount(1) unless $assortment_item->charge;
780         push @items, $item;
781       }
782     }
783   }
784   $self->order->add_items(@items);
785
786   $self->recalc();
787
788   foreach my $item (@items) {
789     my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
790     my $row_as_html = $self->p->render('order/tabs/_row',
791                                        ITEM              => $item,
792                                        ID                => $item_id,
793                                        TYPE              => $self->type,
794                                        ALL_PRICE_FACTORS => $self->all_price_factors
795     );
796
797     $self->js->append('#row_table_id', $row_as_html);
798   }
799
800   $self->js
801     ->run('kivi.Order.close_multi_items_dialog')
802     ->run('kivi.Order.init_row_handlers')
803     ->run('kivi.Order.row_table_scroll_down')
804     ->run('kivi.Order.renumber_positions')
805     ->focus('#add_item_parts_id_name');
806
807   $self->js_redisplay_amounts_and_taxes;
808   $self->js->render();
809 }
810
811 # recalculate all linetotals, amounts and taxes and redisplay them
812 sub action_recalc_amounts_and_taxes {
813   my ($self) = @_;
814
815   $self->recalc();
816
817   $self->js_redisplay_line_values;
818   $self->js_redisplay_amounts_and_taxes;
819   $self->js->render();
820 }
821
822 # redisplay item rows if they are sorted by an attribute
823 sub action_reorder_items {
824   my ($self) = @_;
825
826   my %sort_keys = (
827     partnumber  => sub { $_[0]->part->partnumber },
828     description => sub { $_[0]->description },
829     qty         => sub { $_[0]->qty },
830     sellprice   => sub { $_[0]->sellprice },
831     discount    => sub { $_[0]->discount },
832   );
833
834   my $method = $sort_keys{$::form->{order_by}};
835   my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
836   if ($::form->{sort_dir}) {
837     @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
838   } else {
839     @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
840   }
841   $self->js
842     ->run('kivi.Order.redisplay_items', \@to_sort)
843     ->render;
844 }
845
846 # show the popup to choose a price/discount source
847 sub action_price_popup {
848   my ($self) = @_;
849
850   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
851   my $item = $self->order->items_sorted->[$idx];
852
853   $self->render_price_dialog($item);
854 }
855
856 # get the longdescription for an item if the dialog to enter/change the
857 # longdescription was opened and the longdescription is empty
858 #
859 # If this item is new, get the longdescription from Part.
860 # Otherwise get it from OrderItem.
861 sub action_get_item_longdescription {
862   my $longdescription;
863
864   if ($::form->{item_id}) {
865     $longdescription = SL::DB::OrderItem->new(id => $::form->{item_id})->load->longdescription;
866   } elsif ($::form->{parts_id}) {
867     $longdescription = SL::DB::Part->new(id => $::form->{parts_id})->load->notes;
868   }
869   $_[0]->render(\ $longdescription, { type => 'text' });
870 }
871
872 # load the second row for one or more items
873 #
874 # This action gets the html code for all items second rows by rendering a template for
875 # the second row and sets the html code via client js.
876 sub action_load_second_rows {
877   my ($self) = @_;
878
879   $self->recalc() if $self->order->is_sales; # for margin calculation
880
881   foreach my $item_id (@{ $::form->{item_ids} }) {
882     my $idx  = first_index { $_ eq $item_id } @{ $::form->{orderitem_ids} };
883     my $item = $self->order->items_sorted->[$idx];
884
885     $self->js_load_second_row($item, $item_id, 0);
886   }
887
888   $self->js->run('kivi.Order.init_row_handlers') if $self->order->is_sales; # for lastcosts change-callback
889
890   $self->js->render();
891 }
892
893 sub js_load_second_row {
894   my ($self, $item, $item_id, $do_parse) = @_;
895
896   if ($do_parse) {
897     # Parse values from form (they are formated while rendering (template)).
898     # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
899     # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
900     foreach my $var (@{ $item->cvars_by_config }) {
901       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
902     }
903     $item->parse_custom_variable_values;
904   }
905
906   my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item, TYPE => $self->type);
907
908   $self->js
909     ->html('.row_entry:has(#item_' . $item_id . ') [name = "second_row"]', $row_as_html)
910     ->data('.row_entry:has(#item_' . $item_id . ') [name = "second_row"]', 'loaded', 1);
911 }
912
913 sub js_redisplay_line_values {
914   my ($self) = @_;
915
916   my $is_sales = $self->order->is_sales;
917
918   # sales orders with margins
919   my @data;
920   if ($is_sales) {
921     @data = map {
922       [
923        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
924        $::form->format_amount(\%::myconfig, $_->{marge_total},   2, 0),
925        $::form->format_amount(\%::myconfig, $_->{marge_percent}, 2, 0),
926       ]} @{ $self->order->items_sorted };
927   } else {
928     @data = map {
929       [
930        $::form->format_amount(\%::myconfig, $_->{linetotal},     2, 0),
931       ]} @{ $self->order->items_sorted };
932   }
933
934   $self->js
935     ->run('kivi.Order.redisplay_line_values', $is_sales, \@data);
936 }
937
938 sub js_redisplay_amounts_and_taxes {
939   my ($self) = @_;
940
941   if (scalar @{ $self->{taxes} }) {
942     $self->js->show('#taxincluded_row_id');
943   } else {
944     $self->js->hide('#taxincluded_row_id');
945   }
946
947   if ($self->order->taxincluded) {
948     $self->js->hide('#subtotal_row_id');
949   } else {
950     $self->js->show('#subtotal_row_id');
951   }
952
953   $self->js
954     ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
955     ->html('#amount_id',    $::form->format_amount(\%::myconfig, $self->order->amount,    -2))
956     ->remove('.tax_row')
957     ->insertBefore($self->build_tax_rows, '#amount_row_id');
958 }
959
960 #
961 # helpers
962 #
963
964 sub init_valid_types {
965   [ sales_order_type(), purchase_order_type(), sales_quotation_type(), request_quotation_type() ];
966 }
967
968 sub init_type {
969   my ($self) = @_;
970
971   if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
972     die "Not a valid type for order";
973   }
974
975   $self->type($::form->{type});
976 }
977
978 sub init_cv {
979   my ($self) = @_;
980
981   my $cv = (any { $self->type eq $_ } (sales_order_type(),    sales_quotation_type()))   ? 'customer'
982          : (any { $self->type eq $_ } (purchase_order_type(), request_quotation_type())) ? 'vendor'
983          : die "Not a valid type for order";
984
985   return $cv;
986 }
987
988 sub init_p {
989   SL::Presenter->get;
990 }
991
992 sub init_order {
993   $_[0]->make_order;
994 }
995
996 # model used to filter/display the parts in the multi-items dialog
997 sub init_multi_items_models {
998   SL::Controller::Helper::GetModels->new(
999     controller     => $_[0],
1000     model          => 'Part',
1001     with_objects   => [ qw(unit_obj) ],
1002     disable_plugin => 'paginated',
1003     source         => $::form->{multi_items},
1004     sorted         => {
1005       _default    => {
1006         by  => 'partnumber',
1007         dir => 1,
1008       },
1009       partnumber  => t8('Partnumber'),
1010       description => t8('Description')}
1011   );
1012 }
1013
1014 sub init_all_price_factors {
1015   SL::DB::Manager::PriceFactor->get_all;
1016 }
1017
1018 sub check_auth {
1019   my ($self) = @_;
1020
1021   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
1022
1023   my $right   = $right_for->{ $self->type };
1024   $right    ||= 'DOES_NOT_EXIST';
1025
1026   $::auth->assert($right);
1027 }
1028
1029 # build the selection box for contacts
1030 #
1031 # Needed, if customer/vendor changed.
1032 sub build_contact_select {
1033   my ($self) = @_;
1034
1035   select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
1036     value_key  => 'cp_id',
1037     title_key  => 'full_name_dep',
1038     default    => $self->order->cp_id,
1039     with_empty => 1,
1040     style      => 'width: 300px',
1041   );
1042 }
1043
1044 # build the selection box for shiptos
1045 #
1046 # Needed, if customer/vendor changed.
1047 sub build_shipto_select {
1048   my ($self) = @_;
1049
1050   select_tag('order.shipto_id', [ $self->order->{$self->cv}->shipto ],
1051     value_key  => 'shipto_id',
1052     title_key  => 'displayable_id',
1053     default    => $self->order->shipto_id,
1054     with_empty => 1,
1055     style      => 'width: 300px',
1056   );
1057 }
1058
1059 # render the info line for business
1060 #
1061 # Needed, if customer/vendor changed.
1062 sub build_business_info_row
1063 {
1064   $_[0]->p->render('order/tabs/_business_info_row', SELF => $_[0]);
1065 }
1066
1067 # build the rows for displaying taxes
1068 #
1069 # Called if amounts where recalculated and redisplayed.
1070 sub build_tax_rows {
1071   my ($self) = @_;
1072
1073   my $rows_as_html;
1074   foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
1075     $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
1076   }
1077   return $rows_as_html;
1078 }
1079
1080
1081 sub render_price_dialog {
1082   my ($self, $record_item) = @_;
1083
1084   my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
1085
1086   $self->js
1087     ->run(
1088       'kivi.io.price_chooser_dialog',
1089       t8('Available Prices'),
1090       $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
1091     )
1092     ->reinit_widgets;
1093
1094 #   if (@errors) {
1095 #     $self->js->text('#dialog_flash_error_content', join ' ', @errors);
1096 #     $self->js->show('#dialog_flash_error');
1097 #   }
1098
1099   $self->js->render;
1100 }
1101
1102 sub load_order {
1103   my ($self) = @_;
1104
1105   return if !$::form->{id};
1106
1107   $self->order(SL::DB::Order->new(id => $::form->{id})->load);
1108 }
1109
1110 # load or create a new order object
1111 #
1112 # And assign changes from the form to this object.
1113 # If the order is loaded from db, check if items are deleted in the form,
1114 # remove them form the object and collect them for removing from db on saving.
1115 # Then create/update items from form (via make_item) and add them.
1116 sub make_order {
1117   my ($self) = @_;
1118
1119   # add_items adds items to an order with no items for saving, but they cannot
1120   # be retrieved via items until the order is saved. Adding empty items to new
1121   # order here solves this problem.
1122   my $order;
1123   $order   = SL::DB::Manager::Order->find_by(id => $::form->{id}) if $::form->{id};
1124   $order ||= SL::DB::Order->new(orderitems => [],
1125                                 quotation  => (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type())));
1126
1127   my $cv_id_method = $self->cv . '_id';
1128   if (!$::form->{id} && $::form->{$cv_id_method}) {
1129     $order->$cv_id_method($::form->{$cv_id_method});
1130     setup_order_from_cv($order);
1131   }
1132
1133   my $form_orderitems               = delete $::form->{order}->{orderitems};
1134   my $form_periodic_invoices_config = delete $::form->{order}->{periodic_invoices_config};
1135
1136   $order->assign_attributes(%{$::form->{order}});
1137
1138   my $periodic_invoices_config = make_periodic_invoices_config_from_yaml($form_periodic_invoices_config);
1139   $order->periodic_invoices_config($periodic_invoices_config) if $periodic_invoices_config;
1140
1141   # remove deleted items
1142   $self->item_ids_to_delete([]);
1143   foreach my $idx (reverse 0..$#{$order->orderitems}) {
1144     my $item = $order->orderitems->[$idx];
1145     if (none { $item->id == $_->{id} } @{$form_orderitems}) {
1146       splice @{$order->orderitems}, $idx, 1;
1147       push @{$self->item_ids_to_delete}, $item->id;
1148     }
1149   }
1150
1151   my @items;
1152   my $pos = 1;
1153   foreach my $form_attr (@{$form_orderitems}) {
1154     my $item = make_item($order, $form_attr);
1155     $item->position($pos);
1156     push @items, $item;
1157     $pos++;
1158   }
1159   $order->add_items(grep {!$_->id} @items);
1160
1161   return $order;
1162 }
1163
1164 # create or update items from form
1165 #
1166 # Make item objects from form values. For items already existing read from db.
1167 # Create a new item else. And assign attributes.
1168 sub make_item {
1169   my ($record, $attr) = @_;
1170
1171   my $item;
1172   $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
1173
1174   my $is_new = !$item;
1175
1176   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1177   # they cannot be retrieved via custom_variables until the order/orderitem is
1178   # saved. Adding empty custom_variables to new orderitem here solves this problem.
1179   $item ||= SL::DB::OrderItem->new(custom_variables => []);
1180
1181   $item->assign_attributes(%$attr);
1182   $item->longdescription($item->part->notes)                     if $is_new && !defined $attr->{longdescription};
1183   $item->project_id($record->globalproject_id)                   if $is_new && !defined $attr->{project_id};
1184   $item->lastcost($record->is_sales ? $item->part->lastcost : 0) if $is_new && !defined $attr->{lastcost_as_number};
1185
1186   return $item;
1187 }
1188
1189 # create a new item
1190 #
1191 # This is used to add one item
1192 sub new_item {
1193   my ($record, $attr) = @_;
1194
1195   my $item = SL::DB::OrderItem->new;
1196
1197   # Remove attributes where the user left or set the inputs empty.
1198   # So these attributes will be undefined and we can distinguish them
1199   # from zero later on.
1200   for (qw(qty_as_number sellprice_as_number discount_as_percent)) {
1201     delete $attr->{$_} if $attr->{$_} eq '';
1202   }
1203
1204   $item->assign_attributes(%$attr);
1205
1206   my $part         = SL::DB::Part->new(id => $attr->{parts_id})->load;
1207   my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
1208
1209   $item->unit($part->unit) if !$item->unit;
1210
1211   my $price_src;
1212   if ( $part->is_assortment ) {
1213     # add assortment items with price 0, as the components carry the price
1214     $price_src = $price_source->price_from_source("");
1215     $price_src->price(0);
1216   } elsif (defined $item->sellprice) {
1217     $price_src = $price_source->price_from_source("");
1218     $price_src->price($item->sellprice);
1219   } else {
1220     $price_src = $price_source->best_price
1221            ? $price_source->best_price
1222            : $price_source->price_from_source("");
1223     $price_src->price(0) if !$price_source->best_price;
1224   }
1225
1226   my $discount_src;
1227   if (defined $item->discount) {
1228     $discount_src = $price_source->discount_from_source("");
1229     $discount_src->discount($item->discount);
1230   } else {
1231     $discount_src = $price_source->best_discount
1232                   ? $price_source->best_discount
1233                   : $price_source->discount_from_source("");
1234     $discount_src->discount(0) if !$price_source->best_discount;
1235   }
1236
1237   my %new_attr;
1238   $new_attr{part}                   = $part;
1239   $new_attr{description}            = $part->description     if ! $item->description;
1240   $new_attr{qty}                    = 1.0                    if ! $item->qty;
1241   $new_attr{price_factor_id}        = $part->price_factor_id if ! $item->price_factor_id;
1242   $new_attr{sellprice}              = $price_src->price;
1243   $new_attr{discount}               = $discount_src->discount;
1244   $new_attr{active_price_source}    = $price_src;
1245   $new_attr{active_discount_source} = $discount_src;
1246   $new_attr{longdescription}        = $part->notes           if ! defined $attr->{longdescription};
1247   $new_attr{project_id}             = $record->globalproject_id;
1248   $new_attr{lastcost}               = $record->is_sales ? $part->lastcost : 0;
1249
1250   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1251   # they cannot be retrieved via custom_variables until the order/orderitem is
1252   # saved. Adding empty custom_variables to new orderitem here solves this problem.
1253   $new_attr{custom_variables} = [];
1254
1255   $item->assign_attributes(%new_attr);
1256
1257   return $item;
1258 }
1259
1260 sub setup_order_from_cv {
1261   my ($order) = @_;
1262
1263   $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id));
1264
1265   $order->intnotes($order->customervendor->notes);
1266
1267   if ($order->is_sales) {
1268     $order->salesman_id($order->customer->salesman_id);
1269     $order->taxincluded(defined($order->customer->taxincluded_checked)
1270                         ? $order->customer->taxincluded_checked
1271                         : $::myconfig{taxincluded_checked});
1272   }
1273
1274 }
1275
1276 # recalculate prices and taxes
1277 #
1278 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1279 sub recalc {
1280   my ($self) = @_;
1281
1282   # bb: todo: currency later
1283   $self->order->currency_id($::instance_conf->get_currency_id());
1284
1285   my %pat = $self->order->calculate_prices_and_taxes();
1286   $self->{taxes} = [];
1287   foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
1288     my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
1289
1290     my @amount_keys = grep { $pat{amounts}->{$_}->{tax_id} == $tax->id } keys %{ $pat{amounts} };
1291     push(@{ $self->{taxes} }, { amount    => $pat{taxes}->{$tax_chart_id},
1292                                 netamount => $pat{amounts}->{$amount_keys[0]}->{amount},
1293                                 tax       => $tax });
1294   }
1295
1296   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
1297 }
1298
1299 # get data for saving, printing, ..., that is not changed in the form
1300 #
1301 # Only cvars for now.
1302 sub get_unalterable_data {
1303   my ($self) = @_;
1304
1305   foreach my $item (@{ $self->order->items }) {
1306     # autovivify all cvars that are not in the form (cvars_by_config can do it).
1307     # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1308     foreach my $var (@{ $item->cvars_by_config }) {
1309       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1310     }
1311     $item->parse_custom_variable_values;
1312   }
1313 }
1314
1315 # delete the order
1316 #
1317 # And remove related files in the spool directory
1318 sub delete {
1319   my ($self) = @_;
1320
1321   my $errors = [];
1322   my $db     = $self->order->db;
1323
1324   $db->with_transaction(
1325     sub {
1326       my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
1327       $self->order->delete;
1328       my $spool = $::lx_office_conf{paths}->{spool};
1329       unlink map { "$spool/$_" } @spoolfiles if $spool;
1330
1331       1;
1332   }) || push(@{$errors}, $db->error);
1333
1334   return $errors;
1335 }
1336
1337 # save the order
1338 #
1339 # And delete items that are deleted in the form.
1340 sub save {
1341   my ($self) = @_;
1342
1343   my $errors = [];
1344   my $db     = $self->order->db;
1345
1346   $db->with_transaction(sub {
1347     SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete};
1348     $self->order->save(cascade => 1);
1349
1350     # link records
1351     if ($::form->{converted_from_oe_id}) {
1352       SL::DB::Order->new(id => $::form->{converted_from_oe_id})->load->link_to_record($self->order);
1353
1354       if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1355         my $idx = 0;
1356         foreach (@{ $self->order->items_sorted }) {
1357           my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1358           next if !$from_id;
1359           SL::DB::RecordLink->new(from_table => 'orderitems',
1360                                   from_id    => $from_id,
1361                                   to_table   => 'orderitems',
1362                                   to_id      => $_->id
1363           )->save;
1364           $idx++;
1365         }
1366       }
1367     }
1368     1;
1369   }) || push(@{$errors}, $db->error);
1370
1371   return $errors;
1372 }
1373
1374 sub workflow_sales_or_purchase_order {
1375   my ($self) = @_;
1376
1377   my $destination_type = $::form->{type} eq sales_quotation_type()   ? sales_order_type()
1378                        : $::form->{type} eq request_quotation_type() ? purchase_order_type()
1379                        : $::form->{type} eq purchase_order_type()    ? sales_order_type()
1380                        : $::form->{type} eq sales_order_type()       ? purchase_order_type()
1381                        : '';
1382
1383   $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1384   $self->{converted_from_oe_id} = delete $::form->{id};
1385
1386   # set item ids to new fake id, to identify them as new items
1387   foreach my $item (@{$self->order->items_sorted}) {
1388     $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1389   }
1390
1391   # change form type
1392   $::form->{type} = $destination_type;
1393   $self->type($self->init_type);
1394   $self->cv  ($self->init_cv);
1395   $self->check_auth;
1396
1397   $self->recalc();
1398   $self->get_unalterable_data();
1399   $self->pre_render();
1400
1401   # trigger rendering values for second row/longdescription as hidden,
1402   # because they are loaded only on demand. So we need to keep the values
1403   # from the source.
1404   $_->{render_second_row}      = 1 for @{ $self->order->items_sorted };
1405   $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1406
1407   $self->render(
1408     'order/form',
1409     title => $self->get_title_for('edit'),
1410     %{$self->{template_args}}
1411   );
1412 }
1413
1414
1415 sub pre_render {
1416   my ($self) = @_;
1417
1418   $self->{all_taxzones}             = SL::DB::Manager::TaxZone->get_all_sorted();
1419   $self->{all_departments}          = SL::DB::Manager::Department->get_all_sorted();
1420   $self->{all_employees}            = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1421                                                                                             deleted => 0 ] ],
1422                                                                          sort_by => 'name');
1423   $self->{all_salesmen}             = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1424                                                                                             deleted => 0 ] ],
1425                                                                          sort_by => 'name');
1426   $self->{all_payment_terms}        = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1427                                                                                                       obsolete => 0 ] ]);
1428   $self->{all_delivery_terms}       = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1429   $self->{current_employee_id}      = SL::DB::Manager::Employee->current->id;
1430   $self->{periodic_invoices_status} = $self->get_periodic_invoices_status($self->order->periodic_invoices_config);
1431   $self->{order_probabilities}      = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
1432
1433   my $print_form = Form->new('');
1434   $print_form->{type}      = $self->type;
1435   $print_form->{printers}  = SL::DB::Manager::Printer->get_all_sorted;
1436   $print_form->{languages} = SL::DB::Manager::Language->get_all_sorted;
1437   $self->{print_options}   = SL::Helper::PrintOptions->get_print_options(
1438     form => $print_form,
1439     options => {dialog_name_prefix => 'print_options.',
1440                 show_headers       => 1,
1441                 no_queue           => 1,
1442                 no_postscript      => 1,
1443                 no_opendocument    => 1,
1444                 no_html            => 1},
1445   );
1446
1447   foreach my $item (@{$self->order->orderitems}) {
1448     my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1449     $item->active_price_source(   $price_source->price_from_source(   $item->active_price_source   ));
1450     $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
1451   }
1452
1453   if ($self->order->number && $::instance_conf->get_webdav) {
1454     my $webdav = SL::Webdav->new(
1455       type     => $self->type,
1456       number   => $self->order->number,
1457     );
1458     my @all_objects = $webdav->get_all_objects;
1459     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1460                                                     type => t8('File'),
1461                                                     link => File::Spec->catfile($_->full_filedescriptor),
1462                                                 } } @all_objects;
1463   }
1464
1465   $::request->{layout}->use_javascript("${_}.js") for qw(kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery edit_periodic_invoices_config calculate_qty);
1466   $self->setup_edit_action_bar;
1467 }
1468
1469 sub setup_edit_action_bar {
1470   my ($self, %params) = @_;
1471
1472   my $deletion_allowed = (any { $self->type eq $_ } (sales_quotation_type(), request_quotation_type()))
1473                       || (($self->type eq sales_order_type())    && $::instance_conf->get_sales_order_show_delete)
1474                       || (($self->type eq purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);
1475
1476   for my $bar ($::request->layout->get('actionbar')) {
1477     $bar->add(
1478       combobox => [
1479         action => [
1480           t8('Save'),
1481           call      => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
1482                                                     $::instance_conf->get_order_warn_no_deliverydate,
1483                                                                                                       ],
1484           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1485         ],
1486         action => [
1487           t8('Save as new'),
1488           call      => [ 'kivi.Order.save', 'save_as_new', $::instance_conf->get_order_warn_duplicate_parts ],
1489           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1490           disabled  => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1491         ],
1492         action => [
1493           t8('Save and Delivery Order'),
1494           call      => [ 'kivi.Order.save', 'save_and_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
1495                                                                        $::instance_conf->get_order_warn_no_deliverydate,
1496                                                                                                                         ],
1497           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1498           only_if   => (any { $self->type eq $_ } (sales_order_type(), purchase_order_type()))
1499         ],
1500         action => [
1501           t8('Save and Invoice'),
1502           call      => [ 'kivi.Order.save', 'save_and_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
1503           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1504         ],
1505       ], # end of combobox "Save"
1506
1507       combobox => [
1508         action => [
1509           t8('Workflow'),
1510         ],
1511         action => [
1512           t8('Sales Order'),
1513           submit   => [ '#order_form', { action => "Order/sales_order" } ],
1514           only_if  => (any { $self->type eq $_ } (sales_quotation_type(), purchase_order_type())),
1515           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1516         ],
1517         action => [
1518           t8('Purchase Order'),
1519           submit   => [ '#order_form', { action => "Order/purchase_order" } ],
1520           only_if  => (any { $self->type eq $_ } (sales_order_type(), request_quotation_type())),
1521           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1522         ],
1523       ], # end of combobox "Workflow"
1524
1525       combobox => [
1526         action => [
1527           t8('Export'),
1528         ],
1529         action => [
1530           t8('Print'),
1531           call => [ 'kivi.Order.show_print_options' ],
1532         ],
1533         action => [
1534           t8('E-mail'),
1535           call => [ 'kivi.Order.email' ],
1536         ],
1537         action => [
1538           t8('Download attachments of all parts'),
1539           call     => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
1540           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1541           only_if  => $::instance_conf->get_doc_storage,
1542         ],
1543       ], # end of combobox "Export"
1544
1545       action => [
1546         t8('Delete'),
1547         call     => [ 'kivi.Order.delete_order' ],
1548         confirm  => $::locale->text('Do you really want to delete this object?'),
1549         disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1550         only_if  => $deletion_allowed,
1551       ],
1552     );
1553   }
1554 }
1555
1556 sub generate_pdf {
1557   my ($order, $pdf_ref, $params) = @_;
1558
1559   my @errors = ();
1560
1561   my $print_form = Form->new('');
1562   $print_form->{type}        = $order->type;
1563   $print_form->{formname}    = $params->{formname} || $order->type;
1564   $print_form->{format}      = $params->{format}   || 'pdf';
1565   $print_form->{media}       = $params->{media}    || 'file';
1566   $print_form->{groupitems}  = $params->{groupitems};
1567   $print_form->{media}       = 'file'                             if $print_form->{media} eq 'screen';
1568
1569   $order->language($params->{language});
1570   $order->flatten_to_form($print_form, format_amounts => 1);
1571
1572   # search for the template
1573   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1574     name        => $print_form->{formname},
1575     email       => $print_form->{media} eq 'email',
1576     language    => $params->{language},
1577     printer_id  => $print_form->{printer_id},  # todo
1578   );
1579
1580   if (!defined $template_file) {
1581     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);
1582   }
1583
1584   return @errors if scalar @errors;
1585
1586   $print_form->throw_on_error(sub {
1587     eval {
1588       $print_form->prepare_for_printing;
1589
1590       $$pdf_ref = SL::Helper::CreatePDF->create_pdf(
1591         template  => $template_file,
1592         variables => $print_form,
1593         variable_content_types => {
1594           longdescription => 'html',
1595           partnotes       => 'html',
1596           notes           => 'html',
1597         },
1598       );
1599       1;
1600     } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
1601   });
1602
1603   return @errors;
1604 }
1605
1606 sub get_files_for_email_dialog {
1607   my ($self) = @_;
1608
1609   my %files = map { ($_ => []) } qw(versions files vc_files part_files);
1610
1611   return %files if !$::instance_conf->get_doc_storage;
1612
1613   if ($self->order->id) {
1614     $files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id,              object_type => $self->order->type, file_type => 'document') ];
1615     $files{files}    = [ SL::File->get_all(         object_id => $self->order->id,              object_type => $self->order->type, file_type => 'attachment') ];
1616     $files{vc_files} = [ SL::File->get_all(         object_id => $self->order->{$self->cv}->id, object_type => $self->cv,          file_type => 'attachment') ];
1617   }
1618
1619   my @parts =
1620     uniq_by { $_->{id} }
1621     map {
1622       +{ id         => $_->part->id,
1623          partnumber => $_->part->partnumber }
1624     } @{$self->order->items_sorted};
1625
1626   foreach my $part (@parts) {
1627     my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
1628     push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
1629   }
1630
1631   foreach my $key (keys %files) {
1632     $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
1633   }
1634
1635   return %files;
1636 }
1637
1638 sub make_periodic_invoices_config_from_yaml {
1639   my ($yaml_config) = @_;
1640
1641   return if !$yaml_config;
1642   my $attr = YAML::Load($yaml_config);
1643   return if 'HASH' ne ref $attr;
1644   return SL::DB::PeriodicInvoicesConfig->new(%$attr);
1645 }
1646
1647
1648 sub get_periodic_invoices_status {
1649   my ($self, $config) = @_;
1650
1651   return                      if $self->type ne sales_order_type();
1652   return t8('not configured') if !$config;
1653
1654   my $active = ('HASH' eq ref $config)                           ? $config->{active}
1655              : ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
1656              :                                                     die "Cannot get status of periodic invoices config";
1657
1658   return $active ? t8('active') : t8('inactive');
1659 }
1660
1661 sub get_title_for {
1662   my ($self, $action) = @_;
1663
1664   return '' if none { lc($action)} qw(add edit);
1665
1666   # for locales:
1667   # $::locale->text("Add Sales Order");
1668   # $::locale->text("Add Purchase Order");
1669   # $::locale->text("Add Quotation");
1670   # $::locale->text("Add Request for Quotation");
1671   # $::locale->text("Edit Sales Order");
1672   # $::locale->text("Edit Purchase Order");
1673   # $::locale->text("Edit Quotation");
1674   # $::locale->text("Edit Request for Quotation");
1675
1676   $action = ucfirst(lc($action));
1677   return $self->type eq sales_order_type()       ? $::locale->text("$action Sales Order")
1678        : $self->type eq purchase_order_type()    ? $::locale->text("$action Purchase Order")
1679        : $self->type eq sales_quotation_type()   ? $::locale->text("$action Quotation")
1680        : $self->type eq request_quotation_type() ? $::locale->text("$action Request for Quotation")
1681        : '';
1682 }
1683
1684 sub sales_order_type {
1685   'sales_order';
1686 }
1687
1688 sub purchase_order_type {
1689   'purchase_order';
1690 }
1691
1692 sub sales_quotation_type {
1693   'sales_quotation';
1694 }
1695
1696 sub request_quotation_type {
1697   'request_quotation';
1698 }
1699
1700 sub nr_key {
1701   return $_[0]->type eq sales_order_type()       ? 'ordnumber'
1702        : $_[0]->type eq purchase_order_type()    ? 'ordnumber'
1703        : $_[0]->type eq sales_quotation_type()   ? 'quonumber'
1704        : $_[0]->type eq request_quotation_type() ? 'quonumber'
1705        : '';
1706 }
1707
1708 1;
1709
1710 __END__
1711
1712 =encoding utf-8
1713
1714 =head1 NAME
1715
1716 SL::Controller::Order - controller for orders
1717
1718 =head1 SYNOPSIS
1719
1720 This is a new form to enter orders, completely rewritten with the use
1721 of controller and java script techniques.
1722
1723 The aim is to provide the user a better expirience and a faster flow
1724 of work. Also the code should be more readable, more reliable and
1725 better to maintain.
1726
1727 =head2 Key Features
1728
1729 =over 4
1730
1731 =item *
1732
1733 One input row, so that input happens every time at the same place.
1734
1735 =item *
1736
1737 Use of pickers where possible.
1738
1739 =item *
1740
1741 Possibility to enter more than one item at once.
1742
1743 =item *
1744
1745 Save order only on "save" (and "save and delivery order"-workflow). No
1746 hidden save on "print" or "email".
1747
1748 =item *
1749
1750 Item list in a scrollable area, so that the workflow buttons stay at
1751 the bottom.
1752
1753 =item *
1754
1755 Reordering item rows with drag and drop is possible. Sorting item rows is
1756 possible (by partnumber, description, qty, sellprice and discount for now).
1757
1758 =item *
1759
1760 No C<update> is necessary. All entries and calculations are managed
1761 with ajax-calls and the page does only reload on C<save>.
1762
1763 =item *
1764
1765 User can see changes immediately, because of the use of java script
1766 and ajax.
1767
1768 =back
1769
1770 =head1 CODE
1771
1772 =head2 Layout
1773
1774 =over 4
1775
1776 =item * C<SL/Controller/Order.pm>
1777
1778 the controller
1779
1780 =item * C<template/webpages/order/form.html>
1781
1782 main form
1783
1784 =item * C<template/webpages/order/tabs/basic_data.html>
1785
1786 Main tab for basic_data.
1787
1788 This is the only tab here for now. "linked records" and "webdav" tabs are
1789 reused from generic code.
1790
1791 =over 4
1792
1793 =item * C<template/webpages/order/tabs/_business_info_row.html>
1794
1795 For displaying information on business type
1796
1797 =item * C<template/webpages/order/tabs/_item_input.html>
1798
1799 The input line for items
1800
1801 =item * C<template/webpages/order/tabs/_row.html>
1802
1803 One row for already entered items
1804
1805 =item * C<template/webpages/order/tabs/_tax_row.html>
1806
1807 Displaying tax information
1808
1809 =item * C<template/webpages/order/tabs/_multi_items_dialog.html>
1810
1811 Dialog for entering more than one item at once
1812
1813 =item * C<template/webpages/order/tabs/_multi_items_result.html>
1814
1815 Results for the filter in the multi items dialog
1816
1817 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
1818
1819 Dialog for selecting price and discount sources
1820
1821 =back
1822
1823 =item * C<js/kivi.Order.js>
1824
1825 java script functions
1826
1827 =back
1828
1829 =head1 TODO
1830
1831 =over 4
1832
1833 =item * testing
1834
1835 =item * currency
1836
1837 =item * credit limit
1838
1839 =item * more workflows (save as new, quotation, purchase order)
1840
1841 =item * price sources: little symbols showing better price / better discount
1842
1843 =item * select units in input row?
1844
1845 =item * custom shipto address
1846
1847 =item * check for direct delivery (workflow sales order -> purchase order)
1848
1849 =item * language / part translations
1850
1851 =item * access rights
1852
1853 =item * display weights
1854
1855 =item * history
1856
1857 =item * mtime check
1858
1859 =item * optional client/user behaviour
1860
1861 (transactions has to be set - department has to be set -
1862  force project if enabled in client config - transport cost reminder)
1863
1864 =back
1865
1866 =head1 KNOWN BUGS AND CAVEATS
1867
1868 =over 4
1869
1870 =item *
1871
1872 Customer discount is not displayed as a valid discount in price source popup
1873 (this might be a bug in price sources)
1874
1875 (I cannot reproduce this (Bernd))
1876
1877 =item *
1878
1879 No indication that <shift>-up/down expands/collapses second row.
1880
1881 =item *
1882
1883 Inline creation of parts is not currently supported
1884
1885 =item *
1886
1887 Table header is not sticky in the scrolling area.
1888
1889 =item *
1890
1891 Sorting does not include C<position>, neither does reordering.
1892
1893 This behavior was implemented intentionally. But we can discuss, which behavior
1894 should be implemented.
1895
1896 =item *
1897
1898 C<show_multi_items_dialog> does not use the currently inserted string for
1899 filtering.
1900
1901 =item *
1902
1903 The language selected in print or email dialog is not saved when the order is saved.
1904
1905 =back
1906
1907 =head1 To discuss / Nice to have
1908
1909 =over 4
1910
1911 =item *
1912
1913 How to expand/collapse second row. Now it can be done clicking the icon or
1914 <shift>-up/down.
1915
1916 =item *
1917
1918 Possibility to change longdescription in input row?
1919
1920 =item *
1921
1922 Possibility to select PriceSources in input row?
1923
1924 =item *
1925
1926 This controller uses a (changed) copy of the template for the PriceSource
1927 dialog. Maybe there could be used one code source.
1928
1929 =item *
1930
1931 Rounding-differences between this controller (PriceTaxCalculator) and the old
1932 form. This is not only a problem here, but also in all parts using the PTC.
1933 There exists a ticket and a patch. This patch should be testet.
1934
1935 =item *
1936
1937 An indicator, if the actual inputs are saved (like in an
1938 editor or on text processing application).
1939
1940 =item *
1941
1942 A warning when leaving the page without saveing unchanged inputs.
1943
1944 =item *
1945
1946 Workflows for delivery order and invoice are in the menu "Save", because the
1947 order is saved before opening the new document form. Nevertheless perhaps these
1948 workflow buttons should be put under "Workflows".
1949
1950
1951 =back
1952
1953 =head1 AUTHOR
1954
1955 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>
1956
1957 =cut