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