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