Verbrauchsbericht: Lager->Berichte->Lagerentnahme
[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 linked_records) ],
32  'scalar --get_set_init' => [ qw(models customers project_types project_statuses projects) ],
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->render('project/search', %params);
55 }
56
57 sub action_list {
58   my ($self) = @_;
59
60   $self->make_filter_summary;
61
62   $self->prepare_report;
63
64   $self->report_generator_list_objects(report => $self->{report}, objects => $self->models->get);
65 }
66
67 sub action_new {
68   my ($self) = @_;
69
70   $self->project(SL::DB::Project->new);
71   $self->display_form(title    => $::locale->text('Create a new project'),
72                       callback => $::form->{callback} || $self->url_for(action => 'new'));
73 }
74
75 sub action_edit {
76   my ($self) = @_;
77
78   $self->get_linked_records;
79   $self->display_form(title    => $::locale->text('Edit project #1', $self->project->projectnumber),
80                       callback => $::form->{callback} || $self->url_for(action => 'edit', id => $self->project->id));
81 }
82
83 sub action_create {
84   my ($self) = @_;
85
86   $self->project(SL::DB::Project->new);
87   $self->create_or_update;
88 }
89
90 sub action_update {
91   my ($self) = @_;
92   $self->create_or_update;
93 }
94
95 sub action_destroy {
96   my ($self) = @_;
97
98   if (eval { $self->project->delete; 1; }) {
99     flash_later('info',  $::locale->text('The project has been deleted.'));
100   } else {
101     flash_later('error', $::locale->text('The project is in use and cannot be deleted.'));
102   }
103
104   $self->redirect_to(action => 'search');
105 }
106
107 sub action_ajax_autocomplete {
108   my ($self, %params) = @_;
109
110   $::form->{filter}{'all:substr:multi::ilike'} =~ s{[\(\)]+}{}g;
111
112   # if someone types something, and hits enter, assume he entered the full name.
113   # if something matches, treat that as sole match
114   # unfortunately get_models can't do more than one per package atm, so we d it
115   # the oldfashioned way.
116   if ($::form->{prefer_exact}) {
117     my $exact_matches;
118     if (1 == scalar @{ $exact_matches = SL::DB::Manager::Project->get_all(
119       query => [
120         valid => 1,
121         or => [
122           description   => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
123           projectnumber => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
124         ]
125       ],
126       limit => 2,
127     ) }) {
128       $self->projects($exact_matches);
129     }
130   }
131
132   $::form->{sort_by} = 'customer_and_description';
133
134   my @hashes = map {
135    +{
136      value         => $_->full_description(style => 'full'),
137      label         => $_->full_description(style => 'full'),
138      id            => $_->id,
139      projectnumber => $_->projectnumber,
140      description   => $_->description,
141      cvars         => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
142     }
143   } @{ $self->projects }; # neato: if exact match triggers we don't even need the init_projects
144
145   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
146 }
147
148 sub action_test_page {
149   $_[0]->render('project/test_page');
150 }
151
152 #
153 # filters
154 #
155
156 sub check_auth {
157   $::auth->assert('project_edit');
158 }
159
160 #
161 # helpers
162 #
163
164 sub init_project_statuses { SL::DB::Manager::ProjectStatus->get_all_sorted }
165 sub init_project_types    { SL::DB::Manager::ProjectType->get_all_sorted   }
166
167 sub init_projects {
168   if ($::form->{no_paginate}) {
169     $_[0]->models->disable_plugin('paginated');
170   }
171
172   $_[0]->models->get;
173 }
174
175 sub init_customers {
176   my ($self)      = @_;
177   my @customer_id = $self->project && $self->project->customer_id ? (id => $self->project->customer_id) : ();
178
179   return SL::DB::Manager::Customer->get_all_sorted(where => [ or => [ obsolete => 0, obsolete => undef, @customer_id ]]);
180 }
181
182 sub display_form {
183   my ($self, %params) = @_;
184
185   $params{CUSTOM_VARIABLES}  = CVar->get_custom_variables(module => 'Projects', trans_id => $self->project->id);
186
187   if ($params{keep_cvars}) {
188     for my $cvar (@{ $params{CUSTOM_VARIABLES} }) {
189       $cvar->{value} = $::form->{"cvar_$cvar->{name}"} if $::form->{"cvar_$cvar->{name}"};
190     }
191   }
192
193   CVar->render_inputs(variables => $params{CUSTOM_VARIABLES}) if @{ $params{CUSTOM_VARIABLES} };
194
195   $self->render('project/form', %params);
196 }
197
198 sub create_or_update {
199   my $self   = shift;
200   my $is_new = !$self->project->id;
201   my $params = delete($::form->{project}) || { };
202
203   delete $params->{id};
204   $self->project->assign_attributes(%{ $params });
205
206   my @errors = $self->project->validate;
207
208   if (@errors) {
209     flash('error', @errors);
210     $self->display_form(title    => $is_new ? $::locale->text('Create a new project') : $::locale->text('Edit project'),
211                         callback => $::form->{callback},
212                         keep_cvars => 1);
213     return;
214   }
215
216   $self->project->save;
217
218   CVar->save_custom_variables(
219     dbh          => $self->project->db->dbh,
220     module       => 'Projects',
221     trans_id     => $self->project->id,
222     variables    => $::form,
223     always_valid => 1,
224   );
225
226   flash_later('info', $is_new ? $::locale->text('The project has been created.') : $::locale->text('The project has been saved.'));
227
228   $self->redirect_to($::form->{callback} || (action => 'search'));
229 }
230
231 sub load_project {
232   my ($self) = @_;
233   $self->project(SL::DB::Project->new(id => $::form->{id})->load);
234 }
235
236 sub get_linked_records {
237   my ($self) = @_;
238
239   $self->linked_records([
240     map  { @{ $_ } }
241     grep { $_      } (
242       SL::DB::Manager::Order->          get_all(where => [ globalproject_id => $self->project->id ], with_objects => [ 'customer', 'vendor' ], sort_by => 'transdate ASC'),
243       SL::DB::Manager::DeliveryOrder->  get_all(where => [ globalproject_id => $self->project->id ], with_objects => [ 'customer', 'vendor' ], sort_by => 'transdate ASC'),
244       SL::DB::Manager::Invoice->        get_all(where => [ globalproject_id => $self->project->id ], with_objects => [ 'customer'           ], sort_by => 'transdate ASC'),
245       SL::DB::Manager::PurchaseInvoice->get_all(where => [ globalproject_id => $self->project->id ], with_objects => [             'vendor' ], sort_by => 'transdate ASC'),
246     )]);
247 }
248
249 sub prepare_report {
250   my ($self)      = @_;
251
252   my $callback    = $self->models->get_callback;
253
254   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
255   $self->{report} = $report;
256
257   my @columns     = qw(project_status customer projectnumber description active valid project_type);
258   my @sortable    = qw(projectnumber description customer              project_type project_status);
259
260   my %column_defs = (
261     projectnumber => { obj_link => sub { $self->url_for(action => 'edit', id => $_[0]->id, callback => $callback) } },
262     description   => { obj_link => sub { $self->url_for(action => 'edit', id => $_[0]->id, callback => $callback) } },
263     project_type  => { sub  => sub { $_[0]->project_type->description } },
264     project_status => { sub  => sub { $_[0]->project_status->description }, text => t8('Status') },
265     customer      => { sub       => sub { !$_[0]->customer_id ? '' : $_[0]->customer->name },
266                        raw_data  => sub { !$_[0]->customer_id ? '' : $self->presenter->customer($_[0]->customer, display => 'table-cell', callback => $callback) } },
267     active        => { sub  => sub { $_[0]->active   ? $::locale->text('Active') : $::locale->text('Inactive') },
268                        text => $::locale->text('Active') },
269     valid         => { sub  => sub { $_[0]->valid    ? $::locale->text('Valid')  : $::locale->text('Invalid')  },
270                        text => $::locale->text('Valid')  },
271   );
272
273   map { $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) } keys %column_defs;
274
275   $report->set_options(
276     std_column_visibility => 1,
277     controller_class      => 'Project',
278     output_format         => 'HTML',
279     title                 => $::locale->text('Projects'),
280     allow_pdf_export      => 1,
281     allow_csv_export      => 1,
282   );
283   $report->set_columns(%column_defs);
284   $report->set_column_order(@columns);
285   $report->set_export_options(qw(list filter));
286   $report->set_options_from_form;
287   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
288   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
289   $report->set_options(
290     raw_top_info_text     => $self->render('project/report_top',    { output => 0 }),
291     raw_bottom_info_text  => $self->render('project/report_bottom', { output => 0 }),
292   );
293 }
294
295 sub init_models {
296   my ($self) = @_;
297
298   SL::Controller::Helper::GetModels->new(
299     controller => $self,
300     sorted => {
301       _default => {
302         by    => 'projectnumber',
303         dir   => 1,
304       },
305       customer       => t8('Customer'),
306       description    => t8('Description'),
307       projectnumber  => t8('Project Number'),
308       project_type   => t8('Project Type'),
309       project_status => t8('Project Status'),
310       customer_and_description => 1,
311     },
312     with_objects => [ 'customer', 'project_status', 'project_type' ],
313   );
314 }
315
316 sub make_filter_summary {
317   my ($self) = @_;
318
319   my $filter = $::form->{filter} || {};
320   my @filter_strings;
321
322   my @filters = (
323     [ $filter->{"projectnumber:substr::ilike"},  t8('Project Number') ],
324     [ $filter->{"description:substr::ilike"},    t8('Description')    ],
325     [ $filter->{customer}{"name:substr::ilike"}, t8('Customer')       ],
326     [ $filter->{"project_type_id"},              t8('Project Type'),    sub { SL::DB::Manager::ProjectType->find_by(id => $filter->{"project_type_id"})->description }   ],
327     [ $filter->{"project_status_id"},            t8('Project Status'),  sub { SL::DB::Manager::ProjectStatus->find_by(id => $filter->{"project_status_id"})->description } ],
328   );
329
330   my @flags = (
331     [ $filter->{active} eq 'active',    $::locale->text('Active')      ],
332     [ $filter->{active} eq 'inactive',  $::locale->text('Inactive')    ],
333     [ $filter->{valid}  eq 'valid',     $::locale->text('Valid')       ],
334     [ $filter->{valid}  eq 'invalid',   $::locale->text('Invalid')     ],
335     [ $filter->{orphaned},              $::locale->text('Orphaned')    ],
336   );
337
338   for (@flags) {
339     push @filter_strings, "$_->[1]" if $_->[0];
340   }
341   for (@filters) {
342     push @filter_strings, "$_->[1]: " . ($_->[2] ? $_->[2]->() : $_->[0]) if $_->[0];
343   }
344
345   $self->{filter_summary} = join ', ', @filter_strings;
346 }
347 1;