Auftrags-Controller: Email: Anhang-Policy anders prüfen
[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::Printer;
19 use SL::DB::Language;
20 use SL::DB::RecordLink;
21
22 use SL::Helper::CreatePDF qw(:all);
23 use SL::Helper::PrintOptions;
24
25 use SL::Controller::Helper::GetModels;
26
27 use List::Util qw(first);
28 use List::UtilsBy qw(sort_by uniq_by);
29 use List::MoreUtils qw(any none pairwise first_index);
30 use English qw(-no_match_vars);
31 use File::Spec;
32 use Cwd;
33
34 use Rose::Object::MakeMethods::Generic
35 (
36  scalar => [ qw(item_ids_to_delete) ],
37  'scalar --get_set_init' => [ qw(order valid_types type cv p multi_items_models all_price_factors) ],
38 );
39
40
41 # safety
42 __PACKAGE__->run_before('_check_auth');
43
44 __PACKAGE__->run_before('_recalc',
45                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print create_pdf send_email) ]);
46
47 __PACKAGE__->run_before('_get_unalterable_data',
48                         only => [ qw(save save_as_new save_and_delivery_order save_and_invoice print create_pdf send_email) ]);
49
50 #
51 # actions
52 #
53
54 # add a new order
55 sub action_add {
56   my ($self) = @_;
57
58   $self->order->transdate(DateTime->now_local());
59   my $extra_days = $self->type eq _sales_quotation_type() ? $::instance_conf->get_reqdate_interval : 1;
60   $self->order->reqdate(DateTime->today_local->next_workday(extra_days => $extra_days)) if !$self->order->reqdate;
61
62   $self->_pre_render();
63   $self->render(
64     'order/form',
65     title => $self->_get_title_for('add'),
66     %{$self->{template_args}}
67   );
68 }
69
70 # edit an existing order
71 sub action_edit {
72   my ($self) = @_;
73
74   $self->_load_order;
75   $self->_recalc();
76   $self->_pre_render();
77   $self->render(
78     'order/form',
79     title => $self->_get_title_for('edit'),
80     %{$self->{template_args}}
81   );
82 }
83
84 # delete the order
85 sub action_delete {
86   my ($self) = @_;
87
88   my $errors = $self->_delete();
89
90   if (scalar @{ $errors }) {
91     $self->js->flash('error', $_) foreach @{ $errors };
92     return $self->js->render();
93   }
94
95   my $text = $self->type eq _sales_order_type()       ? $::locale->text('The order has been deleted')
96            : $self->type eq _purchase_order_type()    ? $::locale->text('The order has been deleted')
97            : $self->type eq _sales_quotation_type()   ? $::locale->text('The quotation has been deleted')
98            : $self->type eq _request_quotation_type() ? $::locale->text('The rfq has been deleted')
99            : '';
100   flash_later('info', $text);
101
102   my @redirect_params = (
103     action => 'add',
104     type   => $self->type,
105   );
106
107   $self->redirect_to(@redirect_params);
108 }
109
110 # save the order
111 sub action_save {
112   my ($self) = @_;
113
114   my $errors = $self->_save();
115
116   if (scalar @{ $errors }) {
117     $self->js->flash('error', $_) foreach @{ $errors };
118     return $self->js->render();
119   }
120
121   my $text = $self->type eq _sales_order_type()       ? $::locale->text('The order has been saved')
122            : $self->type eq _purchase_order_type()    ? $::locale->text('The order has been saved')
123            : $self->type eq _sales_quotation_type()   ? $::locale->text('The quotation has been saved')
124            : $self->type eq _request_quotation_type() ? $::locale->text('The rfq has been saved')
125            : '';
126   flash_later('info', $text);
127
128   my @redirect_params = (
129     action => 'edit',
130     type   => $self->type,
131     id     => $self->order->id,
132   );
133
134   $self->redirect_to(@redirect_params);
135 }
136
137 # save the order as new document an open it for edit
138 sub action_save_as_new {
139   my ($self) = @_;
140
141   my $order = $self->order;
142
143   if (!$order->id) {
144     $self->js->flash('error', t8('This object has not been saved yet.'));
145     return $self->js->render();
146   }
147
148   # load order from db to check if values changed
149   my $saved_order = SL::DB::Order->new(id => $order->id)->load;
150
151   my %new_attrs;
152   # Lets assign a new number if the user hasn't changed the previous one.
153   # If it has been changed manually then use it as-is.
154   $new_attrs{number}    = (trim($order->number) eq $saved_order->number)
155                         ? ''
156                         : trim($order->number);
157
158   # Clear transdate unless changed
159   $new_attrs{transdate} = ($order->transdate == $saved_order->transdate)
160                         ? DateTime->today_local
161                         : $order->transdate;
162
163   # Set new reqdate unless changed
164   if ($order->reqdate == $saved_order->reqdate) {
165     my $extra_days = $self->type eq _sales_quotation_type() ? $::instance_conf->get_reqdate_interval : 1;
166     $new_attrs{reqdate} = DateTime->today_local->next_workday(extra_days => $extra_days);
167   } else {
168     $new_attrs{reqdate} = $order->reqdate;
169   }
170
171   # Update employee
172   $new_attrs{employee}  = SL::DB::Manager::Employee->current;
173
174   # Create new record from current one
175   $self->order(SL::DB::Order->new_from($order, destination_type => $order->type, attributes => \%new_attrs));
176
177   # no linked records on save as new
178   delete $::form->{$_} for qw(converted_from_oe_id converted_from_orderitems_ids);
179
180   # save
181   $self->action_save();
182 }
183
184 # print the order
185 #
186 # This is called if "print" is pressed in the print dialog.
187 # If PDF creation was requested and succeeded, the pdf is stored in a session
188 # file and the filename is stored as session value with an unique key. A
189 # javascript function with this key is then called. This function calls the
190 # download action below (action_download_pdf), which offers the file for
191 # download.
192 sub action_print {
193   my ($self) = @_;
194
195   my $format      = $::form->{print_options}->{format};
196   my $media       = $::form->{print_options}->{media};
197   my $formname    = $::form->{print_options}->{formname};
198   my $copies      = $::form->{print_options}->{copies};
199   my $groupitems  = $::form->{print_options}->{groupitems};
200
201   # only pdf by now
202   if (none { $format eq $_ } qw(pdf)) {
203     return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
204   }
205
206   # only screen or printer by now
207   if (none { $media eq $_ } qw(screen printer)) {
208     return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
209   }
210
211   my $language;
212   $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
213
214   # create a form for generate_attachment_filename
215   my $form = Form->new;
216   $form->{ordnumber} = $self->order->ordnumber;
217   $form->{type}      = $self->type;
218   $form->{format}    = $format;
219   $form->{formname}  = $formname;
220   $form->{language}  = '_' . $language->template_code if $language;
221   my $pdf_filename   = $form->generate_attachment_filename();
222
223   my $pdf;
224   my @errors = _create_pdf($self->order, \$pdf, { format     => $format,
225                                                   formname   => $formname,
226                                                   language   => $language,
227                                                   groupitems => $groupitems });
228   if (scalar @errors) {
229     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
230   }
231
232   if ($media eq 'screen') {
233     # screen/download
234     my $sfile = SL::SessionFile::Random->new(mode => "w");
235     $sfile->fh->print($pdf);
236     $sfile->fh->close;
237
238     my $key = join('_', Time::HiRes::gettimeofday(), int rand 1000000000000);
239     $::auth->set_session_value("Order::create_pdf-${key}" => $sfile->file_name);
240
241     $self->js
242     ->run('kivi.Order.download_pdf', $pdf_filename, $key)
243     ->flash('info', t8('The PDF has been created'));
244
245   } elsif ($media eq 'printer') {
246     # printer
247     my $printer_id = $::form->{print_options}->{printer_id};
248     SL::DB::Printer->new(id => $printer_id)->load->print_document(
249       copies  => $copies,
250       content => $pdf,
251     );
252
253     $self->js->flash('info', t8('The PDF has been printed'));
254   }
255
256   # copy file to webdav folder
257   if ($self->order->ordnumber && $::instance_conf->get_webdav_documents) {
258     my $webdav = SL::Webdav->new(
259       type     => $self->type,
260       number   => $self->order->ordnumber,
261     );
262     my $webdav_file = SL::Webdav::File->new(
263       webdav   => $webdav,
264       filename => $pdf_filename,
265     );
266     eval {
267       $webdav_file->store(data => \$pdf);
268       1;
269     } or do {
270       $self->js->flash('error', t8('Storing PDF to webdav folder failed: #1', $@));
271     }
272   }
273   if ($self->order->ordnumber && $::instance_conf->get_doc_storage) {
274     eval {
275       SL::File->save(object_id     => $self->order->id,
276                      object_type   => $self->type,
277                      mime_type     => 'application/pdf',
278                      source        => 'created',
279                      file_type     => 'document',
280                      file_name     => $pdf_filename,
281                      file_contents => $pdf);
282       1;
283     } or do {
284       $self->js->flash('error', t8('Storing PDF in storage backend failed: #1', $@));
285     }
286   }
287   $self->js->render;
288 }
289
290 # offer pdf for download
291 #
292 # It needs to get the key for the session value to get the pdf file.
293 sub action_download_pdf {
294   my ($self) = @_;
295
296   my $key = $::form->{key};
297   my $tmp_filename = $::auth->get_session_value("Order::create_pdf-${key}");
298   return $self->send_file(
299     $tmp_filename,
300     type => 'application/pdf',
301     name => $::form->{pdf_filename},
302   );
303 }
304
305 # open the email dialog
306 sub action_show_email_dialog {
307   my ($self) = @_;
308
309   my $cv_method = $self->cv;
310
311   if (!$self->order->$cv_method) {
312     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'))
313                     ->render($self);
314   }
315
316   my $email_form;
317   $email_form->{to}   = $self->order->contact->cp_email if $self->order->contact;
318   $email_form->{to} ||= $self->order->$cv_method->email;
319   $email_form->{cc}   = $self->order->$cv_method->cc;
320   $email_form->{bcc}  = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
321   # Todo: get addresses from shipto, if any
322
323   my $form = Form->new;
324   $form->{ordnumber} = $self->order->ordnumber;
325   $form->{formname}  = $self->type;
326   $form->{type}      = $self->type;
327   $form->{language} = 'de';
328   $form->{format}   = 'pdf';
329
330   $email_form->{subject}             = $form->generate_email_subject();
331   $email_form->{attachment_filename} = $form->generate_attachment_filename();
332   $email_form->{message}             = $form->generate_email_body();
333   $email_form->{js_send_function}    = 'kivi.Order.send_email()';
334
335   my %files = $self->_get_files_for_email_dialog();
336   my $dialog_html = $self->render('common/_send_email_dialog', { output => 0 },
337                                   email_form  => $email_form,
338                                   show_bcc    => $::auth->assert('email_bcc', 'may fail'),
339                                   FILES       => \%files,
340                                   is_customer => $self->cv eq 'customer',
341   );
342
343   $self->js
344       ->run('kivi.Order.show_email_dialog', $dialog_html)
345       ->reinit_widgets
346       ->render($self);
347 }
348
349 # send email
350 #
351 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
352 sub action_send_email {
353   my ($self) = @_;
354
355   my $email_form  = delete $::form->{email_form};
356   my %field_names = (to => 'email');
357
358   $::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };
359
360   # for Form::cleanup which may be called in Form::send_email
361   $::form->{cwd}    = getcwd();
362   $::form->{tmpdir} = $::lx_office_conf{paths}->{userspath};
363
364   $::form->{$_}     = $::form->{print_options}->{$_} for keys %{ $::form->{print_options} };
365   $::form->{media}  = 'email';
366
367   if (($::form->{attachment_policy} // '') !~ m{^(?:old_file|no_file)$}) {
368     my $language;
369     $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
370
371     my $pdf;
372     my @errors = _create_pdf($self->order, \$pdf, {media      => $::form->{media},
373                                                    format     => $::form->{print_options}->{format},
374                                                    formname   => $::form->{print_options}->{formname},
375                                                    language   => $language,
376                                                    groupitems => $::form->{print_options}->{groupitems}});
377     if (scalar @errors) {
378       return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render($self);
379     }
380
381     my $sfile = SL::SessionFile::Random->new(mode => "w");
382     $sfile->fh->print($pdf);
383     $sfile->fh->close;
384
385     $::form->{tmpfile} = $sfile->file_name;
386     $::form->{tmpdir}  = $sfile->get_path; # for Form::cleanup which may be called in Form::send_email
387   }
388
389   $::form->send_email(\%::myconfig, 'pdf');
390
391   # internal notes
392   my $intnotes = $self->order->intnotes;
393   $intnotes   .= "\n\n" if $self->order->intnotes;
394   $intnotes   .= t8('[email]')                                                                                        . "\n";
395   $intnotes   .= t8('Date')       . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
396   $intnotes   .= t8('To (email)') . ": " . $::form->{email}                                                           . "\n";
397   $intnotes   .= t8('Cc')         . ": " . $::form->{cc}                                                              . "\n"    if $::form->{cc};
398   $intnotes   .= t8('Bcc')        . ": " . $::form->{bcc}                                                             . "\n"    if $::form->{bcc};
399   $intnotes   .= t8('Subject')    . ": " . $::form->{subject}                                                         . "\n\n";
400   $intnotes   .= t8('Message')    . ": " . $::form->{message};
401
402   $self->js
403       ->val('#order_intnotes', $intnotes)
404       ->run('kivi.Order.close_email_dialog')
405       ->flash('info', t8('The email has been sent.'))
406       ->render($self);
407 }
408
409 # open the periodic invoices config dialog
410 #
411 # If there are values in the form (i.e. dialog was opened before),
412 # then use this values. Create new ones, else.
413 sub action_show_periodic_invoices_config_dialog {
414   my ($self) = @_;
415
416   my $config = _make_periodic_invoices_config_from_yaml(delete $::form->{config});
417   $config  ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
418   $config  ||= SL::DB::PeriodicInvoicesConfig->new(periodicity             => 'm',
419                                                    order_value_periodicity => 'p', # = same as periodicity
420                                                    start_date_as_date      => $::form->{transdate} || $::form->current_date,
421                                                    extend_automatically_by => 12,
422                                                    active                  => 1,
423                                                    email_subject           => GenericTranslations->get(
424                                                                                 language_id      => $::form->{language_id},
425                                                                                 translation_type =>"preset_text_periodic_invoices_email_subject"),
426                                                    email_body              => GenericTranslations->get(
427                                                                                 language_id      => $::form->{language_id},
428                                                                                 translation_type =>"preset_text_periodic_invoices_email_body"),
429   );
430   $config->periodicity('m')             if none { $_ eq $config->periodicity             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
431   $config->order_value_periodicity('p') if none { $_ eq $config->order_value_periodicity } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
432
433   $::form->get_lists(printers => "ALL_PRINTERS",
434                      charts   => { key       => 'ALL_CHARTS',
435                                    transdate => 'current_date' });
436
437   $::form->{AR} = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
438
439   if ($::form->{customer_id}) {
440     $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
441   }
442
443   $self->render('oe/edit_periodic_invoices_config', { layout => 0 },
444                 popup_dialog             => 1,
445                 popup_js_close_function  => 'kivi.Order.close_periodic_invoices_config_dialog()',
446                 popup_js_assign_function => 'kivi.Order.assign_periodic_invoices_config()',
447                 config                   => $config,
448                 %$::form);
449 }
450
451 # assign the values of the periodic invoices config dialog
452 # as yaml in the hidden tag and set the status.
453 sub action_assign_periodic_invoices_config {
454   my ($self) = @_;
455
456   $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
457
458   my $config = { active                  => $::form->{active}     ? 1 : 0,
459                  terminated              => $::form->{terminated} ? 1 : 0,
460                  direct_debit            => $::form->{direct_debit} ? 1 : 0,
461                  periodicity             => (any { $_ eq $::form->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES)              ? $::form->{periodicity}             : 'm',
462                  order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
463                  start_date_as_date      => $::form->{start_date_as_date},
464                  end_date_as_date        => $::form->{end_date_as_date},
465                  first_billing_date_as_date => $::form->{first_billing_date_as_date},
466                  print                   => $::form->{print} ? 1 : 0,
467                  printer_id              => $::form->{print} ? $::form->{printer_id} * 1 : undef,
468                  copies                  => $::form->{copies} * 1 ? $::form->{copies} : 1,
469                  extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
470                  ar_chart_id             => $::form->{ar_chart_id} * 1,
471                  send_email                 => $::form->{send_email} ? 1 : 0,
472                  email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
473                  email_recipient_address    => $::form->{email_recipient_address},
474                  email_sender               => $::form->{email_sender},
475                  email_subject              => $::form->{email_subject},
476                  email_body                 => $::form->{email_body},
477                };
478
479   my $periodic_invoices_config = YAML::Dump($config);
480
481   my $status = $self->_get_periodic_invoices_status($config);
482
483   $self->js
484     ->remove('#order_periodic_invoices_config')
485     ->insertAfter(hidden_tag('order.periodic_invoices_config', $periodic_invoices_config), '#periodic_invoices_status')
486     ->run('kivi.Order.close_periodic_invoices_config_dialog')
487     ->html('#periodic_invoices_status', $status)
488     ->flash('info', t8('The periodic invoices config has been assigned.'))
489     ->render($self);
490 }
491
492 sub action_get_has_active_periodic_invoices {
493   my ($self) = @_;
494
495   my $config = _make_periodic_invoices_config_from_yaml(delete $::form->{config});
496   $config  ||= SL::DB::Manager::PeriodicInvoicesConfig->find_by(oe_id => $::form->{id}) if $::form->{id};
497
498   my $has_active_periodic_invoices =
499        $self->type eq _sales_order_type()
500     && $config
501     && $config->active
502     && (!$config->end_date || ($config->end_date > DateTime->today_local))
503     && $config->get_previous_billed_period_start_date;
504
505   $_[0]->render(\ !!$has_active_periodic_invoices, { type => 'text' });
506 }
507
508 # save the order and redirect to the frontend subroutine for a new
509 # delivery order
510 sub action_save_and_delivery_order {
511   my ($self) = @_;
512
513   my $errors = $self->_save();
514
515   if (scalar @{ $errors }) {
516     $self->js->flash('error', $_) foreach @{ $errors };
517     return $self->js->render();
518   }
519
520   my $text = $self->type eq _sales_order_type()       ? $::locale->text('The order has been saved')
521            : $self->type eq _purchase_order_type()    ? $::locale->text('The order has been saved')
522            : $self->type eq _sales_quotation_type()   ? $::locale->text('The quotation has been saved')
523            : $self->type eq _request_quotation_type() ? $::locale->text('The rfq has been saved')
524            : '';
525   flash_later('info', $text);
526
527   my @redirect_params = (
528     controller => 'oe.pl',
529     action     => 'oe_delivery_order_from_order',
530     id         => $self->order->id,
531   );
532
533   $self->redirect_to(@redirect_params);
534 }
535
536 # save the order and redirect to the frontend subroutine for a new
537 # invoice
538 sub action_save_and_invoice {
539   my ($self) = @_;
540
541   my $errors = $self->_save();
542
543   if (scalar @{ $errors }) {
544     $self->js->flash('error', $_) foreach @{ $errors };
545     return $self->js->render();
546   }
547
548   my $text = $self->type eq _sales_order_type()       ? $::locale->text('The order has been saved')
549            : $self->type eq _purchase_order_type()    ? $::locale->text('The order has been saved')
550            : $self->type eq _sales_quotation_type()   ? $::locale->text('The quotation has been saved')
551            : $self->type eq _request_quotation_type() ? $::locale->text('The rfq has been saved')
552            : '';
553   flash_later('info', $text);
554
555   my @redirect_params = (
556     controller => 'oe.pl',
557     action     => 'oe_invoice_from_order',
558     id         => $self->order->id,
559   );
560
561   $self->redirect_to(@redirect_params);
562 }
563
564 # workflow from sales quotation to sales order
565 sub action_sales_order {
566   $_[0]->_workflow_sales_or_purchase_order();
567 }
568
569 # workflow from rfq to purchase order
570 sub action_purchase_order {
571   $_[0]->_workflow_sales_or_purchase_order();
572 }
573
574 # set form elements in respect to a changed customer or vendor
575 #
576 # This action is called on an change of the customer/vendor picker.
577 sub action_customer_vendor_changed {
578   my ($self) = @_;
579
580   _setup_order_from_cv($self->order);
581   $self->_recalc();
582
583   my $cv_method = $self->cv;
584
585   if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
586     $self->js->show('#cp_row');
587   } else {
588     $self->js->hide('#cp_row');
589   }
590
591   if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
592     $self->js->show('#shipto_row');
593   } else {
594     $self->js->hide('#shipto_row');
595   }
596
597   $self->js->val( '#order_salesman_id',      $self->order->salesman_id)        if $self->order->is_sales;
598
599   $self->js
600     ->replaceWith('#order_cp_id',            $self->build_contact_select)
601     ->replaceWith('#order_shipto_id',        $self->build_shipto_select)
602     ->replaceWith('#business_info_row',      $self->build_business_info_row)
603     ->val(        '#order_taxzone_id',       $self->order->taxzone_id)
604     ->val(        '#order_taxincluded',      $self->order->taxincluded)
605     ->val(        '#order_payment_id',       $self->order->payment_id)
606     ->val(        '#order_delivery_term_id', $self->order->delivery_term_id)
607     ->val(        '#order_intnotes',         $self->order->intnotes)
608     ->focus(      '#order_' . $self->cv . '_id');
609
610   $self->_js_redisplay_amounts_and_taxes;
611   $self->js->render();
612 }
613
614 # open the dialog for customer/vendor details
615 sub action_show_customer_vendor_details_dialog {
616   my ($self) = @_;
617
618   my $is_customer = 'customer' eq $::form->{vc};
619   my $cv;
620   if ($is_customer) {
621     $cv = SL::DB::Customer->new(id => $::form->{vc_id})->load;
622   } else {
623     $cv = SL::DB::Vendor->new(id => $::form->{vc_id})->load;
624   }
625
626   my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
627   $details{discount_as_percent} = $cv->discount_as_percent;
628   $details{creditlimt}          = $cv->creditlimit_as_number;
629   $details{business}            = $cv->business->description      if $cv->business;
630   $details{language}            = $cv->language_obj->description  if $cv->language_obj;
631   $details{delivery_terms}      = $cv->delivery_term->description if $cv->delivery_term;
632   $details{payment_terms}       = $cv->payment->description       if $cv->payment;
633   $details{pricegroup}          = $cv->pricegroup->pricegroup     if $is_customer && $cv->pricegroup;
634
635   foreach my $entry (@{ $cv->shipto }) {
636     push @{ $details{SHIPTO} },   { map { $_ => $entry->$_ } @{$entry->meta->columns} };
637   }
638   foreach my $entry (@{ $cv->contacts }) {
639     push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
640   }
641
642   $_[0]->render('common/show_vc_details', { layout => 0 },
643                 is_customer => $is_customer,
644                 %details);
645
646 }
647
648 # called if a unit in an existing item row is changed
649 sub action_unit_changed {
650   my ($self) = @_;
651
652   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
653   my $item = $self->order->items_sorted->[$idx];
654
655   my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
656   $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
657
658   $self->_recalc();
659
660   $self->js
661     ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
662   $self->_js_redisplay_line_values;
663   $self->_js_redisplay_amounts_and_taxes;
664   $self->js->render();
665 }
666
667 # add an item row for a new item entered in the input row
668 sub action_add_item {
669   my ($self) = @_;
670
671   my $form_attr = $::form->{add_item};
672
673   return unless $form_attr->{parts_id};
674
675   my $item = _new_item($self->order, $form_attr);
676
677   $self->order->add_items($item);
678
679   $self->_recalc();
680
681   my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
682   my $row_as_html = $self->p->render('order/tabs/_row',
683                                      ITEM              => $item,
684                                      ID                => $item_id,
685                                      TYPE              => $self->type,
686                                      ALL_PRICE_FACTORS => $self->all_price_factors
687   );
688
689   $self->js
690     ->append('#row_table_id', $row_as_html);
691
692   if ( $item->part->is_assortment ) {
693     $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
694     foreach my $assortment_item ( @{$item->part->assortment_items} ) {
695       my $attr = { parts_id => $assortment_item->parts_id,
696                    qty      => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
697                    unit     => $assortment_item->unit,
698                    description => $assortment_item->part->description,
699                  };
700       my $item = _new_item($self->order, $attr);
701
702       # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
703       $item->discount(1) unless $assortment_item->charge;
704
705       $self->order->add_items( $item );
706       $self->_recalc();
707       my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
708       my $row_as_html = $self->p->render('order/tabs/_row',
709                                          ITEM              => $item,
710                                          ID                => $item_id,
711                                          TYPE              => $self->type,
712                                          ALL_PRICE_FACTORS => $self->all_price_factors
713       );
714       $self->js
715         ->append('#row_table_id', $row_as_html);
716     };
717   };
718
719   $self->js
720     ->val('.add_item_input', '')
721     ->run('kivi.Order.init_row_handlers')
722     ->run('kivi.Order.row_table_scroll_down')
723     ->run('kivi.Order.renumber_positions')
724     ->focus('#add_item_parts_id_name');
725
726   $self->_js_redisplay_amounts_and_taxes;
727   $self->js->render();
728 }
729
730 # open the dialog for entering multiple items at once
731 sub action_show_multi_items_dialog {
732   require SL::DB::PartsGroup;
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::Manager::Order->find_by(id => $::form->{id}));
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   $item->assign_attributes(%$attr);
1197
1198   my $part         = SL::DB::Part->new(id => $attr->{parts_id})->load;
1199   my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
1200
1201   $item->unit($part->unit) if !$item->unit;
1202
1203   my $price_src;
1204   if ( $part->is_assortment ) {
1205     # add assortment items with price 0, as the components carry the price
1206     $price_src = $price_source->price_from_source("");
1207     $price_src->price(0);
1208   } elsif ($item->sellprice) {
1209     $price_src = $price_source->price_from_source("");
1210     $price_src->price($item->sellprice);
1211   } else {
1212     $price_src = $price_source->best_price
1213            ? $price_source->best_price
1214            : $price_source->price_from_source("");
1215     $price_src->price(0) if !$price_source->best_price;
1216   }
1217
1218   my $discount_src;
1219   if ($item->discount) {
1220     $discount_src = $price_source->discount_from_source("");
1221     $discount_src->discount($item->discount);
1222   } else {
1223     $discount_src = $price_source->best_discount
1224                   ? $price_source->best_discount
1225                   : $price_source->discount_from_source("");
1226     $discount_src->discount(0) if !$price_source->best_discount;
1227   }
1228
1229   my %new_attr;
1230   $new_attr{part}                   = $part;
1231   $new_attr{description}            = $part->description     if ! $item->description;
1232   $new_attr{qty}                    = 1.0                    if ! $item->qty;
1233   $new_attr{price_factor_id}        = $part->price_factor_id if ! $item->price_factor_id;
1234   $new_attr{sellprice}              = $price_src->price;
1235   $new_attr{discount}               = $discount_src->discount;
1236   $new_attr{active_price_source}    = $price_src;
1237   $new_attr{active_discount_source} = $discount_src;
1238   $new_attr{longdescription}        = $part->notes           if ! defined $attr->{longdescription};
1239   $new_attr{project_id}             = $record->globalproject_id;
1240   $new_attr{lastcost}               = $record->is_sales ? $part->lastcost : 0;
1241
1242   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
1243   # they cannot be retrieved via custom_variables until the order/orderitem is
1244   # saved. Adding empty custom_variables to new orderitem here solves this problem.
1245   $new_attr{custom_variables} = [];
1246
1247   $item->assign_attributes(%new_attr);
1248
1249   return $item;
1250 }
1251
1252 sub _setup_order_from_cv {
1253   my ($order) = @_;
1254
1255   $order->$_($order->customervendor->$_) for (qw(taxzone_id payment_id delivery_term_id));
1256
1257   $order->intnotes($order->customervendor->notes);
1258
1259   if ($order->is_sales) {
1260     $order->salesman_id($order->customer->salesman_id);
1261     $order->taxincluded(defined($order->customer->taxincluded_checked)
1262                         ? $order->customer->taxincluded_checked
1263                         : $::myconfig{taxincluded_checked});
1264   }
1265
1266 }
1267
1268 # recalculate prices and taxes
1269 #
1270 # Using the PriceTaxCalculator. Store linetotals in the item objects.
1271 sub _recalc {
1272   my ($self) = @_;
1273
1274   # bb: todo: currency later
1275   $self->order->currency_id($::instance_conf->get_currency_id());
1276
1277   my %pat = $self->order->calculate_prices_and_taxes();
1278   $self->{taxes} = [];
1279   foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
1280     my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
1281
1282     my @amount_keys = grep { $pat{amounts}->{$_}->{tax_id} == $tax->id } keys %{ $pat{amounts} };
1283     push(@{ $self->{taxes} }, { amount    => $pat{taxes}->{$tax_chart_id},
1284                                 netamount => $pat{amounts}->{$amount_keys[0]}->{amount},
1285                                 tax       => $tax });
1286   }
1287
1288   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
1289 }
1290
1291 # get data for saving, printing, ..., that is not changed in the form
1292 #
1293 # Only cvars for now.
1294 sub _get_unalterable_data {
1295   my ($self) = @_;
1296
1297   foreach my $item (@{ $self->order->items }) {
1298     # autovivify all cvars that are not in the form (cvars_by_config can do it).
1299     # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
1300     foreach my $var (@{ $item->cvars_by_config }) {
1301       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
1302     }
1303     $item->parse_custom_variable_values;
1304   }
1305 }
1306
1307 # delete the order
1308 #
1309 # And remove related files in the spool directory
1310 sub _delete {
1311   my ($self) = @_;
1312
1313   my $errors = [];
1314   my $db     = $self->order->db;
1315
1316   $db->with_transaction(
1317     sub {
1318       my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
1319       $self->order->delete;
1320       my $spool = $::lx_office_conf{paths}->{spool};
1321       unlink map { "$spool/$_" } @spoolfiles if $spool;
1322
1323       1;
1324   }) || push(@{$errors}, $db->error);
1325
1326   return $errors;
1327 }
1328
1329 # save the order
1330 #
1331 # And delete items that are deleted in the form.
1332 sub _save {
1333   my ($self) = @_;
1334
1335   my $errors = [];
1336   my $db     = $self->order->db;
1337
1338   $db->with_transaction(sub {
1339     SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete};
1340     $self->order->save(cascade => 1);
1341
1342     # link records
1343     if ($::form->{converted_from_oe_id}) {
1344       SL::DB::Order->new(id => $::form->{converted_from_oe_id})->load->link_to_record($self->order);
1345
1346       if (scalar @{ $::form->{converted_from_orderitems_ids} || [] }) {
1347         my $idx = 0;
1348         foreach (@{ $self->order->items_sorted }) {
1349           my $from_id = $::form->{converted_from_orderitems_ids}->[$idx];
1350           next if !$from_id;
1351           SL::DB::RecordLink->new(from_table => 'orderitems',
1352                                   from_id    => $from_id,
1353                                   to_table   => 'orderitems',
1354                                   to_id      => $_->id
1355           )->save;
1356           $idx++;
1357         }
1358       }
1359     }
1360     1;
1361   }) || push(@{$errors}, $db->error);
1362
1363   return $errors;
1364 }
1365
1366 sub _workflow_sales_or_purchase_order {
1367   my ($self) = @_;
1368
1369   my $destination_type = $::form->{type} eq _sales_quotation_type()   ? _sales_order_type()
1370                        : $::form->{type} eq _request_quotation_type() ? _purchase_order_type()
1371                        : $::form->{type} eq _purchase_order_type()    ? _sales_order_type()
1372                        : $::form->{type} eq _sales_order_type()       ? _purchase_order_type()
1373                        : '';
1374
1375   $self->order(SL::DB::Order->new_from($self->order, destination_type => $destination_type));
1376   $self->{converted_from_oe_id} = delete $::form->{id};
1377
1378   # set item ids to new fake id, to identify them as new items
1379   foreach my $item (@{$self->order->items_sorted}) {
1380     $item->{new_fake_id} = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
1381   }
1382
1383   # change form type
1384   $::form->{type} = $destination_type;
1385   $self->type($self->init_type);
1386   $self->cv  ($self->init_cv);
1387   $self->_check_auth;
1388
1389   $self->_recalc();
1390   $self->_get_unalterable_data();
1391   $self->_pre_render();
1392
1393   # trigger rendering values for second row/longdescription as hidden,
1394   # because they are loaded only on demand. So we need to keep the values
1395   # from the source.
1396   $_->{render_second_row}      = 1 for @{ $self->order->items_sorted };
1397   $_->{render_longdescription} = 1 for @{ $self->order->items_sorted };
1398
1399   $self->render(
1400     'order/form',
1401     title => $self->_get_title_for('edit'),
1402     %{$self->{template_args}}
1403   );
1404 }
1405
1406
1407 sub _pre_render {
1408   my ($self) = @_;
1409
1410   $self->{all_taxzones}             = SL::DB::Manager::TaxZone->get_all_sorted();
1411   $self->{all_departments}          = SL::DB::Manager::Department->get_all_sorted();
1412   $self->{all_employees}            = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1413                                                                                             deleted => 0 ] ],
1414                                                                          sort_by => 'name');
1415   $self->{all_salesmen}             = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1416                                                                                             deleted => 0 ] ],
1417                                                                          sort_by => 'name');
1418   $self->{all_projects}             = SL::DB::Manager::Project->get_all(where => [ or => [ id => $self->order->globalproject_id,
1419                                                                                            active => 1 ] ],
1420                                                                         sort_by => 'projectnumber');
1421   $self->{all_payment_terms}        = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->order->payment_id,
1422                                                                                                       obsolete => 0 ] ]);
1423   $self->{all_delivery_terms}       = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1424   $self->{current_employee_id}      = SL::DB::Manager::Employee->current->id;
1425   $self->{periodic_invoices_status} = $self->_get_periodic_invoices_status($self->order->periodic_invoices_config);
1426   $self->{order_probabilities}      = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
1427
1428   my $print_form = Form->new('');
1429   $print_form->{type}      = $self->type;
1430   $print_form->{printers}  = SL::DB::Manager::Printer->get_all_sorted;
1431   $print_form->{languages} = SL::DB::Manager::Language->get_all_sorted;
1432   $self->{print_options}   = SL::Helper::PrintOptions->get_print_options(
1433     form => $print_form,
1434     options => {dialog_name_prefix => 'print_options.',
1435                 show_headers       => 1,
1436                 no_queue           => 1,
1437                 no_postscript      => 1,
1438                 no_opendocument    => 1,
1439                 no_html            => 1},
1440   );
1441
1442   foreach my $item (@{$self->order->orderitems}) {
1443     my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1444     $item->active_price_source(   $price_source->price_from_source(   $item->active_price_source   ));
1445     $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
1446   }
1447
1448   if ($self->order->ordnumber && $::instance_conf->get_webdav) {
1449     my $webdav = SL::Webdav->new(
1450       type     => $self->type,
1451       number   => $self->order->ordnumber,
1452     );
1453     my @all_objects = $webdav->get_all_objects;
1454     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1455                                                     type => t8('File'),
1456                                                     link => File::Spec->catfile($_->full_filedescriptor),
1457                                                 } } @all_objects;
1458   }
1459
1460   $::request->{layout}->use_javascript("${_}.js") for qw(kivi.SalesPurchase kivi.Order kivi.File ckeditor/ckeditor ckeditor/adapters/jquery edit_periodic_invoices_config calculate_qty);
1461   $self->_setup_edit_action_bar;
1462 }
1463
1464 sub _setup_edit_action_bar {
1465   my ($self, %params) = @_;
1466
1467   my $deletion_allowed = (any { $self->type eq $_ } (_sales_quotation_type(), _request_quotation_type()))
1468                       || (($self->type eq _sales_order_type())    && $::instance_conf->get_sales_order_show_delete)
1469                       || (($self->type eq _purchase_order_type()) && $::instance_conf->get_purchase_order_show_delete);
1470
1471   for my $bar ($::request->layout->get('actionbar')) {
1472     $bar->add(
1473       combobox => [
1474         action => [
1475           t8('Save'),
1476           call      => [ 'kivi.Order.save', 'save', $::instance_conf->get_order_warn_duplicate_parts,
1477                                                     $::instance_conf->get_order_warn_no_deliverydate,
1478                                                                                                       ],
1479           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1480         ],
1481         action => [
1482           t8('Save as new'),
1483           call      => [ 'kivi.Order.save', 'save_as_new', $::instance_conf->get_order_warn_duplicate_parts ],
1484           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1485           disabled  => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1486         ],
1487         action => [
1488           t8('Save and Delivery Order'),
1489           call      => [ 'kivi.Order.save', 'save_and_delivery_order', $::instance_conf->get_order_warn_duplicate_parts,
1490                                                                        $::instance_conf->get_order_warn_no_deliverydate,
1491                                                                                                                         ],
1492           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1493           only_if   => (any { $self->type eq $_ } (_sales_order_type(), _purchase_order_type()))
1494         ],
1495         action => [
1496           t8('Save and Invoice'),
1497           call      => [ 'kivi.Order.save', 'save_and_invoice', $::instance_conf->get_order_warn_duplicate_parts ],
1498           checks    => [ 'kivi.Order.check_save_active_periodic_invoices' ],
1499         ],
1500       ], # end of combobox "Save"
1501
1502       combobox => [
1503         action => [
1504           t8('Workflow'),
1505         ],
1506         action => [
1507           t8('Sales Order'),
1508           submit   => [ '#order_form', { action => "Order/sales_order" } ],
1509           only_if  => (any { $self->type eq $_ } (_sales_quotation_type(), _purchase_order_type())),
1510           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1511         ],
1512         action => [
1513           t8('Purchase Order'),
1514           submit   => [ '#order_form', { action => "Order/purchase_order" } ],
1515           only_if  => (any { $self->type eq $_ } (_sales_order_type(), _request_quotation_type())),
1516           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1517         ],
1518       ], # end of combobox "Workflow"
1519
1520       combobox => [
1521         action => [
1522           t8('Export'),
1523         ],
1524         action => [
1525           t8('Print'),
1526           call => [ 'kivi.Order.show_print_options' ],
1527         ],
1528         action => [
1529           t8('E-mail'),
1530           call => [ 'kivi.Order.email' ],
1531         ],
1532         action => [
1533           t8('Download attachments of all parts'),
1534           call     => [ 'kivi.File.downloadOrderitemsFiles', $::form->{type}, $::form->{id} ],
1535           disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1536           only_if  => $::instance_conf->get_doc_storage,
1537         ],
1538       ], # end of combobox "Export"
1539
1540       action => [
1541         t8('Delete'),
1542         call     => [ 'kivi.Order.delete_order' ],
1543         confirm  => $::locale->text('Do you really want to delete this object?'),
1544         disabled => !$self->order->id ? t8('This object has not been saved yet.') : undef,
1545         only_if  => $deletion_allowed,
1546       ],
1547     );
1548   }
1549 }
1550
1551 sub _create_pdf {
1552   my ($order, $pdf_ref, $params) = @_;
1553
1554   my @errors = ();
1555
1556   my $print_form = Form->new('');
1557   $print_form->{type}        = $order->type;
1558   $print_form->{formname}    = $params->{formname} || $order->type;
1559   $print_form->{format}      = $params->{format}   || 'pdf';
1560   $print_form->{media}       = $params->{media}    || 'file';
1561   $print_form->{groupitems}  = $params->{groupitems};
1562   $print_form->{media}       = 'file'                             if $print_form->{media} eq 'screen';
1563
1564   $order->language($params->{language});
1565   $order->flatten_to_form($print_form, format_amounts => 1);
1566
1567   # search for the template
1568   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1569     name        => $print_form->{formname},
1570     email       => $print_form->{media} eq 'email',
1571     language    => $params->{language},
1572     printer_id  => $print_form->{printer_id},  # todo
1573   );
1574
1575   if (!defined $template_file) {
1576     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);
1577   }
1578
1579   return @errors if scalar @errors;
1580
1581   $print_form->throw_on_error(sub {
1582     eval {
1583       $print_form->prepare_for_printing;
1584
1585       $$pdf_ref = SL::Helper::CreatePDF->create_pdf(
1586         template  => $template_file,
1587         variables => $print_form,
1588         variable_content_types => {
1589           longdescription => 'html',
1590           partnotes       => 'html',
1591           notes           => 'html',
1592         },
1593       );
1594       1;
1595     } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
1596   });
1597
1598   return @errors;
1599 }
1600
1601 sub _get_files_for_email_dialog {
1602   my ($self) = @_;
1603
1604   my %files = map { ($_ => []) } qw(versions files vc_files part_files);
1605
1606   return %files if !$::instance_conf->get_doc_storage;
1607
1608   if ($self->order->id) {
1609     $files{versions} = [ SL::File->get_all_versions(object_id => $self->order->id,              object_type => $self->order->type, file_type => 'document') ];
1610     $files{files}    = [ SL::File->get_all(         object_id => $self->order->id,              object_type => $self->order->type, file_type => 'attachment') ];
1611     $files{vc_files} = [ SL::File->get_all(         object_id => $self->order->{$self->cv}->id, object_type => $self->cv,          file_type => 'attachment') ];
1612   }
1613
1614   my @parts =
1615     uniq_by { $_->{id} }
1616     map {
1617       +{ id         => $_->part->id,
1618          partnumber => $_->part->partnumber }
1619     } @{$self->order->items_sorted};
1620
1621   foreach my $part (@parts) {
1622     my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
1623     push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
1624   }
1625
1626   foreach my $key (keys %files) {
1627     $files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
1628   }
1629
1630   return %files;
1631 }
1632
1633 sub _make_periodic_invoices_config_from_yaml {
1634   my ($yaml_config) = @_;
1635
1636   return if !$yaml_config;
1637   my $attr = YAML::Load($yaml_config);
1638   return if 'HASH' ne ref $attr;
1639   return SL::DB::PeriodicInvoicesConfig->new(%$attr);
1640 }
1641
1642
1643 sub _get_periodic_invoices_status {
1644   my ($self, $config) = @_;
1645
1646   return                      if $self->type ne _sales_order_type();
1647   return t8('not configured') if !$config;
1648
1649   my $active = ('HASH' eq ref $config)                           ? $config->{active}
1650              : ('SL::DB::PeriodicInvoicesConfig' eq ref $config) ? $config->active
1651              :                                                     die "Cannot get status of periodic invoices config";
1652
1653   return $active ? t8('active') : t8('inactive');
1654 }
1655
1656 sub _get_title_for {
1657   my ($self, $action) = @_;
1658
1659   return '' if none { lc($action)} qw(add edit);
1660
1661   # for locales:
1662   # $::locale->text("Add Sales Order");
1663   # $::locale->text("Add Purchase Order");
1664   # $::locale->text("Add Quotation");
1665   # $::locale->text("Add Request for Quotation");
1666   # $::locale->text("Edit Sales Order");
1667   # $::locale->text("Edit Purchase Order");
1668   # $::locale->text("Edit Quotation");
1669   # $::locale->text("Edit Request for Quotation");
1670
1671   $action = ucfirst(lc($action));
1672   return $self->type eq _sales_order_type()       ? $::locale->text("$action Sales Order")
1673        : $self->type eq _purchase_order_type()    ? $::locale->text("$action Purchase Order")
1674        : $self->type eq _sales_quotation_type()   ? $::locale->text("$action Quotation")
1675        : $self->type eq _request_quotation_type() ? $::locale->text("$action Request for Quotation")
1676        : '';
1677 }
1678
1679 sub _sales_order_type {
1680   'sales_order';
1681 }
1682
1683 sub _purchase_order_type {
1684   'purchase_order';
1685 }
1686
1687 sub _sales_quotation_type {
1688   'sales_quotation';
1689 }
1690
1691 sub _request_quotation_type {
1692   'request_quotation';
1693 }
1694
1695 1;
1696
1697 __END__
1698
1699 =encoding utf-8
1700
1701 =head1 NAME
1702
1703 SL::Controller::Order - controller for orders
1704
1705 =head1 SYNOPSIS
1706
1707 This is a new form to enter orders, completely rewritten with the use
1708 of controller and java script techniques.
1709
1710 The aim is to provide the user a better expirience and a faster flow
1711 of work. Also the code should be more readable, more reliable and
1712 better to maintain.
1713
1714 =head2 Key Features
1715
1716 =over 4
1717
1718 =item *
1719
1720 One input row, so that input happens every time at the same place.
1721
1722 =item *
1723
1724 Use of pickers where possible.
1725
1726 =item *
1727
1728 Possibility to enter more than one item at once.
1729
1730 =item *
1731
1732 Save order only on "save" (and "save and delivery order"-workflow). No
1733 hidden save on "print" or "email".
1734
1735 =item *
1736
1737 Item list in a scrollable area, so that the workflow buttons stay at
1738 the bottom.
1739
1740 =item *
1741
1742 Reordering item rows with drag and drop is possible. Sorting item rows is
1743 possible (by partnumber, description, qty, sellprice and discount for now).
1744
1745 =item *
1746
1747 No C<update> is necessary. All entries and calculations are managed
1748 with ajax-calls and the page does only reload on C<save>.
1749
1750 =item *
1751
1752 User can see changes immediately, because of the use of java script
1753 and ajax.
1754
1755 =back
1756
1757 =head1 CODE
1758
1759 =head2 Layout
1760
1761 =over 4
1762
1763 =item * C<SL/Controller/Order.pm>
1764
1765 the controller
1766
1767 =item * C<template/webpages/order/form.html>
1768
1769 main form
1770
1771 =item * C<template/webpages/order/tabs/basic_data.html>
1772
1773 Main tab for basic_data.
1774
1775 This is the only tab here for now. "linked records" and "webdav" tabs are
1776 reused from generic code.
1777
1778 =over 4
1779
1780 =item * C<template/webpages/order/tabs/_business_info_row.html>
1781
1782 For displaying information on business type
1783
1784 =item * C<template/webpages/order/tabs/_item_input.html>
1785
1786 The input line for items
1787
1788 =item * C<template/webpages/order/tabs/_row.html>
1789
1790 One row for already entered items
1791
1792 =item * C<template/webpages/order/tabs/_tax_row.html>
1793
1794 Displaying tax information
1795
1796 =item * C<template/webpages/order/tabs/_multi_items_dialog.html>
1797
1798 Dialog for entering more than one item at once
1799
1800 =item * C<template/webpages/order/tabs/_multi_items_result.html>
1801
1802 Results for the filter in the multi items dialog
1803
1804 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
1805
1806 Dialog for selecting price and discount sources
1807
1808 =back
1809
1810 =item * C<js/kivi.Order.js>
1811
1812 java script functions
1813
1814 =back
1815
1816 =head1 TODO
1817
1818 =over 4
1819
1820 =item * testing
1821
1822 =item * currency
1823
1824 =item * credit limit
1825
1826 =item * more workflows (save as new, quotation, purchase order)
1827
1828 =item * price sources: little symbols showing better price / better discount
1829
1830 =item * select units in input row?
1831
1832 =item * custom shipto address
1833
1834 =item * check for direct delivery (workflow sales order -> purchase order)
1835
1836 =item * language / part translations
1837
1838 =item * access rights
1839
1840 =item * display weights
1841
1842 =item * history
1843
1844 =item * mtime check
1845
1846 =item * optional client/user behaviour
1847
1848 (transactions has to be set - department has to be set -
1849  force project if enabled in client config - transport cost reminder)
1850
1851 =back
1852
1853 =head1 KNOWN BUGS AND CAVEATS
1854
1855 =over 4
1856
1857 =item *
1858
1859 Customer discount is not displayed as a valid discount in price source popup
1860 (this might be a bug in price sources)
1861
1862 (I cannot reproduce this (Bernd))
1863
1864 =item *
1865
1866 No indication that <shift>-up/down expands/collapses second row.
1867
1868 =item *
1869
1870 Inline creation of parts is not currently supported
1871
1872 =item *
1873
1874 Table header is not sticky in the scrolling area.
1875
1876 =item *
1877
1878 Sorting does not include C<position>, neither does reordering.
1879
1880 This behavior was implemented intentionally. But we can discuss, which behavior
1881 should be implemented.
1882
1883 =item *
1884
1885 C<show_multi_items_dialog> does not use the currently inserted string for
1886 filtering.
1887
1888 =item *
1889
1890 The language selected in print or email dialog is not saved when the order is saved.
1891
1892 =back
1893
1894 =head1 To discuss / Nice to have
1895
1896 =over 4
1897
1898 =item *
1899
1900 How to expand/collapse second row. Now it can be done clicking the icon or
1901 <shift>-up/down.
1902
1903 =item *
1904
1905 Possibility to change longdescription in input row?
1906
1907 =item *
1908
1909 Possibility to select PriceSources in input row?
1910
1911 =item *
1912
1913 This controller uses a (changed) copy of the template for the PriceSource
1914 dialog. Maybe there could be used one code source.
1915
1916 =item *
1917
1918 Rounding-differences between this controller (PriceTaxCalculator) and the old
1919 form. This is not only a problem here, but also in all parts using the PTC.
1920 There exists a ticket and a patch. This patch should be testet.
1921
1922 =item *
1923
1924 An indicator, if the actual inputs are saved (like in an
1925 editor or on text processing application).
1926
1927 =item *
1928
1929 A warning when leaving the page without saveing unchanged inputs.
1930
1931 =item *
1932
1933 Workflows for delivery order and invoice are in the menu "Save", because the
1934 order is saved before opening the new document form. Nevertheless perhaps these
1935 workflow buttons should be put under "Workflows".
1936
1937
1938 =back
1939
1940 =head1 AUTHOR
1941
1942 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>
1943
1944 =cut