ba460c597ed9af63456f3d28453a41d74bb32dc9
[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   # since we need a second get models instance with different filters for that,
104   # we only modify the original filter temporarily in place
105   if ($::form->{prefer_exact}) {
106     local $::form->{filter}{'all::ilike'} = delete local $::form->{filter}{'all:substr:multi::ilike'};
107     # active and valid filters are use as they are
108
109     my $exact_models = SL::Controller::Helper::GetModels->new(
110       controller   => $self,
111       sorted       => 0,
112       paginated    => { per_page => 2 },
113       with_objects => [ 'customer', 'project_status', 'project_type' ],
114     );
115     my $exact_matches;
116     if (1 == scalar @{ $exact_matches = $exact_models->get }) {
117       $self->project($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 sub action_project_picker_search {
142   $_[0]->render('project/project_picker_search', { layout => 0 });
143 }
144
145 sub action_project_picker_result {
146   $_[0]->render('project/_project_picker_result', { layout => 0 });
147 }
148
149 #
150 # filters
151 #
152
153 sub check_auth {
154   $::auth->assert('project_edit');
155 }
156
157 #
158 # helpers
159 #
160
161 sub init_project_statuses { SL::DB::Manager::ProjectStatus->get_all_sorted }
162 sub init_project_types    { SL::DB::Manager::ProjectType->get_all_sorted   }
163 sub init_employees        { SL::DB::Manager::Employee->get_all_sorted   }
164 sub init_may_edit_invoice_permissions { $::auth->assert('project_edit_view_invoices_permission', 1) }
165 sub init_cvar_configs                 { SL::DB::Manager::CustomVariableConfig->get_all_sorted(where => [ module => 'Projects' ]) }
166 sub init_includeable_cvar_configs     { [ grep { $_->includeable } @{ $_[0]->cvar_configs } ] };
167
168 sub init_include_cvars {
169   my ($self) = @_;
170   return { map { ($_->name => $::form->{"include_cvars_" . $_->name}) }       @{ $self->cvar_configs } } if $::form->{_include_cvars_from_form};
171   return { map { ($_->name => ($_->includeable && $_->included_by_default)) } @{ $self->cvar_configs } };
172 }
173
174 sub init_linked_records {
175   my ($self) = @_;
176   return [
177     map  { @{ $_ } }
178     grep { $_      } (
179       SL::DB::Manager::Invoice->        get_all(where        => [ invoice => 1, or => [ globalproject_id => $self->project->id, 'invoiceitems.project_id' => $self->project->id ] ],
180                                                 with_objects => [ 'invoiceitems', 'customer' ],
181                                                 distinct     => [ 'customer' ],
182                                                 sort_by       => 'transdate ASC'),
183       SL::DB::Manager::Invoice->        get_all(where        => [ invoice => 0, or => [ globalproject_id => $self->project->id, 'transactions.project_id' => $self->project->id ] ],
184                                                 with_objects => [ 'transactions', 'customer' ],
185                                                 distinct     => [ 'customer' ],
186                                                 sort_by       => 'transdate ASC'),
187       SL::DB::Manager::PurchaseInvoice->get_all(where => [ invoice => 1,
188                                                            or => [ globalproject_id => $self->project->id, 'invoiceitems.project_id' => $self->project->id ]
189                                                          ],
190                                                 with_objects => [ 'invoiceitems', 'vendor' ],
191                                                 distinct     => [ 'customer' ],
192                                                 sort_by => 'transdate ASC'),
193       SL::DB::Manager::PurchaseInvoice->get_all(where => [ invoice => 0,
194                                                            or => [ globalproject_id => $self->project->id, 'transactions.project_id' => $self->project->id ]
195                                                          ],
196                                                 with_objects => [ 'transactions', 'vendor' ],
197                                                 distinct     => [ 'customer' ],
198                                                 sort_by => 'transdate ASC'),
199       SL::DB::Manager::GLTransaction->  get_all(where => [ 'transactions.project_id' => $self->project->id ],
200                                                 with_objects => [ 'transactions' ],
201                                                 distinct     => 1,
202                                                 sort_by => 'transdate ASC'),
203       SL::DB::Manager::Order->          get_all(where => [ or => [ globalproject_id => $self->project->id, 'orderitems.project_id' => $self->project->id ] ],
204                                                 with_objects => [ 'orderitems', 'customer', 'vendor' ],
205                                                 distinct => [ 'customer', 'vendor' ],
206                                                 sort_by => 'transdate ASC' ),
207       SL::DB::Manager::DeliveryOrder->  get_all(where => [ or => [ globalproject_id => $self->project->id, 'orderitems.project_id' => $self->project->id ] ],
208                                                 with_objects => [ 'orderitems', 'customer', 'vendor' ],
209                                                 distinct => [ 'customer', 'vendor' ],
210                                                 sort_by => 'transdate ASC'),
211     )];
212 }
213
214
215 sub init_projects {
216   if ($::form->{no_paginate}) {
217     $_[0]->models->disable_plugin('paginated');
218   }
219
220   $_[0]->models->get;
221 }
222
223 sub init_customers {
224   my ($self)      = @_;
225   my @customer_id = $self->project && $self->project->customer_id ? (id => $self->project->customer_id) : ();
226
227   return SL::DB::Manager::Customer->get_all_sorted(where => [ or => [ obsolete => 0, obsolete => undef, @customer_id ]]);
228 }
229
230 sub use_multiselect_js {
231   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
232 }
233
234 sub display_form {
235   my ($self, %params) = @_;
236
237   $params{CUSTOM_VARIABLES}  = CVar->get_custom_variables(module => 'Projects', trans_id => $self->project->id);
238
239   if ($params{keep_cvars}) {
240     for my $cvar (@{ $params{CUSTOM_VARIABLES} }) {
241       $cvar->{value} = $::form->{"cvar_$cvar->{name}"} if $::form->{"cvar_$cvar->{name}"};
242     }
243   }
244
245   CVar->render_inputs(variables => $params{CUSTOM_VARIABLES}) if @{ $params{CUSTOM_VARIABLES} };
246
247   $::request->layout->use_javascript('kivi.File.js');
248   $self->setup_edit_action_bar(callback => $params{callback});
249
250   $self->render('project/form', %params);
251 }
252
253 sub create_or_update {
254   my $self   = shift;
255   my $is_new = !$self->project->id;
256   my $params = delete($::form->{project}) || { };
257
258   if (!$self->may_edit_invoice_permissions) {
259     delete $params->{employee_invoice_permissions};
260   } elsif (!$params->{employee_invoice_permissions}) {
261     $params->{employee_invoice_permissions} = [];
262   }
263
264   delete $params->{id};
265   $self->project->assign_attributes(%{ $params });
266
267   my @errors = $self->project->validate;
268
269   if (@errors) {
270     flash('error', @errors);
271     $self->display_form(title    => $is_new ? $::locale->text('Create a new project') : $::locale->text('Edit project'),
272                         callback => $::form->{callback},
273                         keep_cvars => 1);
274     return;
275   }
276
277   $self->project->save;
278
279   CVar->save_custom_variables(
280     dbh          => $self->project->db->dbh,
281     module       => 'Projects',
282     trans_id     => $self->project->id,
283     variables    => $::form,
284     always_valid => 1,
285   );
286
287   flash_later('info', $is_new ? $::locale->text('The project has been created.') : $::locale->text('The project has been saved.'));
288
289   $self->redirect_to($::form->{callback} || (action => 'search'));
290 }
291
292 sub load_project {
293   my ($self) = @_;
294   $self->project(SL::DB::Project->new(id => $::form->{id})->load);
295 }
296
297
298 sub prepare_report {
299   my ($self)      = @_;
300
301   my $callback    = $self->models->get_callback;
302
303   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
304   $self->{report} = $report;
305
306   my @columns     = qw(project_status customer projectnumber description active valid project_type);
307   my @sortable    = qw(projectnumber description customer              project_type project_status);
308
309   my %column_defs = (
310     projectnumber => { obj_link => sub { $self->url_for(action => 'edit', id => $_[0]->id, callback => $callback) } },
311     description   => { obj_link => sub { $self->url_for(action => 'edit', id => $_[0]->id, callback => $callback) } },
312     project_type  => { sub  => sub { $_[0]->project_type->description } },
313     project_status => { sub  => sub { $_[0]->project_status->description }, text => t8('Status') },
314     customer      => { sub       => sub { !$_[0]->customer_id ? '' : $_[0]->customer->name },
315                        raw_data  => sub { !$_[0]->customer_id ? '' : $_[0]->customer->presenter->customer(display => 'table-cell', callback => $callback) } },
316     active        => { sub  => sub { $_[0]->active   ? $::locale->text('Active') : $::locale->text('Inactive') },
317                        text => $::locale->text('Active') },
318     valid         => { sub  => sub { $_[0]->valid    ? $::locale->text('Valid')  : $::locale->text('Invalid')  },
319                        text => $::locale->text('Valid')  },
320   );
321
322   map { $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) } keys %column_defs;
323
324   # Custom variables
325   my %cvar_column_defs = map {
326     my $cfg = $_;
327     (('cvar_' . $cfg->name) => {
328       sub     => sub { my $var = $_[0]->cvar_by_name($cfg->name); $var ? $var->value_as_text : '' },
329       text    => $cfg->description,
330       visible => $self->include_cvars->{ $cfg->name } ? 1 : 0,
331     })
332   } @{ $self->includeable_cvar_configs };
333
334   push @columns, map { 'cvar_' . $_->name } @{ $self->includeable_cvar_configs };
335   %column_defs = (%column_defs, %cvar_column_defs);
336
337   my @cvar_column_form_names = ('_include_cvars_from_form', map { "include_cvars_" . $_->name } @{ $self->includeable_cvar_configs });
338
339   $report->set_options(
340     std_column_visibility => 1,
341     controller_class      => 'Project',
342     output_format         => 'HTML',
343     title                 => $::locale->text('Projects'),
344     allow_pdf_export      => 1,
345     allow_csv_export      => 1,
346   );
347   $report->set_columns(%column_defs);
348   $report->set_column_order(@columns);
349   $report->set_export_options(qw(list filter), @cvar_column_form_names);
350   $report->set_options_from_form;
351   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
352   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
353   $report->set_options(
354     raw_top_info_text     => $self->render('project/report_top',    { output => 0 }),
355     raw_bottom_info_text  => $self->render('project/report_bottom', { output => 0 }),
356   );
357 }
358
359 sub init_models {
360   my ($self) = @_;
361
362   SL::Controller::Helper::GetModels->new(
363     controller => $self,
364     sorted => {
365       _default => {
366         by    => 'projectnumber',
367         dir   => 1,
368       },
369       customer       => t8('Customer'),
370       description    => t8('Description'),
371       projectnumber  => t8('Project Number'),
372       project_type   => t8('Project Type'),
373       project_status => t8('Project Status'),
374       customer_and_description => 1,
375     },
376     with_objects => [ 'customer', 'project_status', 'project_type' ],
377   );
378 }
379
380 sub make_filter_summary {
381   my ($self) = @_;
382
383   my $filter = $::form->{filter} || {};
384   my @filter_strings;
385
386   my @filters = (
387     [ $filter->{"projectnumber:substr::ilike"},  t8('Project Number') ],
388     [ $filter->{"description:substr::ilike"},    t8('Description')    ],
389     [ $filter->{customer}{"name:substr::ilike"}, t8('Customer')       ],
390     [ $filter->{"project_type_id"},              t8('Project Type'),    sub { SL::DB::Manager::ProjectType->find_by(id => $filter->{"project_type_id"})->description }   ],
391     [ $filter->{"project_status_id"},            t8('Project Status'),  sub { SL::DB::Manager::ProjectStatus->find_by(id => $filter->{"project_status_id"})->description } ],
392   );
393
394   my @flags = (
395     [ $filter->{active} eq 'active',    $::locale->text('Active')      ],
396     [ $filter->{active} eq 'inactive',  $::locale->text('Inactive')    ],
397     [ $filter->{valid}  eq 'valid',     $::locale->text('Valid')       ],
398     [ $filter->{valid}  eq 'invalid',   $::locale->text('Invalid')     ],
399     [ $filter->{orphaned},              $::locale->text('Orphaned')    ],
400   );
401
402   for (@flags) {
403     push @filter_strings, "$_->[1]" if $_->[0];
404   }
405   for (@filters) {
406     push @filter_strings, "$_->[1]: " . ($_->[2] ? $_->[2]->() : $_->[0]) if $_->[0];
407   }
408
409   $self->{filter_summary} = join ', ', @filter_strings;
410 }
411
412 sub setup_edit_action_bar {
413   my ($self, %params) = @_;
414
415   my $is_new = !$self->project->id;
416
417   for my $bar ($::request->layout->get('actionbar')) {
418     $bar->add(
419       combobox => [
420         action => [
421           t8('Save'),
422           submit    => [ '#form', { action => 'Project/' . ($is_new ? 'create' : 'update') } ],
423           accesskey => 'enter',
424         ],
425         action => [
426           t8('Save as new'),
427           submit   => [ '#form', { action => 'Project/create' }],
428           disabled => $is_new ? t8('The object has not been saved yet.') : undef,
429         ],
430       ], # end of combobox "Save"
431
432       action => [
433         t8('Delete'),
434         submit   => [ '#form', { action => 'Project/destroy' } ],
435         confirm  => $::locale->text('Do you really want to delete this object?'),
436         disabled => $is_new                 ? t8('This object has not been saved yet.')
437                   : $self->project->is_used ? t8('This object has already been used.')
438                   :                           undef,
439       ],
440
441       link => [
442         t8('Abort'),
443         link => $params{callback} || $self->url_for(action => 'list'),
444       ],
445     );
446   }
447 }
448
449 sub setup_list_action_bar {
450   my ($self, %params) = @_;
451
452   for my $bar ($::request->layout->get('actionbar')) {
453     $bar->add(
454       action => [
455         t8('Update'),
456         submit    => [ '#search_form', { action => 'Project/list' } ],
457         accesskey => 'enter',
458       ],
459       link => [
460         t8('Add'),
461         link => $self->url_for(action => 'new'),
462       ],
463     );
464   }
465 }
466
467 1;