Kosmetik: Einrückung/Anordnung
[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::Common ();
11 use SL::Controller::Helper::GetModels;
12 use SL::Controller::Helper::ReportGenerator;
13 use SL::Controller::Helper::RequirementSpec;
14 use SL::DB::Customer;
15 use SL::DB::Project;
16 use SL::DB::ProjectStatus;
17 use SL::DB::ProjectType;
18 use SL::DB::RequirementSpecComplexity;
19 use SL::DB::RequirementSpecRisk;
20 use SL::DB::RequirementSpecStatus;
21 use SL::DB::RequirementSpecType;
22 use SL::DB::RequirementSpec;
23 use SL::Helper::CreatePDF qw();
24 use SL::Helper::Flash;
25 use SL::Locale::String;
26 use SL::System::Process;
27 use SL::Template::LaTeX;
28
29 use Rose::Object::MakeMethods::Generic
30 (
31   scalar                  => [ qw(requirement_spec_item visible_item visible_section) ],
32   '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
33                                   current_text_block_output_position models time_based_units html_template cvar_configs includeable_cvar_configs include_cvars) ],
34 );
35
36 __PACKAGE__->run_before('setup');
37 __PACKAGE__->run_before('set_default_filter_args', only => [ qw(list) ]);
38
39 my %sort_columns = (
40   customer      => t8('Customer'),
41   title         => t8('Title'),
42   type          => t8('Requirement Spec Type'),
43   status        => t8('Requirement Spec Status'),
44   projectnumber => t8('Project Number'),
45   version       => t8('Version'),
46   mtime         => t8('Last modification'),
47 );
48
49 #
50 # actions
51 #
52
53
54 sub action_list {
55   my ($self) = @_;
56
57   $self->_setup_search_action_bar;
58   $self->prepare_report;
59   $self->report_generator_list_objects(report => $self->{report}, objects => $self->models->get);
60 }
61
62 sub action_new {
63   my ($self) = @_;
64
65   $self->requirement_spec(SL::DB::RequirementSpec->new(is_template => $::form->{is_template}));
66
67   if ($self->copy_source) {
68     $self->requirement_spec->$_($self->copy_source->$_) for qw(type_id status_id customer_id title hourly_rate is_template)
69   }
70
71   $self->_setup_form_action_bar;
72
73   $self->render('requirement_spec/new', title => $self->requirement_spec->is_template ? t8('Create a new requirement spec template') : t8('Create a new requirement spec'));
74 }
75
76 sub action_ajax_show_basic_settings {
77   my ($self) = @_;
78
79   $self->render('requirement_spec/_show_basic_settings', { layout => 0 });
80 }
81
82 sub action_ajax_edit {
83   my ($self) = @_;
84
85   my $html   = $self->render('requirement_spec/_form', { output => 0 }, submit_as => 'ajax');
86
87   $self->js
88     ->hide('#basic_settings')
89     ->after('#basic_settings', $html)
90     ->reinit_widgets
91     ->render;
92 }
93
94 sub action_ajax_edit_project_link {
95   my ($self) = @_;
96
97   my $html   = $self->render('requirement_spec/_project_link_form', { output => 0 }, submit_as => 'ajax');
98
99   $self->js
100     ->hide('#basic_settings')
101     ->after('#basic_settings', $html)
102     ->render;
103 }
104
105 sub action_ajax_show_time_and_cost_estimate {
106   my ($self) = @_;
107
108   $self->render('requirement_spec/_show_time_and_cost_estimate', { layout => 0 });
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   my $first  = ($self->requirement_spec->sections_sorted || [])->[0];
116   $first     = ($first->children_sorted || [])->[0] if $first;
117
118   $self->js
119    ->hide('#time_cost_estimate')
120    ->after('#time_cost_estimate', $html)
121    ->on('#time_cost_estimate INPUT[type=text]', 'keydown', 'kivi.requirement_spec.time_cost_estimate_input_key_down')
122    ->action_if($first && $first->id, 'focus', '#time_and_cost_estimate_form_complexity_id_' . $first->id)
123    ->render;
124 }
125
126 sub action_ajax_save_time_and_cost_estimate {
127   my ($self) = @_;
128
129   $self->requirement_spec->db->with_transaction(sub {
130     # Make Emacs happy
131     1;
132     foreach my $attributes (@{ $::form->{requirement_spec_items} || [] }) {
133       SL::DB::RequirementSpecItem
134         ->new(id => delete $attributes->{id})
135         ->load
136         ->update_attributes(%{ $attributes });
137     }
138
139     1;
140   });
141
142   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $self->requirement_spec->id)->load);
143
144   my $html = $self->render('requirement_spec/_show_time_and_cost_estimate', { output => 0 }, initially_hidden => !!$::form->{keep_open});
145   $self->js->replaceWith('#time_cost_estimate', $html);
146
147   return $self->js->render if $::form->{keep_open};
148
149   $self->js->remove('#time_cost_estimate_form_container');
150
151   if ($self->visible_section) {
152     $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $self->visible_section);
153     $self->js->html('#column-content', $html);
154   }
155
156   $self->js->render;
157 }
158
159 sub action_show {
160   my ($self) = @_;
161
162   my $title  = $self->requirement_spec->is_template ? t8('Show requirement spec template') : t8('Show requirement spec');
163   my $item   = $::form->{requirement_spec_item_id} ? SL::DB::RequirementSpecItem->new(id => $::form->{requirement_spec_item_id})->load : @{ $self->requirement_spec->sections_sorted }[0];
164   $self->requirement_spec_item($item);
165
166   $self->render('requirement_spec/show', title => $title);
167 }
168
169 sub action_create {
170   my ($self) = @_;
171
172   $self->requirement_spec(SL::DB::RequirementSpec->new);
173   $self->create_or_update;
174 }
175
176 sub action_update {
177   my ($self) = @_;
178   $self->create_or_update;
179 }
180
181 sub action_update_project_link {
182   my $self   = shift;
183   my $action = delete($::form->{project_link_action}) || 'keep';
184
185   return $self->update_project_link_none_keep_existing($action) if $action =~ m{none|keep|existing};
186   return $self->update_project_link_new($action)                if $action eq 'new';
187   return $self->update_project_link_create($action)             if $action eq 'create';
188
189   die "Unknown project link action '$action'";
190 }
191
192 sub action_destroy {
193   my ($self) = @_;
194
195   if (eval { $self->requirement_spec->delete; 1; }) {
196     flash_later('info',  t8('The requirement spec has been deleted.'));
197   } else {
198     flash_later('error', t8('The requirement spec is in use and cannot be deleted.'));
199   }
200
201   $self->redirect_to(action => 'list');
202 }
203
204 sub action_revert_to {
205   my ($self, %params) = @_;
206
207   return $self->js->error(t8('Cannot revert a versioned copy.'))->render if $self->requirement_spec->working_copy_id;
208
209   my $versioned_copy = SL::DB::RequirementSpec->new(id => $::form->{versioned_copy_id})->load;
210
211   $self->requirement_spec->copy_from($versioned_copy);
212   my $version = $versioned_copy->versions->[0];
213   $version->update_attributes(working_copy_id => $self->requirement_spec->id);
214
215   flash_later('info', t8('The requirement spec has been reverted to version #1.', $versioned_copy->version->version_number));
216   $self->js->redirect_to($self->url_for(action => 'show', id => $self->requirement_spec->id))->render;
217 }
218
219 sub action_create_pdf {
220   my ($self, %params) = @_;
221
222   my $keep_temp_files = $::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files};
223   my $temp_dir        = File::Temp->newdir(
224     "kivitendo-print-XXXXXX",
225     DIR     => SL::System::Process::exe_dir() . "/" . $::lx_office_conf{paths}->{userspath},
226     CLEANUP => !$keep_temp_files,
227   );
228
229   my $base_name       = $self->requirement_spec->type->template_file_name || 'requirement_spec';
230   my @pictures        = $self->prepare_pictures_for_printing($temp_dir->dirname);
231   my %result          = SL::Template::LaTeX->parse_and_create_pdf("${base_name}.tex", SELF => $self, rspec => $self->requirement_spec, userspath => $temp_dir->dirname);
232
233   unlink @pictures unless ($::lx_office_conf{debug} || {})->{keep_temp_files};
234
235   $::form->error(t8('Conversion to PDF failed: #1', $result{error})) if $result{error};
236
237   my $attachment_name  =  $self->requirement_spec->type->description . ' ' . ($self->requirement_spec->working_copy_id || $self->requirement_spec->id);
238   $attachment_name    .=  ' (v' . $self->requirement_spec->version->version_number . ')' if $self->requirement_spec->version;
239   $attachment_name    .=  '.pdf';
240   $attachment_name     =~ s/[^\wäöüÄÖÜß \-\+\(\)\[\]\{\}\.,]+/_/g;
241
242   $self->send_file($result{file_name}, type => 'application/pdf', name => $attachment_name);
243   unlink $result{file_name};
244 }
245
246 sub action_create_html {
247   my ($self, %params) = @_;
248
249   my $base_name       = $self->requirement_spec->type->template_file_name || 'requirement_spec';
250   my @pictures        = $self->prepare_pictures_for_printing;
251   my $content         = SL::Helper::CreatePDF->create_parsed_file(
252     template      => "${base_name}.html",
253     format        => 'html',
254     template_type => 'HTML',
255     variables     => {
256       SELF        => $self,
257       rspec       => $self->requirement_spec,
258     });
259
260   # $content is now a scalar of bytes, but $self->render() expects a
261   # scalar of characters.
262   $content = Encode::decode('utf-8', $content);
263
264   $self->render(\$content, { layout => 0, process => 0 });
265 }
266
267 sub action_select_template_to_paste {
268   my ($self) = @_;
269
270   my @templates = @{ SL::DB::Manager::RequirementSpec->get_all(
271     where   => [ is_template => 1, SL::DB::Manager::RequirementSpec->not_empty_filter ],
272     sort_by => 'lower(requirement_specs.title)',
273   ) };
274   $self->render('requirement_spec/select_template_to_paste', { layout => 0 }, TEMPLATES => \@templates);
275 }
276
277 sub action_paste_template {
278   my ($self, %params) = @_;
279
280   my $template = SL::DB::RequirementSpec->new(id => $::form->{template_id})->load;
281   my %result   = $self->requirement_spec->paste_template($template);
282
283   return $self->js->error($self->requirement_spec->error)->render if !%result;
284
285   $self->render_pasted_text_block($_) for sort { $a->position <=> $b->position } @{ $result{text_blocks} };
286   $self->render_pasted_section($_)    for sort { $a->position <=> $b->position } @{ $result{sections}    };
287
288   if (@{ $result{sections} } && (($::form->{current_content_type} || 'sections') eq 'sections') && !$::form->{current_content_id}) {
289     $self->render_first_pasted_section_as_list($result{sections}->[0]);
290   }
291
292   my $parts_list = $self->render('requirement_spec_part/show', { output => 0 });
293   $self->js
294     ->replaceWith('#additional_parts_list_container', $parts_list)
295     ->show(       '#additional_parts_list_container')
296     ->remove(     '#additional_parts_form_container');
297
298   $self->invalidate_version->render;
299 }
300
301 sub action_renumber_sections {
302   my ($self)  = @_;
303
304   my %numbers = map { ($_ => 1)                                                                         } qw(section function_block);
305   my %formats = map { my $method = "${_}_number_format"; ($_ => $self->requirement_spec->type->$method) } qw(section function_block);
306   my @items   = @{ $self->requirement_spec->sections_sorted };
307
308   $self->requirement_spec->db->with_transaction(sub {
309     while (@items) {
310       my $item = shift @items;
311       my $type = $item->parent_id ? 'function_block' : 'section';
312
313       $item->update_attributes(fb_number => SL::PrefixedNumber->new(number => $formats{$type} || 0)->set_to($numbers{$type}));
314
315       $numbers{$type}++;
316
317       unshift @items, @{ $item->children_sorted };
318     }
319
320     $self->requirement_spec->invalidate_version unless $self->requirement_spec->is_template;
321
322     1;
323   });
324
325   $self->redirect_to(action => 'show', id => $self->requirement_spec->id);
326 }
327
328 #
329 # filters
330 #
331
332 sub setup {
333   my ($self) = @_;
334
335   $::auth->assert('requirement_spec_edit');
336   $::request->{layout}->use_stylesheet("${_}.css") for qw(jquery.contextMenu requirement_spec);
337   $::request->{layout}->use_javascript("${_}.js")  for qw(jquery.jstree jquery/jquery.contextMenu jquery/jquery.hotkeys requirement_spec ckeditor/ckeditor ckeditor/adapters/jquery kivi.Part kivi.CustomerVendor
338                                                           ckeditor/ckeditor ckeditor/adapters/jquery);
339   $self->init_visible_section;
340
341   return 1;
342 }
343
344 sub init_complexities           { SL::DB::Manager::RequirementSpecComplexity->get_all_sorted  }
345 sub init_default_project_status { SL::DB::Manager::ProjectStatus->find_by(name => 'planning') }
346 sub init_default_project_type   { SL::DB::ProjectType->new(id => 1)->load                     }
347 sub init_project_statuses       { SL::DB::Manager::ProjectStatus->get_all_sorted              }
348 sub init_project_types          { SL::DB::Manager::ProjectType->get_all_sorted                }
349 sub init_projects               { SL::DB::Manager::Project->get_all_sorted                    }
350 sub init_risks                  { SL::DB::Manager::RequirementSpecRisk->get_all_sorted        }
351 sub init_statuses               { SL::DB::Manager::RequirementSpecStatus->get_all_sorted      }
352 sub init_time_based_units       { SL::DB::Manager::Unit->time_based_units                     }
353 sub init_types                  { SL::DB::Manager::RequirementSpecType->get_all_sorted        }
354 sub init_cvar_configs           { SL::DB::Manager::CustomVariableConfig->get_all_sorted(where => [ module => 'RequirementSpecs' ]) }
355
356 sub init_customers {
357   my ($self) = @_;
358
359   my @filter = ('!obsolete' => 1);
360   @filter    = ( or => [ @filter, id => $self->requirement_spec->customer_id ] ) if $self->requirement_spec && $self->requirement_spec->customer_id;
361
362   return SL::DB::Manager::Customer->get_all_sorted(where => \@filter);
363 }
364
365 sub init_requirement_spec {
366   my ($self) = @_;
367   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{id})->load || die "No such requirement spec") if $::form->{id};
368 }
369
370 sub init_copy_source {
371   my ($self) = @_;
372   $self->copy_source(SL::DB::RequirementSpec->new(id => $::form->{copy_source_id})->load) if $::form->{copy_source_id};
373 }
374
375 sub init_current_text_block_output_position {
376   my ($self) = @_;
377   $self->current_text_block_output_position($::form->{current_content_type} !~ m/^(?:text-blocks|tb)-(front|back)/ ? -1 : $1 eq 'front' ? 0 : 1);
378 }
379
380 sub init_includeable_cvar_configs {
381   my ($self) = @_;
382   return [ grep { $_->includeable } @{ $self->cvar_configs } ];
383 }
384
385 sub init_include_cvars {
386   my ($self) = @_;
387   return { map { ($_->name => $::form->{"include_cvars_" . $_->name}) }       @{ $self->cvar_configs } } if $::form->{_include_cvars_from_form};
388   return { map { ($_->name => ($_->includeable && $_->included_by_default)) } @{ $self->cvar_configs } };
389 }
390
391 #
392 # helpers
393 #
394
395 sub create_or_update {
396   my $self                 = shift;
397   my $is_new               = !$self->requirement_spec->id;
398   my $previous_customer_id = $self->requirement_spec->customer_id;
399   my $params               = delete($::form->{requirement_spec}) || { };
400   my $cvars                = delete($::form->{cvars})            || { };
401
402   # Forcefully make it clear to Rose which custom_variables exist (or don't), so that the ones added with »add_custom_variables« are visible when calling »custom_variables«.
403   if ($is_new) {
404     $params->{custom_variables} = [];
405   } else {
406     $self->requirement_spec->custom_variables;
407   }
408
409   $self->requirement_spec->assign_attributes(%{ $params });
410
411   foreach my $var (@{ $self->requirement_spec->cvars_by_config }) {
412     my $value = $cvars->{ $var->config->name };
413     $value    = $::form->parse_amount(\%::myconfig, $value) if $var->config->type eq 'number';
414
415     $var->value($value);
416   }
417
418   my $title  = $is_new && $self->requirement_spec->is_template ? t8('Create a new requirement spec template')
419              : $is_new                                         ? t8('Create a new requirement spec')
420              :            $self->requirement_spec->is_template ? t8('Edit requirement spec template')
421              :                                                   t8('Edit requirement spec');
422
423   my @errors = $self->requirement_spec->validate;
424
425   if (@errors) {
426     return $self->js->error(@errors)->render if $::request->is_ajax;
427
428     flash('error', @errors);
429     $self->render('requirement_spec/new', title => $title);
430     return;
431   }
432
433   my $db = $self->requirement_spec->db;
434   if (!$db->with_transaction(sub {
435     if ($self->copy_source) {
436       $self->requirement_spec($self->copy_source->create_copy(%{ $params }));
437     } else {
438       $self->requirement_spec->save(cascade => 1);
439
440       # If the current requirement spec has versions and the
441       # customer's been changed, then the customer of all the versions
442       # has to be changed, too.
443       if (   !$is_new
444           && !$self->requirement_spec->is_template
445           && ($previous_customer_id != $self->requirement_spec->customer_id)) {
446         SL::DB::Manager::RequirementSpec->update_all(
447           set   => { customer_id     => $self->requirement_spec->customer_id },
448           where => [ working_copy_id => $self->requirement_spec->id          ],
449         );
450       }
451     }
452     1;
453   })) {
454     $::lxdebug->message(LXDebug::WARN(), "Error: " . $db->error);
455     @errors = ($::locale->text('Saving failed. Error message from the database: #1', $db->error));
456     return $self->js->error(@errors)->render if $::request->is_ajax;
457
458     $self->requirement_spec->id(undef) if $is_new;
459     flash('error', @errors);
460     return $self->render('requirement_spec/new', title => $title);
461   }
462
463   my $info = $self->requirement_spec->is_template ? t8('The requirement spec template has been saved.') : t8('The requirement spec has been saved.');
464
465   if ($::request->is_ajax) {
466     my $header_html = $self->render('requirement_spec/_header', { output => 0 });
467     my $basics_html = $self->render('requirement_spec/_show_basic_settings', { output => 0 });
468     return $self->invalidate_version
469       ->replaceWith('#requirement-spec-header', $header_html)
470       ->replaceWith('#basic_settings',          $basics_html)
471       ->remove('#basic_settings_form')
472       ->flash('info', $info)
473       ->render;
474   }
475
476   flash_later('info', $info);
477   $self->redirect_to(action => 'show', id => $self->requirement_spec->id);
478 }
479
480 sub prepare_report {
481   my ($self)      = @_;
482
483   my $is_template = $::form->{is_template};
484   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
485
486   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
487   $self->models->finalize; # for filter laundering
488   my $callback    = $self->models->get_callback;
489
490   $self->{report} = $report;
491
492   my @columns     = $is_template ? qw(title mtime) : qw(title customer status type projectnumber mtime version);
493   my @sortable    = $is_template ? qw(title mtime) : qw(title customer status type projectnumber mtime);
494
495   my %column_defs = (
496     title         => { obj_link => sub { $self->url_for(action => 'show', id => $_[0]->id, callback => $callback) } },
497     mtime         => { sub      => sub { ($_[0]->mtime || $_[0]->itime)->to_kivitendo(precision => 'minute') } },
498   );
499
500   if (!$is_template) {
501     %column_defs = (
502       %column_defs,
503       customer      => { raw_data => sub { $_[0]->customer->presenter->customer(display => 'table-cell', callback => $callback) },
504                          sub      => sub { $_[0]->customer->name } },
505       projectnumber => { raw_data => sub { $_[0]->project ? $_[0]->project->presenter->project(display => 'table-cell', callback => $callback) : '' },
506                          sub      => sub { $_[0]->project_id ? $_[0]->project->projectnumber : '' } },
507       status        => { sub      => sub { $_[0]->status->description } },
508       type          => { sub      => sub { $_[0]->type->description } },
509       version       => { sub      => sub { $_[0]->version ? $_[0]->version->version_number : t8('Working copy without version') } },
510     );
511   }
512
513   $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) for keys %column_defs;
514
515   if (!$is_template) {
516     my %cvar_column_defs = map {
517       my $cfg = $_;
518       (('cvar_' . $cfg->name) => {
519         sub     => sub { my $var = $_[0]->cvar_by_name($cfg->name); $var ? $var->value_as_text : '' },
520         text    => $cfg->description,
521         visible => $self->include_cvars->{ $cfg->name } ? 1 : 0,
522       })
523     } @{ $self->includeable_cvar_configs };
524
525     push @columns, map { 'cvar_' . $_->name } @{ $self->includeable_cvar_configs };
526     %column_defs = (%column_defs, %cvar_column_defs);
527   }
528
529   my @cvar_column_form_names = ('_include_cvars_from_form', map { "include_cvars_" . $_->name } @{ $self->includeable_cvar_configs });
530
531   $report->set_options(
532     std_column_visibility => 1,
533     controller_class      => 'RequirementSpec',
534     output_format         => 'HTML',
535     raw_top_info_text     => $self->render('requirement_spec/report_top',    { output => 0 }, is_template => $is_template),
536     raw_bottom_info_text  => $self->render('requirement_spec/report_bottom', { output => 0 }, models => $self->models),
537     title                 => $is_template ? t8('Requirement Spec Templates') : t8('Requirement Specs'),
538     allow_pdf_export      => 1,
539     allow_csv_export      => 1,
540   );
541   $report->set_columns(%column_defs);
542   $report->set_column_order(@columns);
543   $report->set_export_options(qw(list filter), @cvar_column_form_names);
544   $report->set_options_from_form;
545   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
546 }
547
548 sub invalidate_version {
549   my ($self) = @_;
550
551   my $rspec  = SL::DB::RequirementSpec->new(id => $self->requirement_spec->id)->load;
552   return $self->js if $rspec->is_template;
553
554   $rspec->invalidate_version;
555
556   my $html = $self->render('requirement_spec/_version', { output => 0 }, requirement_spec => $rspec);
557   return $self->js->html('#requirement_spec_version', $html);
558 }
559
560 sub render_pasted_text_block {
561   my ($self, $text_block, %params) = @_;
562
563   if ($self->current_text_block_output_position == $text_block->output_position) {
564     my $html = $self->render('requirement_spec_text_block/_text_block', { output => 0 }, text_block => $text_block);
565     $self->js
566       ->appendTo($html, '#text-block-list')
567       ->hide('#text-block-list-empty');
568   }
569
570   my $node       = $text_block->presenter->jstree_data;
571   my $front_back = $text_block->output_position == 0 ? 'front' : 'back';
572   $self->js
573     ->jstree->create_node('#tree', "#tb-${front_back}", 'last', $node)
574     ->jstree->open_node(  '#tree', "#tb-${front_back}");
575 }
576
577 sub set_default_filter_args {
578   my ($self) = @_;
579
580   if (!$::form->{filter} && !$::form->{is_template}) {
581     $::form->{filter} = {
582       status_id => [ map { $_->{id} } grep { $_->name ne 'done' } @{ $self->statuses } ],
583     };
584   }
585
586   return 1;
587 }
588
589 sub render_pasted_section {
590   my ($self, $item, $parent_id) = @_;
591
592   my $node = $item->presenter->jstree_data;
593   $self->js
594     ->jstree->create_node('#tree', $parent_id ? "#fb-${parent_id}" : '#sections', 'last', $node)
595     ->jstree->open_node(  '#tree', $parent_id ? "#fb-${parent_id}" : '#sections');
596
597   $self->render_pasted_section($_, $item->id) for @{ $item->children_sorted };
598 }
599
600 sub render_first_pasted_section_as_list {
601   my ($self, $section, %params) = @_;
602
603   my $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $section);
604   $self->js
605     ->html('#column-content', $html)
606     ->val( '#current_content_type', $section->item_type)
607     ->val( '#current_content_id',   $section->id)
608     ->jstree->select_node('#tree', '#fb-' . $section->id);
609 }
610
611 sub prepare_pictures_for_printing {
612   my ($self, $userspath) = @_;
613
614   my @files;
615   $userspath ||= SL::System::Process::exe_dir() . "/" . $::lx_office_conf{paths}->{userspath};
616   my $target   = "${userspath}/kivitendo-print-requirement-spec-picture-" . Common::unique_id() . '-';
617
618   foreach my $picture (map { @{ $_->pictures } } @{ $self->requirement_spec->text_blocks }) {
619     my $output_file_name        = $target . $picture->id . '.' . $picture->get_default_file_name_extension;
620     $picture->{print_file_name} = File::Spec->abs2rel($output_file_name, $userspath);
621     my $out                     = IO::File->new($output_file_name, 'w') || die("Could not create file " . $output_file_name);
622     $out->binmode;
623     $out->print($picture->picture_content);
624     $out->close;
625
626     push @files, $output_file_name;
627   }
628
629   return @files;
630 }
631
632 sub update_project_link_none_keep_existing {
633   my ($self, $action) = @_;
634
635   $self->requirement_spec->update_attributes(project_id => undef)                     if $action eq 'none';
636   $self->requirement_spec->update_attributes(project_id => $::form->{new_project_id}) if $action eq 'existing';
637
638   return $self->invalidate_version
639     ->replaceWith('#basic_settings', $self->render('requirement_spec/_show_basic_settings', { output => 0 }))
640     ->remove('#project_link_form')
641     ->flash('info', t8('The project link has been updated.'))
642     ->render;
643 }
644
645 sub update_project_link_new {
646   my ($self) = @_;
647
648   return $self->js
649     ->replaceWith('#project_link_form', $self->render('requirement_spec/_new_project_form', { output => 0 }))
650     ->render;
651 }
652
653 sub update_project_link_create {
654   my ($self)  = @_;
655   my $params  = delete($::form->{project}) || {};
656   my $project = SL::DB::Project->new(
657     %{ $params },
658     valid  => 1,
659     active => 1,
660   );
661
662   my @errors = $project->validate;
663
664   return $self->js->error(@errors)->render if @errors;
665
666   my $db = $self->requirement_spec->db;
667   if (!$db->with_transaction(sub {
668     $project->save;
669     $self->requirement_spec->update_attributes(project_id => $project->id);
670
671   })) {
672     $::lxdebug->message(LXDebug::WARN(), "Error: " . $db->error);
673     return $self->js->error(t8('Saving failed. Error message from the database: #1', $db->error))->render;
674   }
675
676   return $self->invalidate_version
677     ->replaceWith('#basic_settings', $self->render('requirement_spec/_show_basic_settings', { output => 0 }))
678     ->remove('#project_link_form')
679     ->flash('info', t8('The project has been created.'))
680     ->flash('info', t8('The project link has been updated.'))
681     ->render;
682 }
683
684 sub init_models {
685   my ($self) = @_;
686
687   SL::Controller::Helper::GetModels->new(
688     controller   => $self,
689     sorted       => {
690       _default     => {
691         by           => 'customer',
692         dir          => 1,
693       },
694       %sort_columns,
695     },
696     query => [
697       and => [
698         working_copy_id => undef,
699         is_template     => $::form->{is_template} ? 1 : 0,
700       ],
701     ],
702     with_objects => [ 'customer', 'type', 'status', 'project' ],
703   );
704 }
705
706 sub init_html_template {
707   my ($self)    = @_;
708   my $base_name = $self->requirement_spec->type->template_file_name || 'requirement_spec';
709   my $template  = SL::Helper::CreatePDF->find_template(name => $base_name, extension => 'html');
710   return !!$template;
711 }
712
713 sub _setup_form_action_bar {
714   my ($self) = @_;
715
716   for my $bar ($::request->layout->get('actionbar')) {
717     $bar->add(
718       action => [
719         t8('Save'),
720         submit    => [ '#basic_settings_form', { action => 'RequirementSpec/' . ($self->requirement_spec->id ? 'update' : 'create') } ],
721         accesskey => 'enter',
722       ],
723
724       link => [
725         t8('Abort'),
726         link => $self->url_for(action => 'list', is_template => $self->requirement_spec->is_template),
727       ],
728     );
729   }
730 }
731
732 sub _setup_search_action_bar {
733   my ($self, %params) = @_;
734
735   for my $bar ($::request->layout->get('actionbar')) {
736     $bar->add(
737       action => [
738         t8('Update'),
739         submit    => [ '#search_form', { action => 'RequirementSpec/list' } ],
740         accesskey => 'enter',
741       ],
742       link => [
743         t8('Add'),
744         link => $self->url_for(action => 'new', is_template => $::form->{is_template}),
745       ],
746     );
747   }
748 }
749
750 1;