Refactoring
[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 SL::ClientJS;
9 use SL::Controller::Helper::GetModels;
10 use SL::Controller::Helper::Paginated;
11 use SL::Controller::Helper::Sorted;
12 use SL::Controller::Helper::ParseFilter;
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::RequirementSpecComplexity;
18 use SL::DB::RequirementSpecRisk;
19 use SL::DB::RequirementSpecStatus;
20 use SL::DB::RequirementSpecType;
21 use SL::DB::RequirementSpec;
22 use SL::Helper::Flash;
23 use SL::Locale::String;
24 use SL::Template::LaTeX;
25
26 use Rose::Object::MakeMethods::Generic
27 (
28   scalar                  => [ qw(requirement_spec_item customers types statuses db_args flat_filter visible_item visible_section) ],
29   'scalar --get_set_init' => [ qw(requirement_spec complexities risks projects copy_source js current_text_block_output_position) ],
30 );
31
32 __PACKAGE__->run_before('setup');
33 __PACKAGE__->run_before('load_select_options',  only => [ qw(new ajax_edit create update list) ]);
34
35
36 __PACKAGE__->get_models_url_params('flat_filter');
37 __PACKAGE__->make_paginated(
38   MODEL         => 'RequirementSpec',
39   PAGINATE_ARGS => 'db_args',
40   ONLY          => [ qw(list) ],
41 );
42
43 __PACKAGE__->make_sorted(
44   MODEL         => 'RequirementSpec',
45   ONLY          => [ qw(list) ],
46
47   DEFAULT_BY    => 'customer',
48   DEFAULT_DIR   => 1,
49
50   customer      => t8('Customer'),
51   title         => t8('Title'),
52   type          => t8('Requirement Spec Type'),
53   status        => t8('Requirement Spec Status'),
54   projectnumber => t8('Project Number'),
55   version       => t8('Version'),
56   mtime         => t8('Last modification'),
57 );
58
59 #
60 # actions
61 #
62
63
64 sub action_list {
65   my ($self) = @_;
66
67   $self->setup_db_args_from_filter;
68   $self->flat_filter({ map { $_->{key} => $_->{value} } $::form->flatten_variables('filter') });
69
70   $self->prepare_report;
71
72   my $requirement_specs = $self->get_models(%{ $self->db_args });
73
74   $self->report_generator_list_objects(report => $self->{report}, objects => $requirement_specs);
75 }
76
77 sub action_new {
78   my ($self) = @_;
79
80   $self->requirement_spec(SL::DB::RequirementSpec->new(is_template => $::form->{is_template}));
81
82   if ($self->copy_source) {
83     $self->requirement_spec->$_($self->copy_source->$_) for qw(type_id status_id customer_id title hourly_rate)
84   }
85
86   $self->render('requirement_spec/new', title => $self->requirement_spec->is_template ? t8('Create a new requirement spec template') : t8('Create a new requirement spec'));
87 }
88
89 sub action_ajax_edit {
90   my ($self) = @_;
91
92   $self->render('requirement_spec/_form', { layout => 0 }, submit_as => 'ajax');
93 }
94
95 sub action_ajax_show_time_and_cost_estimate {
96   my ($self) = @_;
97
98   $self->render('requirement_spec/_show_time_and_cost_estimate', { layout => 0 });
99 }
100
101 sub action_ajax_cancel_time_and_cost_estimate {
102   my ($self) = @_;
103
104   my $html   = $self->render('requirement_spec/_show_time_and_cost_estimate', { output => 0 });
105
106   $self->js
107    ->replaceWith('#time_cost_estimate', $html)
108    ->render($self);
109 }
110
111 sub action_ajax_edit_time_and_cost_estimate {
112   my ($self) = @_;
113
114   my $html   = $self->render('requirement_spec/_edit_time_and_cost_estimate', { output => 0 });
115
116   $self->js
117    ->replaceWith('#time_cost_estimate', $html)
118    ->render($self);
119 }
120
121 sub action_ajax_save_time_and_cost_estimate {
122   my ($self) = @_;
123
124   $self->requirement_spec->db->do_transaction(sub {
125     # Make Emacs happy
126     1;
127     foreach my $attributes (@{ $::form->{requirement_spec_items} || [] }) {
128       SL::DB::RequirementSpecItem
129         ->new(id => delete $attributes->{id})
130         ->load
131         ->update_attributes(%{ $attributes });
132     }
133
134     1;
135   });
136
137   my $html = $self->render('requirement_spec/_show_time_and_cost_estimate', { output => 0 });
138   $self->js->replaceWith('#time_cost_estimate', $html);
139
140   if ($self->visible_section) {
141     $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $self->visible_section);
142     $self->js->html('#column-content', $html);
143   }
144
145   $self->js->render($self);
146 }
147
148 sub action_show {
149   my ($self) = @_;
150
151   my $title  = $self->requirement_spec->is_template ? t8('Show requirement spec template') : t8('Show requirement spec');
152   my $item   = $::form->{requirement_spec_item_id} ? SL::DB::RequirementSpecItem->new(id => $::form->{requirement_spec_item_id})->load : @{ $self->requirement_spec->sections }[0];
153   $self->requirement_spec_item($item);
154
155   $self->render('requirement_spec/show', title => $title);
156 }
157
158 sub action_create {
159   my ($self) = @_;
160
161   $self->requirement_spec(SL::DB::RequirementSpec->new);
162   $self->create_or_update;
163 }
164
165 sub action_update {
166   my ($self) = @_;
167   $self->create_or_update;
168 }
169
170 sub action_destroy {
171   my ($self) = @_;
172
173   if (eval { $self->requirement_spec->delete; 1; }) {
174     flash_later('info',  t8('The requirement spec has been deleted.'));
175   } else {
176     flash_later('error', t8('The requirement spec is in use and cannot be deleted.'));
177   }
178
179   $self->redirect_to(action => 'list');
180 }
181
182 sub action_revert_to {
183   my ($self, %params) = @_;
184
185   return $self->js->error(t8('Cannot revert a versioned copy.'))->render($self) if $self->requirement_spec->working_copy_id;
186
187   my $versioned_copy = SL::DB::RequirementSpec->new(id => $::form->{versioned_copy_id})->load;
188
189   $self->requirement_spec->copy_from(
190     $versioned_copy,
191     version_id => $versioned_copy->version_id,
192   );
193
194   flash_later('info', t8('The requirement spec has been reverted to version #1.', $self->requirement_spec->version->version_number));
195   $self->js->redirect_to($self->url_for(action => 'show', id => $self->requirement_spec->id))->render($self);
196 }
197
198 sub action_create_pdf {
199   my ($self, %params) = @_;
200
201   my %result = SL::Template::LaTeX->parse_and_create_pdf('requirement_spec.tex', SELF => $self, rspec => $self->requirement_spec);
202
203   $::form->error(t8('Conversion to PDF failed: #1', $result{error})) if $result{error};
204
205   my $attachment_name  =  $self->requirement_spec->type->description . ' ' . ($self->requirement_spec->working_copy_id || $self->requirement_spec->id);
206   $attachment_name    .=  ' (v' . $self->requirement_spec->version->version_number . ')' if $self->requirement_spec->version;
207   $attachment_name    .=  '.pdf';
208   $attachment_name     =~ s/[^\wäöüÄÖÜß \-\+\(\)\[\]\{\}\.,]+/_/g;
209
210   $self->send_file($result{file_name}, type => 'application/pdf', name => $attachment_name);
211   unlink $result{file_name};
212 }
213
214 sub action_select_template_to_paste {
215   my ($self) = @_;
216
217   my @templates = grep { @{ $_->sections } || @{ $_->text_blocks } } @{ SL::DB::Manager::RequirementSpec->get_all(where => [ is_template => 1 ], sort_by => 'lower(title)') };
218   $self->render('requirement_spec/select_template_to_paste', { layout => 0 }, TEMPLATES => \@templates);
219 }
220
221 sub action_paste_template {
222   my ($self, %params) = @_;
223
224   my $template = SL::DB::RequirementSpec->new(id => $::form->{template_id})->load;
225   my %result   = $self->requirement_spec->paste_template($template);
226
227   return $self->js->error($self->requirement_spec->error)->render($self) if !%result;
228
229   $self->render_pasted_text_block($_) for sort { $a->position <=> $b->position } @{ $result{text_blocks} };
230   $self->render_pasted_section($_)    for sort { $a->position <=> $b->position } @{ $result{sections}    };
231
232   if (@{ $result{sections} } && (($::form->{current_content_type} || 'sections') eq 'sections') && !$::form->{current_content_id}) {
233     $self->render_first_pasted_section_as_list($result{sections}->[0]);
234   }
235
236   $self->invalidate_version->render($self);
237 }
238
239 #
240 # filters
241 #
242
243 sub setup {
244   my ($self) = @_;
245
246   $::auth->assert('sales_quotation_edit');
247   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec);
248   $::request->{layout}->use_javascript("${_}.js") for qw(jquery.jstree jquery/jquery.contextMenu client_js requirement_spec);
249   $self->init_visible_section;
250
251   return 1;
252 }
253
254 sub init_complexities {
255   my ($self) = @_;
256   return SL::DB::Manager::RequirementSpecComplexity->get_all_sorted;
257 }
258
259 sub init_risks {
260   my ($self) = @_;
261   return SL::DB::Manager::RequirementSpecRisk->get_all_sorted;
262 }
263
264 sub init_projects {
265   my ($self) = @_;
266   $self->projects(SL::DB::Manager::Project->get_all_sorted);
267 }
268
269 sub init_requirement_spec {
270   my ($self) = @_;
271   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{id})->load || die "No such requirement spec") if $::form->{id};
272 }
273
274 sub init_copy_source {
275   my ($self) = @_;
276   $self->copy_source(SL::DB::RequirementSpec->new(id => $::form->{copy_source_id})->load) if $::form->{copy_source_id};
277 }
278
279 sub init_js {
280   my ($self) = @_;
281   $self->js(SL::ClientJS->new);
282 }
283
284 sub init_current_text_block_output_position {
285   my ($self) = @_;
286   $self->current_text_block_output_position($::form->{current_content_type} !~ m/^(?:text-blocks|tb)-(front|back)/ ? -1 : $1 eq 'front' ? 0 : 1);
287 }
288
289 sub load_select_options {
290   my ($self) = @_;
291
292   my @filter = ('!obsolete' => 1);
293   @filter    = ( or => [ @filter, id => $self->requirement_spec->customer_id ] ) if $self->requirement_spec && $self->requirement_spec->customer_id;
294
295   $self->customers(SL::DB::Manager::Customer->get_all_sorted(where => \@filter));
296   $self->statuses( SL::DB::Manager::RequirementSpecStatus->get_all_sorted);
297   $self->types(    SL::DB::Manager::RequirementSpecType->get_all_sorted);
298 }
299
300 #
301 # helpers
302 #
303
304 sub create_or_update {
305   my $self   = shift;
306   my $is_new = !$self->requirement_spec->id;
307   my $params = delete($::form->{requirement_spec}) || { };
308
309   $self->requirement_spec->assign_attributes(%{ $params });
310
311   my $title  = $is_new && $self->requirement_spec->is_template ? t8('Create a new requirement spec template')
312              : $is_new                                         ? t8('Create a new requirement spec')
313              :            $self->requirement_spec->is_template ? t8('Edit requirement spec template')
314              :                                                   t8('Edit requirement spec');
315
316   my @errors = $self->requirement_spec->validate;
317
318   if (@errors) {
319     return $self->js->error(@errors)->render($self) if $::request->is_ajax;
320
321     flash('error', @errors);
322     $self->render('requirement_spec/new', title => $title);
323     return;
324   }
325
326   my $db = $self->requirement_spec->db;
327   if (!$db->do_transaction(sub {
328     if ($self->copy_source) {
329       $self->requirement_spec($self->copy_source->create_copy(%{ $params }));
330     } else {
331       $self->requirement_spec->save;
332     }
333   })) {
334     $::lxdebug->message(LXDebug::WARN(), "Error: " . $db->error);
335     @errors = ($::locale->text('Saving failed. Error message from the database: #1'), $db->error);
336     return $self->js->error(@errors)->render($self) if $::request->is_ajax;
337
338     $self->requirement_spec->id(undef) if $is_new;
339     flash('error', @errors);
340     return $self->render('requirement_spec/new', title => $title);
341   }
342
343   my $info = $self->requirement_spec->is_template ? t8('The requirement spec template has been saved.') : t8('The requirement spec has been saved.');
344
345   if ($::request->is_ajax) {
346     my $html = $self->render('requirement_spec/_header', { output => 0 });
347     return $self->invalidate_version
348       ->replaceWith('#requirement-spec-header', $html)
349       ->flash('info', $info)
350       ->render($self);
351   }
352
353   flash_later('info', $info);
354   $self->redirect_to(action => 'show', id => $self->requirement_spec->id);
355 }
356
357 sub setup_db_args_from_filter {
358   my ($self) = @_;
359
360   $self->{filter} = {};
361   my %args = parse_filter(
362     $::form->{filter},
363     with_objects => [ 'customer', 'type', 'status', 'project' ],
364     launder_to   => $self->{filter},
365   );
366
367   $args{where} = [
368     and => [
369       @{ $args{where} || [] },
370       working_copy_id => undef,
371       is_template     => $::form->{is_template} ? 1 : 0,
372     ]];
373
374   $self->db_args(\%args);
375 }
376
377 sub prepare_report {
378   my ($self)      = @_;
379
380   my $callback    = $self->get_callback;
381
382   my $is_template = $::form->{is_template};
383   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
384   $self->{report} = $report;
385
386   my @columns     = $is_template ? qw(title mtime) : qw(title customer status type projectnumber mtime version);
387   my @sortable    = $is_template ? qw(title mtime) : qw(title customer status type projectnumber mtime);
388
389   my %column_defs = (
390     title         => { obj_link => sub { $self->url_for(action => 'show', id => $_[0]->id, callback => $callback) } },
391     mtime         => { sub      => sub { ($_[0]->mtime || $_[0]->itime)->to_kivitendo(precision => 'minute') } },
392   );
393
394   if (!$is_template) {
395     %column_defs = (
396       %column_defs,
397       customer      => { raw_data => sub { $self->presenter->customer($_[0]->customer, display => 'table-cell', callback => $callback) },
398                          sub      => sub { $_[0]->customer->name } },
399       projectnumber => { raw_data => sub { $self->presenter->project($_[0]->project, display => 'table-cell', callback => $callback) },
400                          sub      => sub { $_[0]->project_id ? $_[0]->project->projectnumber : '' } },
401       status        => { sub      => sub { $_[0]->status->description } },
402       type          => { sub      => sub { $_[0]->type->description } },
403       version       => { sub      => sub { $_[0]->version_id ? $_[0]->version->version_number : t8('Working copy without version') } },
404     );
405   }
406
407   map { $column_defs{$_}->{text} ||= $::locale->text( $self->get_sort_spec->{$_}->{title} ) } keys %column_defs;
408
409   $report->set_options(
410     std_column_visibility => 1,
411     controller_class      => 'RequirementSpec',
412     output_format         => 'HTML',
413     raw_top_info_text     => $self->render('requirement_spec/report_top',    { output => 0 }, is_template => $is_template),
414     raw_bottom_info_text  => $self->render('requirement_spec/report_bottom', { output => 0 }),
415     title                 => $is_template ? t8('Requirement Spec Templates') : t8('Requirement Specs'),
416     allow_pdf_export      => 1,
417     allow_csv_export      => 1,
418   );
419   $report->set_columns(%column_defs);
420   $report->set_column_order(@columns);
421   $report->set_export_options(qw(list filter));
422   $report->set_options_from_form;
423   $self->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
424
425   $self->disable_pagination if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
426 }
427
428 sub invalidate_version {
429   my ($self) = @_;
430
431   my $rspec  = SL::DB::RequirementSpec->new(id => $self->requirement_spec->id)->load;
432   return $self->js if $rspec->is_template;
433
434   $rspec->invalidate_version;
435
436   my $html = $self->render('requirement_spec/_version', { output => 0 }, requirement_spec => $rspec);
437   return $self->js->html('#requirement_spec_version', $html);
438 }
439
440 sub render_pasted_text_block {
441   my ($self, $text_block, %params) = @_;
442
443   if ($self->current_text_block_output_position == $text_block->output_position) {
444     my $html = $self->render('requirement_spec_text_block/_text_block', { output => 0 }, text_block => $text_block);
445     $self->js
446       ->appendTo($html, '#text-block-list')
447       ->hide('#text-block-list-empty');
448   }
449
450   my $node       = $self->presenter->requirement_spec_text_block_jstree_data($text_block);
451   my $front_back = $text_block->output_position == 0 ? 'front' : 'back';
452   $self->js
453     ->jstree->create_node('#tree', "#tb-${front_back}", 'last', $node)
454     ->jstree->open_node(  '#tree', "#tb-${front_back}");
455 }
456
457 sub render_pasted_section {
458   my ($self, $item, $parent_id) = @_;
459
460   my $node = $self->presenter->requirement_spec_item_jstree_data($item);
461   $self->js
462     ->jstree->create_node('#tree', $parent_id ? "#fb-${parent_id}" : '#sections', 'last', $node)
463     ->jstree->open_node(  '#tree', $parent_id ? "#fb-${parent_id}" : '#sections');
464
465   $self->render_pasted_section($_, $item->id) for @{ $item->children_sorted };
466 }
467
468 sub render_first_pasted_section_as_list {
469   my ($self, $section, %params) = @_;
470
471   my $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $section);
472   $self->js
473     ->html('#column-content', $html)
474     ->val( '#current_content_type', $section->item_type)
475     ->val( '#current_content_id',   $section->id)
476     ->jstree->select_node('#tree', '#fb-' . $section->id);
477 }
478
479 1;