marei: new koma-names + fallback for outdated versions
[kivitendo-erp.git] / SL / Controller / Project.pm
1 package SL::Controller::Project;
2
3 use strict;
4
5 use parent qw(SL::Controller::Base);
6
7 use Clone qw(clone);
8
9 use SL::Controller::Helper::GetModels;
10 use SL::Controller::Helper::ParseFilter;
11 use SL::Controller::Helper::ReportGenerator;
12 use SL::CVar;
13 use SL::DB::Customer;
14 use SL::DB::DeliveryOrder;
15 use SL::DB::Employee;
16 use SL::DB::Invoice;
17 use SL::DB::Order;
18 use SL::DB::Project;
19 use SL::DB::ProjectType;
20 use SL::DB::ProjectStatus;
21 use SL::DB::PurchaseInvoice;
22 use SL::DB::ProjectType;
23 use SL::Helper::Flash;
24 use SL::Locale::String;
25
26 use Data::Dumper;
27 use JSON;
28 use Rose::DB::Object::Helpers qw(as_tree);
29
30 use Rose::Object::MakeMethods::Generic
31 (
32  scalar => [ qw(project) ],
33  'scalar --get_set_init' => [ qw(models customers project_types project_statuses projects linked_records employees may_edit_invoice_permissions
34                                  cvar_configs includeable_cvar_configs include_cvars) ],
35 );
36
37 __PACKAGE__->run_before('check_auth',   except => [ qw(ajax_autocomplete) ]);
38 __PACKAGE__->run_before('load_project', only   => [ qw(edit update destroy) ]);
39 __PACKAGE__->run_before('use_multiselect_js', only => [ qw(new create edit update) ]);
40
41 #
42 # actions
43 #
44
45 sub action_list {
46   my ($self) = @_;
47
48   $self->setup_list_action_bar;
49
50   $self->make_filter_summary;
51
52   $self->prepare_report;
53
54   $self->report_generator_list_objects(report => $self->{report}, objects => $self->models->get);
55 }
56
57 sub action_new {
58   my ($self) = @_;
59
60   $self->project(SL::DB::Project->new);
61   $self->display_form(title    => $::locale->text('Create a new project'),
62                       callback => $::form->{callback} || $self->url_for(action => 'list'));
63 }
64
65 sub action_edit {
66   my ($self) = @_;
67
68   $self->display_form(title    => $::locale->text('Edit project #1', $self->project->projectnumber),
69                       callback => $::form->{callback} || $self->url_for(action => 'list'));
70 }
71
72 sub action_create {
73   my ($self) = @_;
74
75   $self->project(SL::DB::Project->new);
76   $self->create_or_update;
77 }
78
79 sub action_update {
80   my ($self) = @_;
81   $self->create_or_update;
82 }
83
84 sub action_destroy {
85   my ($self) = @_;
86
87   if (eval { $self->project->delete; 1; }) {
88     flash_later('info',  $::locale->text('The project has been deleted.'));
89   } else {
90     flash_later('error', $::locale->text('The project is in use and cannot be deleted.'));
91   }
92
93   $self->redirect_to(action => 'list');
94 }
95
96 sub action_ajax_autocomplete {
97   my ($self, %params) = @_;
98
99   $::form->{filter}{'all:substr:multi::ilike'} =~ s{[\(\)]+}{}g;
100
101   # if someone types something, and hits enter, assume he entered the full name.
102   # if something matches, treat that as the sole match
103   # unfortunately get_models can't do more than one per package atm, so we do it
104   # the oldfashioned way.
105   if ($::form->{prefer_exact}) {
106     my $exact_matches;
107     if (1 == scalar @{ $exact_matches = SL::DB::Manager::Project->get_all(
108       query => [
109         valid => 1,
110         or => [
111           description   => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
112           projectnumber => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
113         ]
114       ],
115       limit => 2,
116     ) }) {
117       $self->projects($exact_matches);
118     }
119   }
120
121   $::form->{sort_by} = 'customer_and_description';
122
123   my @hashes = map {
124    +{
125      value         => $_->full_description(style => 'full'),
126      label         => $_->full_description(style => 'full'),
127      id            => $_->id,
128      projectnumber => $_->projectnumber,
129      description   => $_->description,
130      cvars         => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
131     }
132   } @{ $self->projects }; # neato: if exact match triggers we don't even need the init_projects
133
134   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
135 }
136
137 sub action_test_page {
138   $_[0]->render('project/test_page');
139 }
140
141 #
142 # filters
143 #
144
145 sub check_auth {
146   $::auth->assert('project_edit');
147 }
148
149 #
150 # helpers
151 #
152
153 sub init_project_statuses { SL::DB::Manager::ProjectStatus->get_all_sorted }
154 sub init_project_types    { SL::DB::Manager::ProjectType->get_all_sorted   }
155 sub init_employees        { SL::DB::Manager::Employee->get_all_sorted   }
156 sub init_may_edit_invoice_permissions { $::auth->assert('project_edit_view_invoices_permission', 1) }
157 sub init_cvar_configs                 { SL::DB::Manager::CustomVariableConfig->get_all_sorted(where => [ module => 'Projects' ]) }
158 sub init_includeable_cvar_configs     { [ grep { $_->includeable } @{ $_[0]->cvar_configs } ] };
159
160 sub init_include_cvars {
161   my ($self) = @_;
162   return { map { ($_->name => $::form->{"include_cvars_" . $_->name}) }       @{ $self->cvar_configs } } if $::form->{_include_cvars_from_form};
163   return { map { ($_->name => ($_->includeable && $_->included_by_default)) } @{ $self->cvar_configs } };
164 }
165
166 sub init_linked_records {
167   my ($self) = @_;
168   return [
169     map  { @{ $_ } }
170     grep { $_      } (
171       SL::DB::Manager::Invoice->        get_all(where        => [ invoice => 1, or => [ globalproject_id => $self->project->id, 'invoiceitems.project_id' => $self->project->id ] ],
172                                                 with_objects => [ 'invoiceitems', 'customer' ],
173                                                 distinct     => [ 'customer' ],
174                                                 sort_by       => 'transdate ASC'),
175       SL::DB::Manager::Invoice->        get_all(where        => [ invoice => 0, or => [ globalproject_id => $self->project->id, 'transactions.project_id' => $self->project->id ] ],
176                                                 with_objects => [ 'transactions', 'customer' ],
177                                                 distinct     => [ 'customer' ],
178                                                 sort_by       => 'transdate ASC'),
179       SL::DB::Manager::PurchaseInvoice->get_all(where => [ invoice => 1,
180                                                            or => [ globalproject_id => $self->project->id, 'invoiceitems.project_id' => $self->project->id ]
181                                                          ],
182                                                 with_objects => [ 'invoiceitems', 'vendor' ],
183                                                 distinct     => [ 'customer' ],
184                                                 sort_by => 'transdate ASC'),
185       SL::DB::Manager::PurchaseInvoice->get_all(where => [ invoice => 0,
186                                                            or => [ globalproject_id => $self->project->id, 'transactions.project_id' => $self->project->id ]
187                                                          ],
188                                                 with_objects => [ 'transactions', 'vendor' ],
189                                                 distinct     => [ 'customer' ],
190                                                 sort_by => 'transdate ASC'),
191       SL::DB::Manager::GLTransaction->  get_all(where => [ 'transactions.project_id' => $self->project->id ],
192                                                 with_objects => [ 'transactions' ],
193                                                 distinct     => 1,
194                                                 sort_by => 'transdate ASC'),
195       SL::DB::Manager::Order->          get_all(where => [ or => [ globalproject_id => $self->project->id, 'orderitems.project_id' => $self->project->id ] ],
196                                                 with_objects => [ 'orderitems', 'customer', 'vendor' ],
197                                                 distinct => [ 'customer', 'vendor' ],
198                                                 sort_by => 'transdate ASC' ),
199       SL::DB::Manager::DeliveryOrder->  get_all(where => [ or => [ globalproject_id => $self->project->id, 'orderitems.project_id' => $self->project->id ] ],
200                                                 with_objects => [ 'orderitems', 'customer', 'vendor' ],
201                                                 distinct => [ 'customer', 'vendor' ],
202                                                 sort_by => 'transdate ASC'),
203     )];
204 }
205
206
207 sub init_projects {
208   if ($::form->{no_paginate}) {
209     $_[0]->models->disable_plugin('paginated');
210   }
211
212   $_[0]->models->get;
213 }
214
215 sub init_customers {
216   my ($self)      = @_;
217   my @customer_id = $self->project && $self->project->customer_id ? (id => $self->project->customer_id) : ();
218
219   return SL::DB::Manager::Customer->get_all_sorted(where => [ or => [ obsolete => 0, obsolete => undef, @customer_id ]]);
220 }
221
222 sub use_multiselect_js {
223   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
224 }
225
226 sub display_form {
227   my ($self, %params) = @_;
228
229   $params{CUSTOM_VARIABLES}  = CVar->get_custom_variables(module => 'Projects', trans_id => $self->project->id);
230
231   if ($params{keep_cvars}) {
232     for my $cvar (@{ $params{CUSTOM_VARIABLES} }) {
233       $cvar->{value} = $::form->{"cvar_$cvar->{name}"} if $::form->{"cvar_$cvar->{name}"};
234     }
235   }
236
237   CVar->render_inputs(variables => $params{CUSTOM_VARIABLES}) if @{ $params{CUSTOM_VARIABLES} };
238
239   $self->setup_edit_action_bar(callback => $params{callback});
240
241   $self->render('project/form', %params);
242 }
243
244 sub create_or_update {
245   my $self   = shift;
246   my $is_new = !$self->project->id;
247   my $params = delete($::form->{project}) || { };
248
249   if (!$self->may_edit_invoice_permissions) {
250     delete $params->{employee_invoice_permissions};
251   } elsif (!$params->{employee_invoice_permissions}) {
252     $params->{employee_invoice_permissions} = [];
253   }
254
255   delete $params->{id};
256   $self->project->assign_attributes(%{ $params });
257
258   my @errors = $self->project->validate;
259
260   if (@errors) {
261     flash('error', @errors);
262     $self->display_form(title    => $is_new ? $::locale->text('Create a new project') : $::locale->text('Edit project'),
263                         callback => $::form->{callback},
264                         keep_cvars => 1);
265     return;
266   }
267
268   $self->project->save;
269
270   CVar->save_custom_variables(
271     dbh          => $self->project->db->dbh,
272     module       => 'Projects',
273     trans_id     => $self->project->id,
274     variables    => $::form,
275     always_valid => 1,
276   );
277
278   flash_later('info', $is_new ? $::locale->text('The project has been created.') : $::locale->text('The project has been saved.'));
279
280   $self->redirect_to($::form->{callback} || (action => 'search'));
281 }
282
283 sub load_project {
284   my ($self) = @_;
285   $self->project(SL::DB::Project->new(id => $::form->{id})->load);
286 }
287
288
289 sub prepare_report {
290   my ($self)      = @_;
291
292   my $callback    = $self->models->get_callback;
293
294   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
295   $self->{report} = $report;
296
297   my @columns     = qw(project_status customer projectnumber description active valid project_type);
298   my @sortable    = qw(projectnumber description customer              project_type project_status);
299
300   my %column_defs = (
301     projectnumber => { obj_link => sub { $self->url_for(action => 'edit', id => $_[0]->id, callback => $callback) } },
302     description   => { obj_link => sub { $self->url_for(action => 'edit', id => $_[0]->id, callback => $callback) } },
303     project_type  => { sub  => sub { $_[0]->project_type->description } },
304     project_status => { sub  => sub { $_[0]->project_status->description }, text => t8('Status') },
305     customer      => { sub       => sub { !$_[0]->customer_id ? '' : $_[0]->customer->name },
306                        raw_data  => sub { !$_[0]->customer_id ? '' : $_[0]->customer->presenter->customer(display => 'table-cell', callback => $callback) } },
307     active        => { sub  => sub { $_[0]->active   ? $::locale->text('Active') : $::locale->text('Inactive') },
308                        text => $::locale->text('Active') },
309     valid         => { sub  => sub { $_[0]->valid    ? $::locale->text('Valid')  : $::locale->text('Invalid')  },
310                        text => $::locale->text('Valid')  },
311   );
312
313   map { $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) } keys %column_defs;
314
315   # Custom variables
316   my %cvar_column_defs = map {
317     my $cfg = $_;
318     (('cvar_' . $cfg->name) => {
319       sub     => sub { my $var = $_[0]->cvar_by_name($cfg->name); $var ? $var->value_as_text : '' },
320       text    => $cfg->description,
321       visible => $self->include_cvars->{ $cfg->name } ? 1 : 0,
322     })
323   } @{ $self->includeable_cvar_configs };
324
325   push @columns, map { 'cvar_' . $_->name } @{ $self->includeable_cvar_configs };
326   %column_defs = (%column_defs, %cvar_column_defs);
327
328   my @cvar_column_form_names = ('_include_cvars_from_form', map { "include_cvars_" . $_->name } @{ $self->includeable_cvar_configs });
329
330   $report->set_options(
331     std_column_visibility => 1,
332     controller_class      => 'Project',
333     output_format         => 'HTML',
334     title                 => $::locale->text('Projects'),
335     allow_pdf_export      => 1,
336     allow_csv_export      => 1,
337   );
338   $report->set_columns(%column_defs);
339   $report->set_column_order(@columns);
340   $report->set_export_options(qw(list filter), @cvar_column_form_names);
341   $report->set_options_from_form;
342   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
343   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
344   $report->set_options(
345     raw_top_info_text     => $self->render('project/report_top',    { output => 0 }),
346     raw_bottom_info_text  => $self->render('project/report_bottom', { output => 0 }),
347   );
348 }
349
350 sub init_models {
351   my ($self) = @_;
352
353   SL::Controller::Helper::GetModels->new(
354     controller => $self,
355     sorted => {
356       _default => {
357         by    => 'projectnumber',
358         dir   => 1,
359       },
360       customer       => t8('Customer'),
361       description    => t8('Description'),
362       projectnumber  => t8('Project Number'),
363       project_type   => t8('Project Type'),
364       project_status => t8('Project Status'),
365       customer_and_description => 1,
366     },
367     with_objects => [ 'customer', 'project_status', 'project_type' ],
368   );
369 }
370
371 sub make_filter_summary {
372   my ($self) = @_;
373
374   my $filter = $::form->{filter} || {};
375   my @filter_strings;
376
377   my @filters = (
378     [ $filter->{"projectnumber:substr::ilike"},  t8('Project Number') ],
379     [ $filter->{"description:substr::ilike"},    t8('Description')    ],
380     [ $filter->{customer}{"name:substr::ilike"}, t8('Customer')       ],
381     [ $filter->{"project_type_id"},              t8('Project Type'),    sub { SL::DB::Manager::ProjectType->find_by(id => $filter->{"project_type_id"})->description }   ],
382     [ $filter->{"project_status_id"},            t8('Project Status'),  sub { SL::DB::Manager::ProjectStatus->find_by(id => $filter->{"project_status_id"})->description } ],
383   );
384
385   my @flags = (
386     [ $filter->{active} eq 'active',    $::locale->text('Active')      ],
387     [ $filter->{active} eq 'inactive',  $::locale->text('Inactive')    ],
388     [ $filter->{valid}  eq 'valid',     $::locale->text('Valid')       ],
389     [ $filter->{valid}  eq 'invalid',   $::locale->text('Invalid')     ],
390     [ $filter->{orphaned},              $::locale->text('Orphaned')    ],
391   );
392
393   for (@flags) {
394     push @filter_strings, "$_->[1]" if $_->[0];
395   }
396   for (@filters) {
397     push @filter_strings, "$_->[1]: " . ($_->[2] ? $_->[2]->() : $_->[0]) if $_->[0];
398   }
399
400   $self->{filter_summary} = join ', ', @filter_strings;
401 }
402
403 sub setup_edit_action_bar {
404   my ($self, %params) = @_;
405
406   my $is_new = !$self->project->id;
407
408   for my $bar ($::request->layout->get('actionbar')) {
409     $bar->add(
410       combobox => [
411         action => [
412           t8('Save'),
413           submit    => [ '#form', { action => 'Project/' . ($is_new ? 'create' : 'update') } ],
414           accesskey => 'enter',
415         ],
416         action => [
417           t8('Save as new'),
418           submit   => [ '#form', { action => 'Project/create' }],
419           disabled => $is_new ? t8('The object has not been saved yet.') : undef,
420         ],
421       ], # end of combobox "Save"
422
423       action => [
424         t8('Delete'),
425         submit   => [ '#form', { action => 'Project/destroy' } ],
426         confirm  => $::locale->text('Do you really want to delete this object?'),
427         disabled => $is_new                 ? t8('This object has not been saved yet.')
428                   : $self->project->is_used ? t8('This object has already been used.')
429                   :                           undef,
430       ],
431
432       link => [
433         t8('Abort'),
434         link => $params{callback} || $self->url_for(action => 'list'),
435       ],
436     );
437   }
438 }
439
440 sub setup_list_action_bar {
441   my ($self, %params) = @_;
442
443   for my $bar ($::request->layout->get('actionbar')) {
444     $bar->add(
445       action => [
446         t8('Update'),
447         submit    => [ '#search_form', { action => 'Project/list' } ],
448         accesskey => 'enter',
449       ],
450       link => [
451         t8('Add'),
452         link => $self->url_for(action => 'new'),
453       ],
454     );
455   }
456 }
457
458 1;