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