RequirementSpec Suche auf GetModels umgestellt.
[kivitendo-erp.git] / SL / Controller / RequirementSpec.pm
1 package SL::Controller::RequirementSpec;
2
3 use strict;
4 use utf8;
5
6 use parent qw(SL::Controller::Base);
7
8 use File::Spec ();
9
10 use SL::ClientJS;
11 use SL::Common ();
12 use SL::Controller::Helper::GetModels;
13 use SL::Controller::Helper::ReportGenerator;
14 use SL::Controller::Helper::RequirementSpec;
15 use SL::DB::Customer;
16 use SL::DB::Project;
17 use SL::DB::ProjectStatus;
18 use SL::DB::ProjectType;
19 use SL::DB::RequirementSpecComplexity;
20 use SL::DB::RequirementSpecRisk;
21 use SL::DB::RequirementSpecStatus;
22 use SL::DB::RequirementSpecType;
23 use SL::DB::RequirementSpec;
24 use SL::Helper::Flash;
25 use SL::Locale::String;
26 use SL::Template::LaTeX;
27
28 use Rose::Object::MakeMethods::Generic
29 (
30   scalar                  => [ qw(requirement_spec_item visible_item visible_section) ],
31   'scalar --get_set_init' => [ qw(requirement_spec customers types statuses complexities risks projects project_types project_statuses default_project_type default_project_status copy_source js
32                                   current_text_block_output_position models) ],
33 );
34
35 __PACKAGE__->run_before('setup');
36
37 my %sort_columns = (
38   customer      => t8('Customer'),
39   title         => t8('Title'),
40   type          => t8('Requirement Spec Type'),
41   status        => t8('Requirement Spec Status'),
42   projectnumber => t8('Project Number'),
43   version       => t8('Version'),
44   mtime         => t8('Last modification'),
45 );
46
47 #
48 # actions
49 #
50
51
52 sub action_list {
53   my ($self) = @_;
54
55   $self->prepare_report;
56   $self->report_generator_list_objects(report => $self->{report}, objects => $self->models->get);
57 }
58
59 sub action_new {
60   my ($self) = @_;
61
62   $self->requirement_spec(SL::DB::RequirementSpec->new(is_template => $::form->{is_template}));
63
64   if ($self->copy_source) {
65     $self->requirement_spec->$_($self->copy_source->$_) for qw(type_id status_id customer_id title hourly_rate)
66   }
67
68   $self->render('requirement_spec/new', title => $self->requirement_spec->is_template ? t8('Create a new requirement spec template') : t8('Create a new requirement spec'));
69 }
70
71 sub action_ajax_show_basic_settings {
72   my ($self) = @_;
73
74   $self->render('requirement_spec/_show_basic_settings', { layout => 0 });
75 }
76
77 sub action_ajax_edit {
78   my ($self) = @_;
79
80   my $html   = $self->render('requirement_spec/_form', { output => 0 }, submit_as => 'ajax');
81
82   $self->js
83     ->hide('#basic_settings')
84     ->after('#basic_settings', $html)
85     ->render($self);
86 }
87
88 sub action_ajax_edit_project_link {
89   my ($self) = @_;
90
91   my $html   = $self->render('requirement_spec/_project_link_form', { output => 0 }, submit_as => 'ajax');
92
93   $self->js
94     ->hide('#basic_settings')
95     ->after('#basic_settings', $html)
96     ->render($self);
97 }
98
99 sub action_ajax_show_time_and_cost_estimate {
100   my ($self) = @_;
101
102   $self->render('requirement_spec/_show_time_and_cost_estimate', { layout => 0 });
103 }
104
105 sub action_ajax_edit_time_and_cost_estimate {
106   my ($self) = @_;
107
108   my $html   = $self->render('requirement_spec/_edit_time_and_cost_estimate', { output => 0 });
109   my $first  = ($self->requirement_spec->sections_sorted || [])->[0];
110   $first     = ($first->children_sorted || [])->[0] if $first;
111
112   $self->js
113    ->hide('#time_cost_estimate')
114    ->after('#time_cost_estimate', $html)
115    ->on('#time_cost_estimate INPUT[type=text]', 'keydown', 'kivi.requirement_spec.time_cost_estimate_input_key_down')
116    ->action_if($first && $first->id, 'focus', '#time_and_cost_estimate_form_complexity_id_' . $first->id)
117    ->render($self);
118 }
119
120 sub action_ajax_save_time_and_cost_estimate {
121   my ($self) = @_;
122
123   $self->requirement_spec->db->do_transaction(sub {
124     # Make Emacs happy
125     1;
126     foreach my $attributes (@{ $::form->{requirement_spec_items} || [] }) {
127       SL::DB::RequirementSpecItem
128         ->new(id => delete $attributes->{id})
129         ->load
130         ->update_attributes(%{ $attributes });
131     }
132
133     1;
134   });
135
136   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $self->requirement_spec->id)->load);
137
138   my $html = $self->render('requirement_spec/_show_time_and_cost_estimate', { output => 0 }, initially_hidden => !!$::form->{keep_open});
139   $self->js->replaceWith('#time_cost_estimate', $html);
140
141   return $self->js->render($self) if $::form->{keep_open};
142
143   $self->js->remove('#time_cost_estimate_form_container');
144
145   if ($self->visible_section) {
146     $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $self->visible_section);
147     $self->js->html('#column-content', $html);
148   }
149
150   $self->js->render($self);
151 }
152
153 sub action_show {
154   my ($self) = @_;
155
156   my $title  = $self->requirement_spec->is_template ? t8('Show requirement spec template') : t8('Show requirement spec');
157   my $item   = $::form->{requirement_spec_item_id} ? SL::DB::RequirementSpecItem->new(id => $::form->{requirement_spec_item_id})->load : @{ $self->requirement_spec->sections_sorted }[0];
158   $self->requirement_spec_item($item);
159
160   $self->render('requirement_spec/show', title => $title);
161 }
162
163 sub action_create {
164   my ($self) = @_;
165
166   $self->requirement_spec(SL::DB::RequirementSpec->new);
167   $self->create_or_update;
168 }
169
170 sub action_update {
171   my ($self) = @_;
172   $self->create_or_update;
173 }
174
175 sub action_update_project_link {
176   my $self   = shift;
177   my $action = delete($::form->{project_link_action}) || 'keep';
178
179   return $self->update_project_link_none_keep_existing($action) if $action =~ m{none|keep|existing};
180   return $self->update_project_link_new($action)                if $action eq 'new';
181   return $self->update_project_link_create($action)             if $action eq 'create';
182
183   die "Unknown project link action '$action'";
184 }
185
186 sub action_destroy {
187   my ($self) = @_;
188
189   if (eval { $self->requirement_spec->delete; 1; }) {
190     flash_later('info',  t8('The requirement spec has been deleted.'));
191   } else {
192     flash_later('error', t8('The requirement spec is in use and cannot be deleted.'));
193   }
194
195   $self->redirect_to(action => 'list');
196 }
197
198 sub action_revert_to {
199   my ($self, %params) = @_;
200
201   return $self->js->error(t8('Cannot revert a versioned copy.'))->render($self) if $self->requirement_spec->working_copy_id;
202
203   my $versioned_copy = SL::DB::RequirementSpec->new(id => $::form->{versioned_copy_id})->load;
204
205   $self->requirement_spec->copy_from($versioned_copy);
206   my $version = $versioned_copy->versions->[0];
207   $version->update_attributes(working_copy_id => $self->requirement_spec->id);
208
209   flash_later('info', t8('The requirement spec has been reverted to version #1.', $self->requirement_spec->version->version_number));
210   $self->js->redirect_to($self->url_for(action => 'show', id => $self->requirement_spec->id))->render($self);
211 }
212
213 sub action_create_pdf {
214   my ($self, %params) = @_;
215
216   my $base_name       = $self->requirement_spec->type->template_file_name || 'requirement_spec';
217   my @pictures        = $self->prepare_pictures_for_printing;
218   my %result          = SL::Template::LaTeX->parse_and_create_pdf("${base_name}.tex", SELF => $self, rspec => $self->requirement_spec);
219
220   unlink @pictures unless ($::lx_office_conf{debug} || {})->{keep_temp_files};
221
222   $::form->error(t8('Conversion to PDF failed: #1', $result{error})) if $result{error};
223
224   my $attachment_name  =  $self->requirement_spec->type->description . ' ' . ($self->requirement_spec->working_copy_id || $self->requirement_spec->id);
225   $attachment_name    .=  ' (v' . $self->requirement_spec->version->version_number . ')' if $self->requirement_spec->version;
226   $attachment_name    .=  '.pdf';
227   $attachment_name     =~ s/[^\wäöüÄÖÜß \-\+\(\)\[\]\{\}\.,]+/_/g;
228
229   $self->send_file($result{file_name}, type => 'application/pdf', name => $attachment_name);
230   unlink $result{file_name};
231 }
232
233 sub action_select_template_to_paste {
234   my ($self) = @_;
235
236   my @templates = grep { @{ $_->sections } || @{ $_->text_blocks } } @{ SL::DB::Manager::RequirementSpec->get_all(where => [ is_template => 1 ], sort_by => 'lower(title)') };
237   $self->render('requirement_spec/select_template_to_paste', { layout => 0 }, TEMPLATES => \@templates);
238 }
239
240 sub action_paste_template {
241   my ($self, %params) = @_;
242
243   my $template = SL::DB::RequirementSpec->new(id => $::form->{template_id})->load;
244   my %result   = $self->requirement_spec->paste_template($template);
245
246   return $self->js->error($self->requirement_spec->error)->render($self) if !%result;
247
248   $self->render_pasted_text_block($_) for sort { $a->position <=> $b->position } @{ $result{text_blocks} };
249   $self->render_pasted_section($_)    for sort { $a->position <=> $b->position } @{ $result{sections}    };
250
251   if (@{ $result{sections} } && (($::form->{current_content_type} || 'sections') eq 'sections') && !$::form->{current_content_id}) {
252     $self->render_first_pasted_section_as_list($result{sections}->[0]);
253   }
254
255   $self->invalidate_version->render($self);
256 }
257
258 #
259 # filters
260 #
261
262 sub setup {
263   my ($self) = @_;
264
265   $::auth->assert('requirement_spec_edit');
266   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec);
267   $::request->{layout}->use_javascript("${_}.js")  for qw(jquery.jstree jquery/jquery.contextMenu jquery/jquery.hotkeys requirement_spec ckeditor/ckeditor ckeditor/adapters/jquery);
268   $self->init_visible_section;
269
270   return 1;
271 }
272
273 sub init_js                     { SL::ClientJS->new                                           }
274 sub init_complexities           { SL::DB::Manager::RequirementSpecComplexity->get_all_sorted  }
275 sub init_default_project_status { SL::DB::Manager::ProjectStatus->find_by(name => 'planning') }
276 sub init_default_project_type   { SL::DB::ProjectType->new(id => 1)->load                     }
277 sub init_project_statuses       { SL::DB::Manager::ProjectStatus->get_all_sorted              }
278 sub init_project_types          { SL::DB::Manager::ProjectType->get_all_sorted                }
279 sub init_projects               { SL::DB::Manager::Project->get_all_sorted                    }
280 sub init_risks                  { SL::DB::Manager::RequirementSpecRisk->get_all_sorted        }
281 sub init_statuses               { SL::DB::Manager::RequirementSpecStatus->get_all_sorted      }
282 sub init_types                  { SL::DB::Manager::RequirementSpecType->get_all_sorted        }
283
284 sub init_customers {
285   my ($self) = @_;
286
287   my @filter = ('!obsolete' => 1);
288   @filter    = ( or => [ @filter, id => $self->requirement_spec->customer_id ] ) if $self->requirement_spec && $self->requirement_spec->customer_id;
289
290   return SL::DB::Manager::Customer->get_all_sorted(where => \@filter);
291 }
292
293 sub init_requirement_spec {
294   my ($self) = @_;
295   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{id})->load || die "No such requirement spec") if $::form->{id};
296 }
297
298 sub init_copy_source {
299   my ($self) = @_;
300   $self->copy_source(SL::DB::RequirementSpec->new(id => $::form->{copy_source_id})->load) if $::form->{copy_source_id};
301 }
302
303 sub init_current_text_block_output_position {
304   my ($self) = @_;
305   $self->current_text_block_output_position($::form->{current_content_type} !~ m/^(?:text-blocks|tb)-(front|back)/ ? -1 : $1 eq 'front' ? 0 : 1);
306 }
307
308 #
309 # helpers
310 #
311
312 sub create_or_update {
313   my $self   = shift;
314   my $is_new = !$self->requirement_spec->id;
315   my $params = delete($::form->{requirement_spec}) || { };
316
317   $self->requirement_spec->assign_attributes(%{ $params });
318
319   my $title  = $is_new && $self->requirement_spec->is_template ? t8('Create a new requirement spec template')
320              : $is_new                                         ? t8('Create a new requirement spec')
321              :            $self->requirement_spec->is_template ? t8('Edit requirement spec template')
322              :                                                   t8('Edit requirement spec');
323
324   my @errors = $self->requirement_spec->validate;
325
326   if (@errors) {
327     return $self->js->error(@errors)->render($self) if $::request->is_ajax;
328
329     flash('error', @errors);
330     $self->render('requirement_spec/new', title => $title);
331     return;
332   }
333
334   my $db = $self->requirement_spec->db;
335   if (!$db->do_transaction(sub {
336     if ($self->copy_source) {
337       $self->requirement_spec($self->copy_source->create_copy(%{ $params }));
338     } else {
339       $self->requirement_spec->save;
340     }
341   })) {
342     $::lxdebug->message(LXDebug::WARN(), "Error: " . $db->error);
343     @errors = ($::locale->text('Saving failed. Error message from the database: #1', $db->error));
344     return $self->js->error(@errors)->render($self) if $::request->is_ajax;
345
346     $self->requirement_spec->id(undef) if $is_new;
347     flash('error', @errors);
348     return $self->render('requirement_spec/new', title => $title);
349   }
350
351   my $info = $self->requirement_spec->is_template ? t8('The requirement spec template has been saved.') : t8('The requirement spec has been saved.');
352
353   if ($::request->is_ajax) {
354     my $header_html = $self->render('requirement_spec/_header', { output => 0 });
355     my $basics_html = $self->render('requirement_spec/_show_basic_settings', { output => 0 });
356     return $self->invalidate_version
357       ->replaceWith('#requirement-spec-header', $header_html)
358       ->replaceWith('#basic_settings',          $basics_html)
359       ->remove('#basic_settings_form')
360       ->flash('info', $info)
361       ->render($self);
362   }
363
364   flash_later('info', $info);
365   $self->redirect_to(action => 'show', id => $self->requirement_spec->id);
366 }
367
368 sub prepare_report {
369   my ($self)      = @_;
370
371   my $is_template = $::form->{is_template};
372   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
373
374   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
375   $self->models->finalize; # for filter laundering
376   my $callback    = $self->models->get_callback;
377
378   $self->{report} = $report;
379
380   my @columns     = $is_template ? qw(title mtime) : qw(title customer status type projectnumber mtime version);
381   my @sortable    = $is_template ? qw(title mtime) : qw(title customer status type projectnumber mtime);
382
383   my %column_defs = (
384     title         => { obj_link => sub { $self->url_for(action => 'show', id => $_[0]->id, callback => $callback) } },
385     mtime         => { sub      => sub { ($_[0]->mtime || $_[0]->itime)->to_kivitendo(precision => 'minute') } },
386   );
387
388   if (!$is_template) {
389     %column_defs = (
390       %column_defs,
391       customer      => { raw_data => sub { $self->presenter->customer($_[0]->customer, display => 'table-cell', callback => $callback) },
392                          sub      => sub { $_[0]->customer->name } },
393       projectnumber => { raw_data => sub { $self->presenter->project($_[0]->project, display => 'table-cell', callback => $callback) },
394                          sub      => sub { $_[0]->project_id ? $_[0]->project->projectnumber : '' } },
395       status        => { sub      => sub { $_[0]->status->description } },
396       type          => { sub      => sub { $_[0]->type->description } },
397       version       => { sub      => sub { $_[0]->version ? $_[0]->version->version_number : t8('Working copy without version') } },
398     );
399   }
400
401   map { $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) } keys %column_defs;
402
403   $report->set_options(
404     std_column_visibility => 1,
405     controller_class      => 'RequirementSpec',
406     output_format         => 'HTML',
407     raw_top_info_text     => $self->render('requirement_spec/report_top',    { output => 0 }, is_template => $is_template),
408     raw_bottom_info_text  => $self->render('requirement_spec/report_bottom', { output => 0 }, models => $self->models),
409     title                 => $is_template ? t8('Requirement Spec Templates') : t8('Requirement Specs'),
410     allow_pdf_export      => 1,
411     allow_csv_export      => 1,
412   );
413   $report->set_columns(%column_defs);
414   $report->set_column_order(@columns);
415   $report->set_export_options(qw(list filter));
416   $report->set_options_from_form;
417   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
418 }
419
420 sub invalidate_version {
421   my ($self) = @_;
422
423   my $rspec  = SL::DB::RequirementSpec->new(id => $self->requirement_spec->id)->load;
424   return $self->js if $rspec->is_template;
425
426   $rspec->invalidate_version;
427
428   my $html = $self->render('requirement_spec/_version', { output => 0 }, requirement_spec => $rspec);
429   return $self->js->html('#requirement_spec_version', $html);
430 }
431
432 sub render_pasted_text_block {
433   my ($self, $text_block, %params) = @_;
434
435   if ($self->current_text_block_output_position == $text_block->output_position) {
436     my $html = $self->render('requirement_spec_text_block/_text_block', { output => 0 }, text_block => $text_block);
437     $self->js
438       ->appendTo($html, '#text-block-list')
439       ->hide('#text-block-list-empty');
440   }
441
442   my $node       = $self->presenter->requirement_spec_text_block_jstree_data($text_block);
443   my $front_back = $text_block->output_position == 0 ? 'front' : 'back';
444   $self->js
445     ->jstree->create_node('#tree', "#tb-${front_back}", 'last', $node)
446     ->jstree->open_node(  '#tree', "#tb-${front_back}");
447 }
448
449 sub render_pasted_section {
450   my ($self, $item, $parent_id) = @_;
451
452   my $node = $self->presenter->requirement_spec_item_jstree_data($item);
453   $self->js
454     ->jstree->create_node('#tree', $parent_id ? "#fb-${parent_id}" : '#sections', 'last', $node)
455     ->jstree->open_node(  '#tree', $parent_id ? "#fb-${parent_id}" : '#sections');
456
457   $self->render_pasted_section($_, $item->id) for @{ $item->children_sorted };
458 }
459
460 sub render_first_pasted_section_as_list {
461   my ($self, $section, %params) = @_;
462
463   my $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $section);
464   $self->js
465     ->html('#column-content', $html)
466     ->val( '#current_content_type', $section->item_type)
467     ->val( '#current_content_id',   $section->id)
468     ->jstree->select_node('#tree', '#fb-' . $section->id);
469 }
470
471 sub prepare_pictures_for_printing {
472   my ($self) = @_;
473
474   my @files;
475   my $userspath = File::Spec->rel2abs($::lx_office_conf{paths}->{userspath});
476   my $target    =  "${userspath}/kivitendo-print-requirement-spec-picture-" . Common::unique_id() . '-';
477
478   foreach my $picture (map { @{ $_->pictures } } @{ $self->requirement_spec->text_blocks }) {
479     my $output_file_name        = $target . $picture->id . '.' . $picture->get_default_file_name_extension;
480     $picture->{print_file_name} = File::Spec->abs2rel($output_file_name, $userspath);
481     my $out                     = IO::File->new($output_file_name, 'w') || die("Could not create file " . $output_file_name);
482     $out->binmode;
483     $out->print($picture->picture_content);
484     $out->close;
485
486     push @files, $output_file_name;
487   }
488
489   return @files;
490 }
491
492 sub update_project_link_none_keep_existing {
493   my ($self, $action) = @_;
494
495   $self->requirement_spec->update_attributes(project_id => undef)                     if $action eq 'none';
496   $self->requirement_spec->update_attributes(project_id => $::form->{new_project_id}) if $action eq 'existing';
497
498   return $self->invalidate_version
499     ->replaceWith('#basic_settings', $self->render('requirement_spec/_show_basic_settings', { output => 0 }))
500     ->remove('#project_link_form')
501     ->flash('info', t8('The project link has been updated.'))
502     ->render($self);
503 }
504
505 sub update_project_link_new {
506   my ($self) = @_;
507
508   return $self->js
509     ->replaceWith('#project_link_form', $self->render('requirement_spec/_new_project_form', { output => 0 }))
510     ->render($self);
511 }
512
513 sub update_project_link_create {
514   my ($self)  = @_;
515   my $params  = delete($::form->{project}) || {};
516   my $project = SL::DB::Project->new(
517     %{ $params },
518     valid  => 1,
519     active => 1,
520   );
521
522   my @errors = $project->validate;
523
524   return $self->js->error(@errors)->render($self) if @errors;
525
526   my $db = $self->requirement_spec->db;
527   if (!$db->do_transaction(sub {
528     $project->save;
529     $self->requirement_spec->update_attributes(project_id => $project->id);
530
531   })) {
532     $::lxdebug->message(LXDebug::WARN(), "Error: " . $db->error);
533     return $self->js->error(t8('Saving failed. Error message from the database: #1', $db->error))->render($self);
534   }
535
536   return $self->invalidate_version
537     ->replaceWith('#basic_settings', $self->render('requirement_spec/_show_basic_settings', { output => 0 }))
538     ->remove('#project_link_form')
539     ->flash('info', t8('The project has been created.'))
540     ->flash('info', t8('The project link has been updated.'))
541     ->render($self);
542 }
543
544 sub init_models {
545   my ($self) = @_;
546
547   SL::Controller::Helper::GetModels->new(
548     controller   => $self,
549     sorted       => {
550       _default     => {
551         by           => 'customer',
552         dir          => 1,
553       },
554       %sort_columns,
555     },
556     query => [
557       and => [
558         working_copy_id => undef,
559         is_template     => $::form->{is_template} ? 1 : 0,
560       ],
561     ],
562     with_objects => [ 'customer', 'type', 'status', 'project' ],
563   );
564 }
565
566 1;