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