144a195d24c68ae118f063f623c62df22bcca07f
[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;
8 use SL::Locale::String qw(t8);
9 use SL::SessionFile::Random;
10 use SL::PriceSource;
11 use SL::Webdav;
12
13 use SL::DB::Order;
14 use SL::DB::Default;
15 use SL::DB::Unit;
16 use SL::DB::Part;
17 use SL::DB::Printer;
18 use SL::DB::Language;
19
20 use SL::Helper::CreatePDF qw(:all);
21 use SL::Helper::PrintOptions;
22
23 use SL::Controller::Helper::GetModels;
24
25 use List::Util qw(first);
26 use List::MoreUtils qw(none pairwise first_index);
27 use English qw(-no_match_vars);
28 use File::Spec;
29
30 use Rose::Object::MakeMethods::Generic
31 (
32  scalar => [ qw(item_ids_to_delete) ],
33  'scalar --get_set_init' => [ qw(order valid_types type cv p multi_items_models all_price_factors) ],
34 );
35
36
37 # safety
38 __PACKAGE__->run_before('_check_auth');
39
40 __PACKAGE__->run_before('_recalc',
41                         only => [ qw(save save_and_delivery_order print create_pdf send_email) ]);
42
43 __PACKAGE__->run_before('_get_unalterable_data',
44                         only => [ qw(save save_and_delivery_order print create_pdf send_email) ]);
45
46 #
47 # actions
48 #
49
50 # add a new order
51 sub action_add {
52   my ($self) = @_;
53
54   $self->order->transdate(DateTime->now_local());
55   $self->order->reqdate(DateTime->today_local->next_workday) if !$self->order->reqdate;
56
57   $self->_pre_render();
58   $self->render(
59     'order/form',
60     title => $self->type eq _sales_order_type()    ? $::locale->text('Add Sales Order')
61            : $self->type eq _purchase_order_type() ? $::locale->text('Add Purchase Order')
62            : '',
63     %{$self->{template_args}}
64   );
65 }
66
67 # edit an existing order
68 sub action_edit {
69   my ($self) = @_;
70
71   $self->_load_order;
72   $self->_recalc();
73   $self->_pre_render();
74   $self->render(
75     'order/form',
76     title => $self->type eq _sales_order_type()    ? $::locale->text('Edit Sales Order')
77            : $self->type eq _purchase_order_type() ? $::locale->text('Edit Purchase Order')
78            : '',
79     %{$self->{template_args}}
80   );
81 }
82
83 # delete the order
84 sub action_delete {
85   my ($self) = @_;
86
87   my $errors = $self->_delete();
88
89   if (scalar @{ $errors }) {
90     $self->js->flash('error', $_) foreach @{ $errors };
91     return $self->js->render();
92   }
93
94   flash_later('info', $::locale->text('The order has been deleted'));
95   my @redirect_params = (
96     action => 'add',
97     type   => $self->type,
98   );
99
100   $self->redirect_to(@redirect_params);
101 }
102
103 # save the order
104 sub action_save {
105   my ($self) = @_;
106
107   my $errors = $self->_save();
108
109   if (scalar @{ $errors }) {
110     $self->js->flash('error', $_) foreach @{ $errors };
111     return $self->js->render();
112   }
113
114   flash_later('info', $::locale->text('The order has been saved'));
115   my @redirect_params = (
116     action => 'edit',
117     type   => $self->type,
118     id     => $self->order->id,
119   );
120
121   $self->redirect_to(@redirect_params);
122 }
123
124 # print the order
125 #
126 # This is called if "print" is pressed in the print dialog.
127 # If PDF creation was requested and succeeded, the pdf is stored in a session
128 # file and the filename is stored as session value with an unique key. A
129 # javascript function with this key is then called. This function calls the
130 # download action below (action_download_pdf), which offers the file for
131 # download.
132 sub action_print {
133   my ($self) = @_;
134
135   my $format      = $::form->{print_options}->{format};
136   my $media       = $::form->{print_options}->{media};
137   my $formname    = $::form->{print_options}->{formname};
138   my $copies      = $::form->{print_options}->{copies};
139   my $groupitems  = $::form->{print_options}->{groupitems};
140
141   # only pdf by now
142   if (none { $format eq $_ } qw(pdf)) {
143     return $self->js->flash('error', t8('Format \'#1\' is not supported yet/anymore.', $format))->render;
144   }
145
146   # only screen or printer by now
147   if (none { $media eq $_ } qw(screen printer)) {
148     return $self->js->flash('error', t8('Media \'#1\' is not supported yet/anymore.', $media))->render;
149   }
150
151   my $language;
152   $language = SL::DB::Language->new(id => $::form->{print_options}->{language_id})->load if $::form->{print_options}->{language_id};
153
154   my $form = Form->new;
155   $form->{ordnumber} = $self->order->ordnumber;
156   $form->{type}      = $self->type;
157   $form->{format}    = $format;
158   $form->{formname}  = $formname;
159   $form->{language}  = '_' . $language->template_code if $language;
160   my $pdf_filename   = $form->generate_attachment_filename();
161
162   my $pdf;
163   my @errors = _create_pdf($self->order, \$pdf, { format     => $format,
164                                                   formname   => $formname,
165                                                   language   => $language,
166                                                   groupitems => $groupitems });
167   if (scalar @errors) {
168     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render;
169   }
170
171   if ($media eq 'screen') {
172     # screen/download
173     my $sfile = SL::SessionFile::Random->new(mode => "w");
174     $sfile->fh->print($pdf);
175     $sfile->fh->close;
176
177     my $key = join('_', Time::HiRes::gettimeofday(), int rand 1000000000000);
178     $::auth->set_session_value("Order::create_pdf-${key}" => $sfile->file_name);
179
180     $self->js
181     ->run('kivi.Order.download_pdf', $pdf_filename, $key)
182     ->flash('info', t8('The PDF has been created'));
183
184   } elsif ($media eq 'printer') {
185     # printer
186     my $printer_id = $::form->{print_options}->{printer_id};
187     SL::DB::Printer->new(id => $printer_id)->load->print_document(
188       copies  => $copies,
189       content => $pdf,
190     );
191
192     $self->js->flash('info', t8('The PDF has been printed'));
193   }
194
195   # copy file to webdav folder
196   if ($self->order->ordnumber && $::instance_conf->get_webdav_documents) {
197     my $webdav = SL::Webdav->new(
198       type     => $self->type,
199       number   => $self->order->ordnumber,
200     );
201     my $webdav_file = SL::Webdav::File->new(
202       webdav   => $webdav,
203       filename => $pdf_filename,
204     );
205     eval {
206       $webdav_file->store(data => \$pdf);
207       1;
208     } or do {
209       $self->js->flash('error', t8('Storing PDF to webdav folder failed: #1', $@));
210     }
211   }
212
213   $self->js->render;
214 }
215
216 # offer pdf for download
217 #
218 # It needs to get the key for the session value to get the pdf file.
219 sub action_download_pdf {
220   my ($self) = @_;
221
222   my $key = $::form->{key};
223   my $tmp_filename = $::auth->get_session_value("Order::create_pdf-${key}");
224   return $self->send_file(
225     $tmp_filename,
226     type => 'application/pdf',
227     name => $::form->{pdf_filename},
228   );
229 }
230
231 # open the email dialog
232 sub action_show_email_dialog {
233   my ($self) = @_;
234
235   my $cv_method = $self->cv;
236
237   if (!$self->order->$cv_method) {
238     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'))
239                     ->render($self);
240   }
241
242   $self->{email}->{to}   = $self->order->contact->cp_email if $self->order->contact;
243   $self->{email}->{to} ||= $self->order->$cv_method->email;
244   $self->{email}->{cc}   = $self->order->$cv_method->cc;
245   $self->{email}->{bcc}  = join ', ', grep $_, $self->order->$cv_method->bcc, SL::DB::Default->get->global_bcc;
246   # Todo: get addresses from shipto, if any
247
248   my $form = Form->new;
249   $form->{ordnumber} = $self->order->ordnumber;
250   $form->{formname}  = $self->type;
251   $form->{type}      = $self->type;
252   $form->{language} = 'de';
253   $form->{format}   = 'pdf';
254
255   $self->{email}->{subject}             = $form->generate_email_subject();
256   $self->{email}->{attachment_filename} = $form->generate_attachment_filename();
257   $self->{email}->{message}             = $form->create_email_signature();
258
259   my $dialog_html = $self->render('order/tabs/_email_dialog', { output => 0 });
260   $self->js
261       ->run('kivi.Order.show_email_dialog', $dialog_html)
262       ->reinit_widgets
263       ->render($self);
264 }
265
266 # send email
267 #
268 # Todo: handling error messages: flash is not displayed in dialog, but in the main form
269 sub action_send_email {
270   my ($self) = @_;
271
272   my $mail      = Mailer->new;
273   $mail->{from} = qq|"$::myconfig{name}" <$::myconfig{email}>|;
274   $mail->{$_}   = $::form->{email}->{$_} for qw(to cc bcc subject message);
275
276   my $pdf;
277   my @errors = _create_pdf($self->order, \$pdf, {media => 'email'});
278   if (scalar @errors) {
279     return $self->js->flash('error', t8('Conversion to PDF failed: #1', $errors[0]))->render($self);
280   }
281
282   $mail->{attachments} = [{ "content" => $pdf,
283                             "name"    => $::form->{email}->{attachment_filename} }];
284
285   if (my $err = $mail->send) {
286     return $self->js->flash('error', t8('Sending E-mail: ') . $err)
287                     ->render($self);
288   }
289
290   # internal notes
291   my $intnotes = $self->order->intnotes;
292   $intnotes   .= "\n\n" if $self->order->intnotes;
293   $intnotes   .= t8('[email]')                                                                                        . "\n";
294   $intnotes   .= t8('Date')       . ": " . $::locale->format_date_object(DateTime->now_local, precision => 'seconds') . "\n";
295   $intnotes   .= t8('To (email)') . ": " . $mail->{to}                                                                . "\n";
296   $intnotes   .= t8('Cc')         . ": " . $mail->{cc}                                                                . "\n"    if $mail->{cc};
297   $intnotes   .= t8('Bcc')        . ": " . $mail->{bcc}                                                               . "\n"    if $mail->{bcc};
298   $intnotes   .= t8('Subject')    . ": " . $mail->{subject}                                                           . "\n\n";
299   $intnotes   .= t8('Message')    . ": " . $mail->{message};
300
301   $self->js
302       ->val('#order_intnotes', $intnotes)
303       ->run('kivi.Order.close_email_dialog')
304       ->render($self);
305 }
306
307 # save the order and redirect to the frontend subroutine for a new
308 # delivery order
309 sub action_save_and_delivery_order {
310   my ($self) = @_;
311
312   my $errors = $self->_save();
313
314   if (scalar @{ $errors }) {
315     $self->js->flash('error', $_) foreach @{ $errors };
316     return $self->js->render();
317   }
318   flash_later('info', $::locale->text('The order has been saved'));
319
320   my @redirect_params = (
321     controller => 'oe.pl',
322     action     => 'oe_delivery_order_from_order',
323     id         => $self->order->id,
324   );
325
326   $self->redirect_to(@redirect_params);
327 }
328
329 # set form elements in respect to a changed customer or vendor
330 #
331 # This action is called on an change of the customer/vendor picker.
332 sub action_customer_vendor_changed {
333   my ($self) = @_;
334
335   my $cv_method = $self->cv;
336
337   if ($self->order->$cv_method->contacts && scalar @{ $self->order->$cv_method->contacts } > 0) {
338     $self->js->show('#cp_row');
339   } else {
340     $self->js->hide('#cp_row');
341   }
342
343   if ($self->order->$cv_method->shipto && scalar @{ $self->order->$cv_method->shipto } > 0) {
344     $self->js->show('#shipto_row');
345   } else {
346     $self->js->hide('#shipto_row');
347   }
348
349   $self->order->taxzone_id($self->order->$cv_method->taxzone_id);
350
351   if ($self->order->is_sales) {
352     $self->order->taxincluded(defined($self->order->$cv_method->taxincluded_checked)
353                               ? $self->order->$cv_method->taxincluded_checked
354                               : $::myconfig{taxincluded_checked});
355   }
356
357   $self->order->payment_id($self->order->$cv_method->payment_id);
358   $self->order->delivery_term_id($self->order->$cv_method->delivery_term_id);
359
360   $self->_recalc();
361
362   $self->js
363     ->replaceWith('#order_cp_id',            $self->build_contact_select)
364     ->replaceWith('#order_shipto_id',        $self->build_shipto_select)
365     ->val(        '#order_taxzone_id',       $self->order->taxzone_id)
366     ->val(        '#order_taxincluded',      $self->order->taxincluded)
367     ->val(        '#order_payment_id',       $self->order->payment_id)
368     ->val(        '#order_delivery_term_id', $self->order->delivery_term_id)
369     ->val(        '#order_intnotes',         $self->order->$cv_method->notes)
370     ->focus(      '#order_' . $self->cv . '_id');
371
372   $self->_js_redisplay_amounts_and_taxes;
373   $self->js->render();
374 }
375
376 # called if a unit in an existing item row is changed
377 sub action_unit_changed {
378   my ($self) = @_;
379
380   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
381   my $item = $self->order->items_sorted->[$idx];
382
383   my $old_unit_obj = SL::DB::Unit->new(name => $::form->{old_unit})->load;
384   $item->sellprice($item->unit_obj->convert_to($item->sellprice, $old_unit_obj));
385
386   $self->_recalc();
387
388   $self->js
389     ->run('kivi.Order.update_sellprice', $::form->{item_id}, $item->sellprice_as_number);
390   $self->_js_redisplay_linetotals;
391   $self->_js_redisplay_amounts_and_taxes;
392   $self->js->render();
393 }
394
395 # add an item row for a new item entered in the input row
396 sub action_add_item {
397   my ($self) = @_;
398
399   my $form_attr = $::form->{add_item};
400
401   return unless $form_attr->{parts_id};
402
403   my $item = _new_item($self->order, $form_attr);
404
405   $self->order->add_items($item);
406
407   $self->_recalc();
408
409   my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
410   my $row_as_html = $self->p->render('order/tabs/_row',
411                                      ITEM              => $item,
412                                      ID                => $item_id,
413                                      ALL_PRICE_FACTORS => $self->all_price_factors
414   );
415
416   $self->js
417     ->append('#row_table_id', $row_as_html);
418
419   if ( $item->part->is_assortment ) {
420     $form_attr->{qty_as_number} = 1 unless $form_attr->{qty_as_number};
421     foreach my $assortment_item ( @{$item->part->assortment_items} ) {
422       my $attr = { parts_id => $assortment_item->parts_id,
423                    qty      => $assortment_item->qty * $::form->parse_amount(\%::myconfig, $form_attr->{qty_as_number}), # TODO $form_attr->{unit}
424                    unit     => $assortment_item->unit,
425                    description => $assortment_item->part->description,
426                  };
427       my $item = _new_item($self->order, $attr);
428
429       # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
430       $item->discount(1) unless $assortment_item->charge;
431
432       $self->order->add_items( $item );
433       $self->_recalc();
434       my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
435       my $row_as_html = $self->p->render('order/tabs/_row',
436                                          ITEM              => $item,
437                                          ID                => $item_id,
438                                          ALL_PRICE_FACTORS => $self->all_price_factors
439       );
440       $self->js
441         ->append('#row_table_id', $row_as_html);
442     };
443   };
444
445   $self->js
446     ->val('.add_item_input', '')
447     ->run('kivi.Order.init_row_handlers')
448     ->run('kivi.Order.row_table_scroll_down')
449     ->run('kivi.Order.renumber_positions')
450     ->focus('#add_item_parts_id_name');
451
452   $self->_js_redisplay_amounts_and_taxes;
453   $self->js->render();
454 }
455
456 # open the dialog for entering multiple items at once
457 sub action_show_multi_items_dialog {
458   require SL::DB::PartsGroup;
459   $_[0]->render('order/tabs/_multi_items_dialog', { layout => 0 },
460                 all_partsgroups => SL::DB::Manager::PartsGroup->get_all);
461 }
462
463 # update the filter results in the multi item dialog
464 sub action_multi_items_update_result {
465   my $max_count = 100;
466
467   $::form->{multi_items}->{filter}->{obsolete} = 0;
468
469   my $count = $_[0]->multi_items_models->count;
470
471   if ($count == 0) {
472     my $text = SL::Presenter::EscapedText->new(text => $::locale->text('No results.'));
473     $_[0]->render($text, { layout => 0 });
474   } elsif ($count > $max_count) {
475     my $text = SL::Presenter::EscapedText->new(text => $::locale->text('Too many results (#1 from #2).', $count, $max_count));
476     $_[0]->render($text, { layout => 0 });
477   } else {
478     my $multi_items = $_[0]->multi_items_models->get;
479     $_[0]->render('order/tabs/_multi_items_result', { layout => 0 },
480                   multi_items => $multi_items);
481   }
482 }
483
484 # add item rows for multiple items at once
485 sub action_add_multi_items {
486   my ($self) = @_;
487
488   my @form_attr = grep { $_->{qty_as_number} } @{ $::form->{add_multi_items} };
489   return $self->js->render() unless scalar @form_attr;
490
491   my @items;
492   foreach my $attr (@form_attr) {
493     my $item = _new_item($self->order, $attr);
494     push @items, $item;
495     if ( $item->part->is_assortment ) {
496       foreach my $assortment_item ( @{$item->part->assortment_items} ) {
497         my $attr = { parts_id => $assortment_item->parts_id,
498                      qty      => $assortment_item->qty * $item->qty, # TODO $form_attr->{unit}
499                      unit     => $assortment_item->unit,
500                      description => $assortment_item->part->description,
501                    };
502         my $item = _new_item($self->order, $attr);
503
504         # set discount to 100% if item isn't supposed to be charged, overwriting any customer discount
505         $item->discount(1) unless $assortment_item->charge;
506         push @items, $assortment_item;
507       }
508     }
509   }
510   $self->order->add_items(@items);
511
512   $self->_recalc();
513
514   foreach my $item (@items) {
515     my $item_id = join('_', 'new', Time::HiRes::gettimeofday(), int rand 1000000000000);
516     my $row_as_html = $self->p->render('order/tabs/_row',
517                                        ITEM              => $item,
518                                        ID                => $item_id,
519                                        ALL_PRICE_FACTORS => $self->all_price_factors
520     );
521
522     $self->js->append('#row_table_id', $row_as_html);
523   }
524
525   $self->js
526     ->run('kivi.Order.close_multi_items_dialog')
527     ->run('kivi.Order.init_row_handlers')
528     ->run('kivi.Order.row_table_scroll_down')
529     ->run('kivi.Order.renumber_positions')
530     ->focus('#add_item_parts_id_name');
531
532   $self->_js_redisplay_amounts_and_taxes;
533   $self->js->render();
534 }
535
536 # recalculate all linetotals, amounts and taxes and redisplay them
537 sub action_recalc_amounts_and_taxes {
538   my ($self) = @_;
539
540   $self->_recalc();
541
542   $self->_js_redisplay_linetotals;
543   $self->_js_redisplay_amounts_and_taxes;
544   $self->js->render();
545 }
546
547 # redisplay item rows if they are sorted by an attribute
548 sub action_reorder_items {
549   my ($self) = @_;
550
551   my %sort_keys = (
552     partnumber  => sub { $_[0]->part->partnumber },
553     description => sub { $_[0]->description },
554     qty         => sub { $_[0]->qty },
555     sellprice   => sub { $_[0]->sellprice },
556     discount    => sub { $_[0]->discount },
557   );
558
559   my $method = $sort_keys{$::form->{order_by}};
560   my @to_sort = map { { old_pos => $_->position, order_by => $method->($_) } } @{ $self->order->items_sorted };
561   if ($::form->{sort_dir}) {
562     @to_sort = sort { $a->{order_by} cmp $b->{order_by} } @to_sort;
563   } else {
564     @to_sort = sort { $b->{order_by} cmp $a->{order_by} } @to_sort;
565   }
566   $self->js
567     ->run('kivi.Order.redisplay_items', \@to_sort)
568     ->render;
569 }
570
571 # show the popup to choose a price/discount source
572 sub action_price_popup {
573   my ($self) = @_;
574
575   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
576   my $item = $self->order->items_sorted->[$idx];
577
578   $self->render_price_dialog($item);
579 }
580
581 # get the longdescription for an item if the dialog to enter/change the
582 # longdescription was opened and the longdescription is empty
583 #
584 # If this item is new, get the longdescription from Part.
585 # Otherwise get it from OrderItem.
586 sub action_get_item_longdescription {
587   my $longdescription;
588
589   if ($::form->{item_id}) {
590     $longdescription = SL::DB::OrderItem->new(id => $::form->{item_id})->load->longdescription;
591   } elsif ($::form->{parts_id}) {
592     $longdescription = SL::DB::Part->new(id => $::form->{parts_id})->load->notes;
593   }
594   $_[0]->render(\ $longdescription, { type => 'text' });
595 }
596
597 # load the second row for an item (cvars only for now)
598 #
599 # This action gets the html code for the items second row by rendering a template for
600 # the second row and calls a javascript function with this html code via client js.
601 sub action_load_second_row {
602   my ($self) = @_;
603
604   my $idx  = first_index { $_ eq $::form->{item_id} } @{ $::form->{orderitem_ids} };
605   my $item = $self->order->items_sorted->[$idx];
606
607   # Parse values from form (they are formated while rendering (template)).
608   # Workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
609   # This parsing is not necessary at all, if we assure that the second row/cvars are only loaded once.
610   #foreach my $var (@{ $item->cvars_by_config }) {
611   #  $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
612   #}
613   #$item->parse_custom_variable_values;
614
615   my $row_as_html = $self->p->render('order/tabs/_second_row', ITEM => $item);
616
617   $self->js
618     ->html('.row_entry:has(#item_' . $::form->{item_id} . ') [name = "second_row"]', $row_as_html)
619     ->data('.row_entry:has(#item_' . $::form->{item_id} . ') [name = "second_row"]', 'loaded', 1)
620     ->render();
621 }
622
623 sub _js_redisplay_linetotals {
624   my ($self) = @_;
625
626   my @data = map {$::form->format_amount(\%::myconfig, $_->{linetotal}, 2, 0)} @{ $self->order->items_sorted };
627   $self->js
628     ->run('kivi.Order.redisplay_linetotals', \@data);
629 }
630
631 sub _js_redisplay_amounts_and_taxes {
632   my ($self) = @_;
633
634   if (scalar @{ $self->{taxes} }) {
635     $self->js->show('#taxincluded_row_id');
636   } else {
637     $self->js->hide('#taxincluded_row_id');
638   }
639
640   if ($self->order->taxincluded) {
641     $self->js->hide('#subtotal_row_id');
642   } else {
643     $self->js->show('#subtotal_row_id');
644   }
645
646   $self->js
647     ->html('#netamount_id', $::form->format_amount(\%::myconfig, $self->order->netamount, -2))
648     ->html('#amount_id',    $::form->format_amount(\%::myconfig, $self->order->amount,    -2))
649     ->remove('.tax_row')
650     ->insertBefore($self->build_tax_rows, '#amount_row_id');
651 }
652
653 #
654 # helpers
655 #
656
657 sub init_valid_types {
658   [ _sales_order_type(), _purchase_order_type() ];
659 }
660
661 sub init_type {
662   my ($self) = @_;
663
664   if (none { $::form->{type} eq $_ } @{$self->valid_types}) {
665     die "Not a valid type for order";
666   }
667
668   $self->type($::form->{type});
669 }
670
671 sub init_cv {
672   my ($self) = @_;
673
674   my $cv = $self->type eq _sales_order_type()    ? 'customer'
675          : $self->type eq _purchase_order_type() ? 'vendor'
676          : die "Not a valid type for order";
677
678   return $cv;
679 }
680
681 sub init_p {
682   SL::Presenter->get;
683 }
684
685 sub init_order {
686   $_[0]->_make_order;
687 }
688
689 # model used to filter/display the parts in the multi-items dialog
690 sub init_multi_items_models {
691   SL::Controller::Helper::GetModels->new(
692     controller     => $_[0],
693     model          => 'Part',
694     with_objects   => [ qw(unit_obj) ],
695     disable_plugin => 'paginated',
696     source         => $::form->{multi_items},
697     sorted         => {
698       _default    => {
699         by  => 'partnumber',
700         dir => 1,
701       },
702       partnumber  => t8('Partnumber'),
703       description => t8('Description')}
704   );
705 }
706
707 sub init_all_price_factors {
708   SL::DB::Manager::PriceFactor->get_all;
709 }
710
711 sub _check_auth {
712   my ($self) = @_;
713
714   my $right_for = { map { $_ => $_.'_edit' } @{$self->valid_types} };
715
716   my $right   = $right_for->{ $self->type };
717   $right    ||= 'DOES_NOT_EXIST';
718
719   $::auth->assert($right);
720 }
721
722 # build the selection box for contacts
723 #
724 # Needed, if customer/vendor changed.
725 sub build_contact_select {
726   my ($self) = @_;
727
728   $self->p->select_tag('order.cp_id', [ $self->order->{$self->cv}->contacts ],
729                        value_key  => 'cp_id',
730                        title_key  => 'full_name_dep',
731                        default    => $self->order->cp_id,
732                        with_empty => 1,
733                        style      => 'width: 300px',
734   );
735 }
736
737 # build the selection box for shiptos
738 #
739 # Needed, if customer/vendor changed.
740 sub build_shipto_select {
741   my ($self) = @_;
742
743   $self->p->select_tag('order.shipto_id', [ $self->order->{$self->cv}->shipto ],
744                        value_key  => 'shipto_id',
745                        title_key  => 'displayable_id',
746                        default    => $self->order->shipto_id,
747                        with_empty => 1,
748                        style      => 'width: 300px',
749   );
750 }
751
752 # build the rows for displaying taxes
753 #
754 # Called if amounts where recalculated and redisplayed.
755 sub build_tax_rows {
756   my ($self) = @_;
757
758   my $rows_as_html;
759   foreach my $tax (sort { $a->{tax}->rate cmp $b->{tax}->rate } @{ $self->{taxes} }) {
760     $rows_as_html .= $self->p->render('order/tabs/_tax_row', TAX => $tax, TAXINCLUDED => $self->order->taxincluded);
761   }
762   return $rows_as_html;
763 }
764
765
766 sub render_price_dialog {
767   my ($self, $record_item) = @_;
768
769   my $price_source = SL::PriceSource->new(record_item => $record_item, record => $self->order);
770
771   $self->js
772     ->run(
773       'kivi.io.price_chooser_dialog',
774       t8('Available Prices'),
775       $self->render('order/tabs/_price_sources_dialog', { output => 0 }, price_source => $price_source)
776     )
777     ->reinit_widgets;
778
779 #   if (@errors) {
780 #     $self->js->text('#dialog_flash_error_content', join ' ', @errors);
781 #     $self->js->show('#dialog_flash_error');
782 #   }
783
784   $self->js->render;
785 }
786
787 sub _load_order {
788   my ($self) = @_;
789
790   return if !$::form->{id};
791
792   $self->order(SL::DB::Manager::Order->find_by(id => $::form->{id}));
793 }
794
795 # load or create a new order object
796 #
797 # And assign changes from the for to this object.
798 # If the order is loaded from db, check if items are deleted in the form,
799 # remove them form the object and collect them for removing from db on saving.
800 # Then create/update items from form (via _make_item) and add them.
801 sub _make_order {
802   my ($self) = @_;
803
804   # add_items adds items to an order with no items for saving, but they cannot
805   # be retrieved via items until the order is saved. Adding empty items to new
806   # order here solves this problem.
807   my $order;
808   $order   = SL::DB::Manager::Order->find_by(id => $::form->{id}) if $::form->{id};
809   $order ||= SL::DB::Order->new(orderitems => []);
810
811   my $form_orderitems = delete $::form->{order}->{orderitems};
812   $order->assign_attributes(%{$::form->{order}});
813
814   # remove deleted items
815   $self->item_ids_to_delete([]);
816   foreach my $idx (reverse 0..$#{$order->orderitems}) {
817     my $item = $order->orderitems->[$idx];
818     if (none { $item->id == $_->{id} } @{$form_orderitems}) {
819       splice @{$order->orderitems}, $idx, 1;
820       push @{$self->item_ids_to_delete}, $item->id;
821     }
822   }
823
824   my @items;
825   my $pos = 1;
826   foreach my $form_attr (@{$form_orderitems}) {
827     my $item = _make_item($order, $form_attr);
828     $item->position($pos);
829     push @items, $item;
830     $pos++;
831   }
832   $order->add_items(grep {!$_->id} @items);
833
834   return $order;
835 }
836
837 # create or update items from form
838 #
839 # Make item objects from form values. For items already existing read from db.
840 # Create a new item else. And assign attributes.
841 sub _make_item {
842   my ($record, $attr) = @_;
843
844   my $item;
845   $item = first { $_->id == $attr->{id} } @{$record->items} if $attr->{id};
846
847   my $is_new = !$item;
848
849   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
850   # they cannot be retrieved via custom_variables until the order/orderitem is
851   # saved. Adding empty custom_variables to new orderitem here solves this problem.
852   $item ||= SL::DB::OrderItem->new(custom_variables => []);
853
854   $item->assign_attributes(%$attr);
855   $item->longdescription($item->part->notes) if $is_new && !defined $attr->{longdescription};
856   # item fields that currently can't be set in in row but are needed:
857   $item->lastcost($item->part->lastcost) if $is_new;
858
859   return $item;
860 }
861
862 # create a new item
863 #
864 # This is used to add one (or more) items
865 sub _new_item {
866   my ($record, $attr) = @_;
867
868   my $item = SL::DB::OrderItem->new;
869   $item->assign_attributes(%$attr);
870
871   my $part         = SL::DB::Part->new(id => $attr->{parts_id})->load;
872   my $price_source = SL::PriceSource->new(record_item => $item, record => $record);
873
874   $item->unit($part->unit) if !$item->unit;
875
876   my $price_src;
877   if ( $part->is_assortment ) {
878     # add assortment items with price 0, as the components carry the price
879     $price_src = $price_source->price_from_source("");
880     $price_src->price(0);
881   } elsif ($item->sellprice) {
882     $price_src = $price_source->price_from_source("");
883     $price_src->price($item->sellprice);
884   } else {
885     $price_src = $price_source->best_price
886            ? $price_source->best_price
887            : $price_source->price_from_source("");
888     $price_src->price(0) if !$price_source->best_price;
889   }
890
891   my $discount_src;
892   if ($item->discount) {
893     $discount_src = $price_source->discount_from_source("");
894     $discount_src->discount($item->discount);
895   } else {
896     $discount_src = $price_source->best_discount
897                   ? $price_source->best_discount
898                   : $price_source->discount_from_source("");
899     $discount_src->discount(0) if !$price_source->best_discount;
900   }
901
902   my %new_attr;
903   $new_attr{part}                   = $part;
904   $new_attr{description}            = $part->description     if ! $item->description;
905   $new_attr{qty}                    = 1.0                    if ! $item->qty;
906   $new_attr{price_factor_id}        = $part->price_factor_id if ! $item->price_factor_id;
907   $new_attr{sellprice}              = $price_src->price;
908   $new_attr{discount}               = $discount_src->discount;
909   $new_attr{active_price_source}    = $price_src;
910   $new_attr{active_discount_source} = $discount_src;
911
912   $new_attr{longdescription}        = $part->notes if ! defined $attr->{longdescription};
913
914   # add_custom_variables adds cvars to an orderitem with no cvars for saving, but
915   # they cannot be retrieved via custom_variables until the order/orderitem is
916   # saved. Adding empty custom_variables to new orderitem here solves this problem.
917   $new_attr{custom_variables} = [];
918
919   $item->assign_attributes(%new_attr);
920
921   return $item;
922 }
923
924 # recalculate prices and taxes
925 #
926 # Using the PriceTaxCalculator. Store linetotals in the item objects.
927 sub _recalc {
928   my ($self) = @_;
929
930   # bb: todo: currency later
931   $self->order->currency_id($::instance_conf->get_currency_id());
932
933   my %pat = $self->order->calculate_prices_and_taxes();
934   $self->{taxes} = [];
935   foreach my $tax_chart_id (keys %{ $pat{taxes} }) {
936     my $tax = SL::DB::Manager::Tax->find_by(chart_id => $tax_chart_id);
937
938     my @amount_keys = grep { $pat{amounts}->{$_}->{tax_id} == $tax->id } keys %{ $pat{amounts} };
939     push(@{ $self->{taxes} }, { amount    => $pat{taxes}->{$tax_chart_id},
940                                 netamount => $pat{amounts}->{$amount_keys[0]}->{amount},
941                                 tax       => $tax });
942   }
943
944   pairwise { $a->{linetotal} = $b->{linetotal} } @{$self->order->items}, @{$pat{items}};
945 }
946
947 # get data for saving, printing, ..., that is not changed in the form
948 #
949 # Only cvars for now.
950 sub _get_unalterable_data {
951   my ($self) = @_;
952
953   foreach my $item (@{ $self->order->items }) {
954     # autovivify all cvars that are not in the form (cvars_by_config can do it).
955     # workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
956     foreach my $var (@{ $item->cvars_by_config }) {
957       $var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
958     }
959     $item->parse_custom_variable_values;
960   }
961 }
962
963 # delete the order
964 #
965 # And remove related files in the spool directory
966 sub _delete {
967   my ($self) = @_;
968
969   my $errors = [];
970   my $db     = $self->order->db;
971
972   $db->with_transaction(
973     sub {
974       my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $self->order->id ]) };
975       $self->order->delete;
976       my $spool = $::lx_office_conf{paths}->{spool};
977       unlink map { "$spool/$_" } @spoolfiles if $spool;
978
979       1;
980   }) || push(@{$errors}, $db->error);
981
982   return $errors;
983 }
984
985 # save the order
986 #
987 # And delete items that are deleted in the form.
988 sub _save {
989   my ($self) = @_;
990
991   my $errors = [];
992   my $db     = $self->order->db;
993
994   $db->with_transaction(sub {
995     SL::DB::OrderItem->new(id => $_)->delete for @{$self->item_ids_to_delete};
996     $self->order->save(cascade => 1);
997   }) || push(@{$errors}, $db->error);
998
999   return $errors;
1000 }
1001
1002
1003 sub _pre_render {
1004   my ($self) = @_;
1005
1006   $self->{all_taxzones}        = SL::DB::Manager::TaxZone->get_all_sorted();
1007   $self->{all_departments}     = SL::DB::Manager::Department->get_all_sorted();
1008   $self->{all_employees}       = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->employee_id,
1009                                                                                        deleted => 0 ] ],
1010                                                                     sort_by => 'name');
1011   $self->{all_salesmen}        = SL::DB::Manager::Employee->get_all(where => [ or => [ id => $self->order->salesman_id,
1012                                                                                        deleted => 0 ] ],
1013                                                                     sort_by => 'name');
1014   $self->{all_projects}        = SL::DB::Manager::Project->get_all(where => [ or => [ id => $self->order->globalproject_id,
1015                                                                                       active => 1 ] ],
1016                                                                    sort_by => 'projectnumber');
1017   $self->{all_payment_terms}   = SL::DB::Manager::PaymentTerm->get_all_sorted();
1018   $self->{all_delivery_terms}  = SL::DB::Manager::DeliveryTerm->get_all_sorted();
1019
1020   $self->{current_employee_id} = SL::DB::Manager::Employee->current->id;
1021
1022   my $print_form = Form->new('');
1023   $print_form->{type}      = $self->type;
1024   $print_form->{printers}  = SL::DB::Manager::Printer->get_all_sorted;
1025   $print_form->{languages} = SL::DB::Manager::Language->get_all_sorted;
1026   $self->{print_options}   = SL::Helper::PrintOptions->get_print_options(
1027     form => $print_form,
1028     options => {dialog_name_prefix => 'print_options.',
1029                 show_headers       => 1,
1030                 no_queue           => 1,
1031                 no_postscript      => 1,
1032                 no_opendocument    => 1,
1033                 no_html            => 1},
1034   );
1035
1036   foreach my $item (@{$self->order->orderitems}) {
1037     my $price_source = SL::PriceSource->new(record_item => $item, record => $self->order);
1038     $item->active_price_source(   $price_source->price_from_source(   $item->active_price_source   ));
1039     $item->active_discount_source($price_source->discount_from_source($item->active_discount_source));
1040   }
1041
1042   if ($self->order->ordnumber && $::instance_conf->get_webdav) {
1043     my $webdav = SL::Webdav->new(
1044       type     => $self->type,
1045       number   => $self->order->ordnumber,
1046     );
1047     my $webdav_path = $webdav->webdav_path;
1048     my @all_objects = $webdav->get_all_objects;
1049     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1050                                                     type => t8('File'),
1051                                                     link => File::Spec->catdir($webdav_path, $_->filename),
1052                                                 } } @all_objects;
1053   }
1054
1055   $::request->{layout}->use_javascript("${_}.js")  for qw(kivi.SalesPurchase kivi.Order ckeditor/ckeditor ckeditor/adapters/jquery);
1056 }
1057
1058 sub _create_pdf {
1059   my ($order, $pdf_ref, $params) = @_;
1060
1061   my @errors = ();
1062
1063   my $print_form = Form->new('');
1064   $print_form->{type}        = $order->type;
1065   $print_form->{formname}    = $params->{formname} || $order->type;
1066   $print_form->{format}      = $params->{format}   || 'pdf';
1067   $print_form->{media}       = $params->{media}    || 'file';
1068   $print_form->{groupitems}  = $params->{groupitems};
1069   $print_form->{media}       = 'file'                             if $print_form->{media} eq 'screen';
1070   $print_form->{language}    = $params->{language}->template_code if $print_form->{language};
1071   $print_form->{language_id} = $params->{language}->id            if $print_form->{language};
1072
1073   $order->flatten_to_form($print_form, format_amounts => 1);
1074
1075   # search for the template
1076   my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
1077     name        => $print_form->{formname},
1078     email       => $print_form->{media} eq 'email',
1079     language    => $params->{language},
1080     printer_id  => $print_form->{printer_id},  # todo
1081   );
1082
1083   if (!defined $template_file) {
1084     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);
1085   }
1086
1087   return @errors if scalar @errors;
1088
1089   $print_form->throw_on_error(sub {
1090     eval {
1091       $print_form->prepare_for_printing;
1092
1093       $$pdf_ref = SL::Helper::CreatePDF->create_pdf(
1094         template  => $template_file,
1095         variables => $print_form,
1096         variable_content_types => {
1097           longdescription => 'html',
1098           partnotes       => 'html',
1099           notes           => 'html',
1100         },
1101       );
1102       1;
1103     } || push @errors, ref($EVAL_ERROR) eq 'SL::X::FormError' ? $EVAL_ERROR->getMessage : $EVAL_ERROR;
1104   });
1105
1106   return @errors;
1107 }
1108
1109 sub _sales_order_type {
1110   'sales_order';
1111 }
1112
1113 sub _purchase_order_type {
1114   'purchase_order';
1115 }
1116
1117 1;
1118
1119 __END__
1120
1121 =encoding utf-8
1122
1123 =head1 NAME
1124
1125 SL::Controller::Order - controller for orders
1126
1127 =head1 SYNOPSIS
1128
1129 This is a new form to enter orders, completely rewritten with the use
1130 of controller and java script techniques.
1131
1132 The aim is to provide the user a better expirience and a faster flow
1133 of work. Also the code should be more readable, more reliable and
1134 better to maintain.
1135
1136 =head2 Key Features
1137
1138 =over 4
1139
1140 =item *
1141
1142 One input row, so that input happens every time at the same place.
1143
1144 =item *
1145
1146 Use of pickers where possible.
1147
1148 =item *
1149
1150 Possibility to enter more than one item at once.
1151
1152 =item *
1153
1154 Save order only on "save" (and "save and delivery order"-workflow). No
1155 hidden save on "print" or "email".
1156
1157 =item *
1158
1159 Item list in a scrollable area, so that the workflow buttons stay at
1160 the bottom.
1161
1162 =item *
1163
1164 Reordering item rows with drag and drop is possible. Sorting item rows is
1165 possible (by partnumber, description, qty, sellprice and discount for now).
1166
1167 =item *
1168
1169 No C<update> is necessary. All entries and calculations are managed
1170 with ajax-calls and the page does only reload on C<save>.
1171
1172 =item *
1173
1174 User can see changes immediately, because of the use of java script
1175 and ajax.
1176
1177 =back
1178
1179 =head1 CODE
1180
1181 =head2 Layout
1182
1183 =over 4
1184
1185 =item * C<SL/Controller/Order.pm>
1186
1187 the controller
1188
1189 =item * C<template/webpages/order/form.html>
1190
1191 main form
1192
1193 =item * C<template/webpages/order/tabs/basic_data.html>
1194
1195 Main tab for basic_data.
1196
1197 This is the only tab here for now. "linked records" and "webdav" tabs are
1198 reused from generic code.
1199
1200 =over 4
1201
1202 =item * C<template/webpages/order/tabs/_item_input.html>
1203
1204 The input line for items
1205
1206 =item * C<template/webpages/order/tabs/_row.html>
1207
1208 One row for already entered items
1209
1210 =item * C<template/webpages/order/tabs/_tax_row.html>
1211
1212 Displaying tax information
1213
1214 =item * C<template/webpages/order/tabs/_multi_items_dialog.html>
1215
1216 Dialog for entering more than one item at once
1217
1218 =item * C<template/webpages/order/tabs/_multi_items_result.html>
1219
1220 Results for the filter in the multi items dialog
1221
1222 =item * C<template/webpages/order/tabs/_price_sources_dialog.html>
1223
1224 Dialog for selecting price and discount sources
1225
1226 =item * C<template/webpages/order/tabs/_email_dialog.html>
1227
1228 Email dialog
1229
1230 =back
1231
1232 =item * C<js/kivi.Order.js>
1233
1234 java script functions
1235
1236 =back
1237
1238 =head1 TODO
1239
1240 =over 4
1241
1242 =item * testing
1243
1244 =item * currency
1245
1246 =item * customer/vendor details ('D'-button)
1247
1248 =item * credit limit
1249
1250 =item * more workflows (save as new / invoice)
1251
1252 =item * price sources: little symbols showing better price / better discount
1253
1254 =item * custom shipto address
1255
1256 =item * periodic invoices
1257
1258 =item * more details on second row (marge, ...)
1259
1260 =item * language / part translations
1261
1262 =item * access rights
1263
1264 =item * preset salesman from customer
1265
1266 =item * display weights
1267
1268 =item * force project if enabled in client config
1269
1270 =item * history
1271
1272 =item * mtime check
1273
1274 =back
1275
1276 =head1 KNOWN BUGS AND CAVEATS
1277
1278 =over 4
1279
1280 =item *
1281
1282 Customer discount is not displayed as a valid discount in price source popup
1283 (this might be a bug in price sources)
1284
1285 =item *
1286
1287 No indication that double click expands second row, no exand all button
1288
1289 =item *
1290
1291 Implementation of second row with a tbody for every item is not supported by
1292 our css.
1293
1294 =item *
1295
1296 As a consequence row striping does not currently work
1297
1298 =item *
1299
1300 Inline creation of parts is not currently supported
1301
1302 =item *
1303
1304 Table header is not sticky in the scrolling area.
1305
1306 =item *
1307
1308 Sorting does not include C<position>, neither does reordering.
1309
1310 This behavior was implemented intentionally. But we can discuss, which behavior
1311 should be implemented.
1312
1313 =item *
1314
1315 C<show_multi_items_dialog> does not use the currently inserted string for
1316 filtering.
1317
1318 =back
1319
1320 =head1 AUTHOR
1321
1322 Bernd Bleßmann E<lt>bernd@kivitendo-premium.deE<gt>
1323
1324 =cut