c2f470aba2b25f0e15ecefb45e2985ffc8dfc681
[kivitendo-erp.git] / SL / Controller / RequirementSpecItem.pm
1 package SL::Controller::RequirementSpecItem;
2
3 use strict;
4
5 use parent qw(SL::Controller::Base);
6
7 use Carp;
8 use List::MoreUtils qw(apply);
9 use List::Util qw(first);
10 use Time::HiRes ();
11
12 use SL::DB::RequirementSpec;
13 use SL::DB::RequirementSpecComplexity;
14 use SL::DB::RequirementSpecItem;
15 use SL::DB::RequirementSpecRisk;
16 use SL::Helper::Flash;
17 use SL::JSON;
18 use SL::Locale::String;
19
20 use Rose::Object::MakeMethods::Generic
21 (
22   scalar                  => [ qw(item visible_item visible_section) ],
23   'scalar --get_set_init' => [ qw(complexities risks) ],
24 );
25
26 __PACKAGE__->run_before('load_requirement_spec_item', only => [ qw(dragged_and_dropped ajax_update ajax_edit ajax_delete) ]);
27 __PACKAGE__->run_before('init_visible_section');
28
29 #
30 # actions
31 #
32
33 sub action_ajax_list {
34   my ($self, $js) = @_;
35
36   my $js = SL::ClientJS->new;
37
38   if (!$::form->{clicked_id}) {
39     # Clicked on "sections" in the tree. Do nothing.
40     return $self->render($js);
41   }
42
43   $self->item(SL::DB::RequirementSpecItem->new(id => $::form->{clicked_id})->load->get_section);
44
45   $self->render_list($js, $self->item) if !$self->visible_section || ($self->visible_section->id != $self->item->id);
46
47   $self->render($js);
48 }
49
50 sub action_dragged_and_dropped {
51   my ($self)             = @_;
52
53   my $position           = $::form->{position} =~ m/^ (?: before | after | last ) $/x ? $::form->{position}                                             : die "Unknown 'position' parameter";
54   my $dropped_item       = $::form->{dropped_id}                                  ? SL::DB::RequirementSpecItem->new(id => $::form->{dropped_id})->load : undef;
55
56   my $visible_section_id = $self->visible_section ? $self->visible_section->id : undef;
57   my $old_parent_id      = $self->item->parent_id;
58   my $old_type           = $self->item->get_type;
59
60   $self->item->db->do_transaction(sub {
61     $self->item->remove_from_list;
62     $self->item->parent_id($position =~ m/before|after/ ? $dropped_item->parent_id : $dropped_item->id);
63     $self->item->add_to_list(position => $position, reference => $::form->{dropped_id} || undef);
64   });
65
66   my $js = SL::ClientJS->new;
67
68   $self->item(SL::DB::RequirementSpecItem->new(id => $self->item->id)->load);
69   my $new_section = $self->item->get_section;
70   my $new_type    = $self->item->get_type;
71
72   return $self->render($js) if !$visible_section_id || ($new_type eq 'section');
73
74   my $old_parent  = SL::DB::RequirementSpecItem->new(id => $old_parent_id)->load;
75   my $old_section = $old_parent->get_section;
76
77   # $::lxdebug->message(0, "old sec ID " . $old_section->id . " new " . $new_section->id . " visible $visible_section_id PARENT: old " . $old_parent->id . " new " . $self->item->parent_id . '/' . $self->item->parent->id);
78
79   if ($visible_section_id == $old_section->id) {
80     my $id_prefix = $old_type eq 'sub-function-block' ? 'sub-' : '';
81     $js->remove('#' . $id_prefix . 'function-block-' . $self->item->id);
82
83     if ($old_type eq 'sub-function-block') {
84       $self->replace_bottom($js, $old_parent) ;
85       $js->hide('#sub-function-block-container-' . $old_parent->id) if 0 == scalar(@{ $old_parent->children });
86
87     } elsif (0 == scalar(@{ $old_section->children })) {
88       $js->show('#section-list-empty');
89     }
90   }
91
92   if ($visible_section_id == $new_section->id) {
93     $js->hide('#section-list-empty');
94
95     my $id_prefix = $new_type eq 'sub-function-block' ? 'sub-' : '';
96     my $template  = 'requirement_spec_item/_' . (apply { s/-/_/g; $_ } $new_type);
97     my $html      = "" . $self->render($template, { output => 0 }, requirement_spec_item => $self->item);
98     my $next_item = $self->item->get_next_in_list;
99
100     if ($next_item) {
101       $js->insertBefore($html, '#' . $id_prefix . 'function-block-' . $next_item->id);
102     } else {
103       my $parent_is_section = $self->item->parent->get_type eq 'section';
104       $js->appendTo($html, $parent_is_section ? '#section-list' : '#sub-function-block-container-' . $self->item->parent_id);
105       $js->show('#sub-function-block-container-' . $self->item->parent_id) if !$parent_is_section;
106     }
107
108     $self->replace_bottom($js, $self->item->parent) if $new_type eq 'sub-function-block';
109   }
110
111   # $::lxdebug->dump(0, "js", $js->to_array);
112
113   $self->render($js);
114 }
115
116 sub action_ajax_add_section {
117   my ($self, %params) = @_;
118
119   die "Missing parameter 'requirement_spec_id'" if !$::form->{requirement_spec_id};
120
121   $self->item(SL::DB::RequirementSpecItem->new(requirement_spec_id => $::form->{requirement_spec_id}));
122
123   my $insert_after = $::form->{id} ? SL::DB::RequirementSpecItem->new(id => $::form->{id})->load->get_section->id : undef;
124   my $html         = $self->render('requirement_spec_item/_section_form', { output => 0 }, id_base => 'new_section', insert_after => $insert_after);
125
126   SL::ClientJS->new
127     ->remove('#new_section_form')
128     ->hide('#column-content > *')
129     ->appendTo($html, '#column-content')
130     ->focus('#new_section_title')
131     ->render($self);
132 }
133
134 sub action_ajax_add_function_block {
135   my ($self, %params) = @_;
136
137   return $self->add_function_block('function-block');
138 }
139
140 sub action_ajax_add_sub_function_block {
141   my ($self, %params) = @_;
142
143   return $self->add_function_block('sub-function-block');
144 }
145
146 sub action_ajax_create {
147   my ($self, %params) = @_;
148
149   my $js              = SL::ClientJS->new;
150   my $prefix          = $::form->{form_prefix} || die "Missing parameter 'form_prefix'";
151   my $attributes      = $::form->{$prefix}     || die "Missing parameter group '${prefix}'";
152   my $insert_after    = delete $attributes->{insert_after};
153
154   my @errors = $self->item(SL::DB::RequirementSpecItem->new(%{ $attributes }))->validate;
155   return $js->error(@errors)->render($self) if @errors;
156
157   $self->item->save;
158   $self->item->add_to_list(position => 'after', reference => $insert_after) if $insert_after;
159
160   my $type = $self->item->get_type;
161
162   if ($type eq 'section') {
163     my $node = $self->presenter->requirement_spec_item_jstree_data($self->item);
164     return $self->render_list($js, $self->item)
165       ->jstree->create_node('#tree', $insert_after ? ('#fb-' . $insert_after, 'after') : ('#sections', 'last'), $node)
166       ->jstree->select_node('#tree', '#fb-' . $self->item->id)
167       ->render($self);
168   }
169
170   my $template = 'requirement_spec_item/_' . (apply { s/-/_/g; $_ } $type);
171   my $html     = $self->render($template, { output => 0 }, requirement_spec_item => $self->item, id_prefix => $type eq 'function-block' ? '' : 'sub-');
172   my $node     = $self->presenter->requirement_spec_item_jstree_data($self->item);
173
174   $js->replaceWith('#' . $prefix . '_form', $html)
175      ->hide('#section-list-empty')
176      ->jstree->create_node('#tree', $insert_after ? ('#fb-' . $insert_after, 'after') : ('#fb-' . $self->item->parent_id, 'last'), $node)
177      ->jstree->select_node('#tree', '#fb-' . $self->item->id);
178
179   $self->replace_bottom($js, $self->item->parent) if $type eq 'sub-function-block';
180
181   $js->render($self);
182 }
183
184 sub action_ajax_edit {
185   my ($self, %params) = @_;
186
187   $self->item(SL::DB::RequirementSpecItem->new(id => $::form->{id})->load);
188
189   my $js = SL::ClientJS->new;
190
191   if (!$self->visible_section || ($self->visible_section->id != $self->item->get_section->id)) {
192     # Show section/item to edit if it is not visible.
193
194     my $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $self->item);
195     $js->html('#column-content', $html);
196   }
197
198   if ($self->item->get_type =~ m/section/) {
199     # Edit the section header, not an item.
200     my $html = $self->render('requirement_spec_item/_section_form', { output => 0 });
201
202     $js->hide('#section-header-' . $self->item->id)
203        ->remove("#edit_section_form")
204        ->insertAfter($html, '#section-header-' . $self->item->id)
205        ->jstree->select_node('#tree', '#fb-' . $self->item->id)
206        ->focus("#edit_section_title")
207        ->val('#current_content_type', 'section')
208        ->val('#current_content_id',   $self->item->id)
209        ->render($self);
210     return;
211   }
212
213   # Edit a function block or a sub function block
214   my @dependencies          = $self->create_dependencies;
215   my @selected_dependencies = map { $_->id } @{ $self->item->dependencies };
216
217   my $html                  = $self->render('requirement_spec_item/_function_block_form', { output => 0 }, DEPENDENCIES => \@dependencies, SELECTED_DEPENDENCIES => \@selected_dependencies);
218   my $id_base               = 'edit_function_block_' . $self->item->id;
219   my $content_top_id        = '#' . $self->item->get_type . '-content-top-' . $self->item->id;
220
221   $js->hide($content_top_id)
222      ->remove("#${id_base}_form")
223      ->insertAfter($html, $content_top_id)
224      ->jstree->select_node('#tree', '#fb-' . $self->item->id)
225      ->focus("#${id_base}_description")
226      ->val('#current_content_type', $self->item->get_type)
227      ->val('#current_content_id', $self->item->id)
228      ->render($self);
229 }
230
231 sub action_ajax_update {
232   my ($self, %params) = @_;
233
234   my $js         = SL::ClientJS->new;
235   my $prefix     = $::form->{form_prefix} || die "Missing parameter 'form_prefix'";
236   my $attributes = $::form->{$prefix}     || {};
237
238   foreach (qw(requirement_spec_id parent_id position)) {
239     delete $attributes->{$_} if !defined $attributes->{$_};
240   }
241
242   my @errors = $self->item->assign_attributes(%{ $attributes })->validate;
243   return $js->error(@errors)->render($self) if @errors;
244
245   $self->item->save;
246
247   my $type = $self->item->get_type;
248
249   if ($type eq 'section') {
250     # Updated section, now update section header.
251
252     my $html = $self->render('requirement_spec_item/_section_header', { output => 0 }, requirement_spec_item => $self->item);
253
254     return SL::ClientJS->new
255       ->remove('#edit_section_form')
256       ->html('#section-header-' . $self->item->id, $html)
257       ->show('#section-header-' . $self->item->id)
258       ->jstree->rename_node('#tree', '#fb-' . $self->item->id, $::request->presenter->requirement_spec_item_tree_node_title($self->item))
259       ->render($self);
260   }
261
262   # Updated function block or sub function block. Update (sub)
263   # function block and potentially the bottom of the parent function
264   # block.
265
266   my $id_prefix    = $type eq 'function-block' ? '' : 'sub-';
267   my $html_top     = $self->render('requirement_spec_item/_function_block_content_top',    { output => 0 }, requirement_spec_item => $self->item, id_prefix => $id_prefix);
268   $id_prefix      .= 'function-block-content-';
269
270   my $js = SL::ClientJS->new
271     ->remove('#' . $prefix . '_form')
272     ->replaceWith('#' . $id_prefix . 'top-' . $self->item->id, $html_top)
273     ->jstree->rename_node('#tree', '#fb-' . $self->item->id, $::request->presenter->requirement_spec_item_tree_node_title($self->item));
274
275   $self->replace_bottom($js, $self->item, id_prefix => $id_prefix);
276   $self->replace_bottom($js, $self->item->parent) if $type eq 'sub-function-block';
277
278   $js->render($self);
279 }
280
281 sub action_ajax_delete {
282   my ($self) = @_;
283
284   my $js        = SL::ClientJS->new;
285   my $full_list = $self->item->get_full_list;
286
287   $self->item->delete;
288
289   if ($self->visible_section && ($self->visible_section->id == $self->item->id)) {
290     # Currently visible section is deleted.
291
292     my $new_section = first { $_->id != $self->item->id } @{ $self->item->requirement_spec->sections };
293     if ($new_section) {
294       $self->render_list($js, $new_section);
295
296     } else {
297       my $html = $self->render('requirement_spec_item/_no_section', { output => 0 });
298       $js->html('#column-content', $html)
299          ->val('#current_content_type', '')
300          ->val('#current_content_id', '')
301     }
302
303   } elsif ($self->visible_section && ($self->visible_section->id == $self->item->get_section->id)) {
304     # Item in currently visible section is deleted.
305
306     my $type = $self->item->get_type;
307     $js->remove('#edit_function_block_' . $self->item->id . '_form')
308        ->remove('#' . $type . '-' . $self->item->id);
309
310     $self->replace_bottom($js, $self->item->parent_id) if $type eq 'sub-function-block';
311
312     if (1 == scalar @{ $full_list }) {
313       if ($type eq 'function-block') {
314         $js->show('#section-list-empty');
315       } elsif ($type eq 'sub-function-block') {
316         $js->hide('#sub-function-block-container-' . $self->item->parent_id);
317       }
318     }
319   }
320
321   $js->jstree->delete_node('#tree', '#fb-' . $self->item->id)
322      ->render($self);
323 }
324
325 #
326 # filters
327 #
328
329 sub load_requirement_spec {
330   my ($self) = @_;
331   $self->requirement_spec(SL::DB::RequirementSpec->new(id => $::form->{requirement_spec_id})->load || die "No such requirement spec");
332 }
333
334 sub load_requirement_spec_item {
335   my ($self) = @_;
336   $self->item(SL::DB::RequirementSpecItem->new(id => $::form->{id})->load || die "No such requirement spec item");
337 }
338
339 #
340 # helpers
341 #
342
343 sub create_random_id {
344   return join '-', Time::HiRes::gettimeofday();
345 }
346
347 sub format_exception {
348   return join "\n", (split m/\n/, $@)[0..4];
349 }
350
351 sub init_visible_section {
352   my ($self)       = @_;
353
354   my $content_id   = $::form->{current_content_id};
355   my $content_type = $::form->{current_content_type};
356
357   return undef unless $content_id;
358   return undef unless $content_type =~ m/section|function-block/;
359
360   $self->visible_item(SL::DB::Manager::RequirementSpecItem->find_by(id => $content_id));
361   return undef unless $self->visible_item;
362
363   return $self->visible_section($self->visible_item->get_section);
364 }
365
366 sub init_complexities {
367   my ($self) = @_;
368
369   return SL::DB::Manager::RequirementSpecComplexity->get_all_sorted;
370 }
371
372 sub init_risks {
373   my ($self) = @_;
374
375   return SL::DB::Manager::RequirementSpecRisk->get_all_sorted;
376 }
377
378 sub replace_bottom {
379   my ($self, $js, $item_or_id) = @_;
380
381   my $item      = (ref($item_or_id) ? $item_or_id : SL::DB::RequirementSpecItem->new(id => $item_or_id))->load;
382   my $id_prefix = $item->get_type eq 'function-block' ? '' : 'sub-';
383   my $html      = $self->render('requirement_spec_item/_function_block_content_bottom', { output => 0 }, requirement_spec_item => $item, id_prefix => $id_prefix);
384   return $js->replaceWith('#' . $id_prefix . 'function-block-content-bottom-' . $item->id, $html);
385 }
386
387 sub render_list {
388   my ($self, $js, $item) = @_;
389
390   my $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $item);
391   $js->html('#column-content',      $html)
392      ->val( '#current_content_type', $item->get_type)
393      ->val( '#current_content_id',   $item->id)
394      ->jstree->select_node('#tree', '#fb-' . $item->id);
395 }
396
397 sub create_dependency_item {
398   my $self = shift;
399   [ $_[0]->id, $self->presenter->truncate(join(' ', grep { $_ } ($_[1], $_[0]->fb_number, $_[0]->description))) ];
400 }
401
402 sub create_dependencies {
403   my ($self) = @_;
404
405   return map { [ $_->fb_number . ' ' . $_->title,
406                  [ map { ( $self->create_dependency_item($_),
407                            map { $self->create_dependency_item($_, '->') } @{ $_->sorted_children })
408                        } @{ $_->sorted_children } ] ]
409              } @{ $self->item->requirement_spec->sections };
410 }
411
412 sub add_function_block {
413   my ($self, $new_type) = @_;
414
415   my $clicked_id = $::form->{id} || ($self->visible_item ? $self->visible_item->id : undef);
416
417   die "Invalid new_type '$new_type'"               if $new_type !~ m/^(?:sub-)?function-block$/;
418   die "Missing parameter 'id' and no visible item" if !$clicked_id;
419   die "Missing parameter 'requirement_spec_id'"    if !$::form->{requirement_spec_id};
420
421   my $clicked_item = SL::DB::RequirementSpecItem->new(id => $clicked_id)->load;
422   my $clicked_type = $clicked_item->get_type;
423
424   die "Invalid clicked_type '$clicked_type'" if $clicked_type !~ m/^(?: section | (?:sub-)? function-block )$/x;
425
426   my $case = "${clicked_type}:${new_type}";
427
428   my ($insert_position, $insert_reference, $parent_id, $display_reference)
429     = $case eq 'section:function-block'                ? ( 'appendTo',    $clicked_item->id,        $clicked_item->id,                '#section-list'                  )
430     : $case eq 'function-block:function-block'         ? ( 'insertAfter', $clicked_item->id,        $clicked_item->parent_id,         '#function-block-'               )
431     : $case eq 'function-block:sub-function-block'     ? ( 'appendTo'  ,  $clicked_item->id,        $clicked_item->id,                '#sub-function-block-container-' )
432     : $case eq 'sub-function-block:function-block'     ? ( 'insertAfter', $clicked_item->parent_id, $clicked_item->parent->parent_id, '#function-block-'               )
433     : $case eq 'sub-function-block:sub-function-block' ? ( 'insertAfter', $clicked_item->id,        $clicked_item->parent_id,         '#sub-function-block-'           )
434     :                                                    die "Invalid combination of 'clicked_type (section)/new_type ($new_type)'";
435
436   $self->item(SL::DB::RequirementSpecItem->new(requirement_spec_id => $::form->{requirement_spec_id}, parent_id => $parent_id));
437
438   $display_reference .= $insert_reference if $display_reference =~ m/-$/;
439   my $id_base         = join('_', 'new_function_block', Time::HiRes::gettimeofday(), int rand 1000000000000);
440   my $html            = $self->render(
441     'requirement_spec_item/_function_block_form',
442     { output => 0 },
443     DEPENDENCIES          => [ $self->create_dependencies ],
444     SELECTED_DEPENDENCIES => [],
445     requirement_spec_item => $self->item,
446     id_base               => $id_base,
447     insert_after          => $insert_position eq 'insertAfter' ? $insert_reference : undef,
448   );
449
450   my $js = SL::ClientJS->new;
451
452   my $new_section = $self->item->get_section;
453   if (!$self->visible_section || ($self->visible_section->id != $new_section->id)) {
454     # Show section/item to edit if it is not visible.
455
456     $html = $self->render('requirement_spec_item/_section', { output => 0 }, requirement_spec_item => $new_section);
457     $js->html('#column-content', $html)
458        ->val('#current_content_type', 'section')
459        ->val('#current_content_id',   $new_section->id)
460        ->jstree->select_node('#tree', '#fb-' . $new_section->id);
461   }
462
463   # $::lxdebug->message(0, "alright! clicked ID " . $::form->{id} . " type $clicked_type new_type $new_type insert_pos $insert_position ref " . ($insert_reference // '<undef>') . " parent $parent_id display_ref $display_reference");
464
465   $js->action($insert_position, $html, $display_reference)
466      ->focus("#${id_base}_description");
467
468   $js->show('#sub-function-block-container-' . $parent_id) if $new_type eq 'sub-function-block';
469
470   $js->render($self);
471 }
472
473 1;