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