Zeiterfassung: Artikel beim Erfassen wählen können und mit auflisten
[kivitendo-erp.git] / SL / Controller / TimeRecording.pm
1 package SL::Controller::TimeRecording;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use DateTime;
7 use English qw(-no_match_vars);
8 use POSIX qw(strftime);
9
10 use SL::Controller::Helper::GetModels;
11 use SL::Controller::Helper::ReportGenerator;
12 use SL::DB::Customer;
13 use SL::DB::Employee;
14 use SL::DB::Part;
15 use SL::DB::TimeRecording;
16 use SL::DB::TimeRecordingArticle;
17 use SL::Locale::String qw(t8);
18 use SL::ReportGenerator;
19
20 use Rose::Object::MakeMethods::Generic
21 (
22 # scalar                  => [ qw() ],
23  'scalar --get_set_init' => [ qw(time_recording models all_employees all_time_recording_articles can_view_all can_edit_all) ],
24 );
25
26
27 # safety
28 __PACKAGE__->run_before('check_auth');
29 __PACKAGE__->run_before('check_auth_edit', only => [ qw(edit save delete) ]);
30
31 my %sort_columns = (
32   start_time   => t8('Start'),
33   end_time     => t8('End'),
34   customer     => t8('Customer'),
35   part         => t8('Article'),
36   project      => t8('Project'),
37   description  => t8('Description'),
38   staff_member => t8('Mitarbeiter'),
39   duration     => t8('Duration'),
40 );
41
42 #
43 # actions
44 #
45
46 sub action_list {
47   my ($self, %params) = @_;
48
49   $::form->{filter} //=  {
50     staff_member_id       => SL::DB::Manager::Employee->current->id,
51     "start_time:date::ge" => DateTime->now_local->add(weeks => -2)->to_kivitendo,
52   };
53
54   $self->setup_list_action_bar;
55   $self->make_filter_summary;
56   $self->prepare_report;
57
58   $self->report_generator_list_objects(report => $self->{report}, objects => $self->models->get);
59 }
60
61 sub action_edit {
62   my ($self) = @_;
63
64   $::request->{layout}->use_javascript("${_}.js") for qw(kivi.TimeRecording ckeditor/ckeditor ckeditor/adapters/jquery kivi.Validator);
65
66   if ($self->time_recording->start_time) {
67     $self->{start_date} = $self->time_recording->start_time->to_kivitendo;
68     $self->{start_time} = $self->time_recording->start_time->to_kivitendo_time;
69   }
70   if ($self->time_recording->end_time) {
71     $self->{end_date}   = $self->time_recording->end_time->to_kivitendo;
72     $self->{end_time}   = $self->time_recording->end_time->to_kivitendo_time;
73   }
74
75   $self->setup_edit_action_bar;
76
77   $self->render('time_recording/form',
78                 title  => t8('Time Recording'),
79   );
80 }
81
82 sub action_save {
83   my ($self) = @_;
84
85   my @errors = $self->time_recording->validate;
86   if (@errors) {
87     $::form->error(t8('Saving the time recording entry failed: #1', join '<br>', @errors));
88     return;
89   }
90
91   if ( !eval { $self->time_recording->save; 1; } ) {
92     $::form->error(t8('Saving the time recording entry failed: #1', $EVAL_ERROR));
93     return;
94   }
95
96   $self->redirect_to(safe_callback());
97 }
98
99 sub action_delete {
100   my ($self) = @_;
101
102   $self->time_recording->delete;
103
104   $self->redirect_to(safe_callback());
105 }
106
107 sub init_time_recording {
108   my $is_new         = !$::form->{id};
109   my $time_recording = $is_new ? SL::DB::TimeRecording->new(start_time => DateTime->now_local)
110                                : SL::DB::TimeRecording->new(id => $::form->{id})->load;
111
112   my %attributes = %{ $::form->{time_recording} || {} };
113
114   foreach my $type (qw(start end)) {
115     if ($::form->{$type . '_date'}) {
116       my $date = DateTime->from_kivitendo($::form->{$type . '_date'});
117       $attributes{$type . '_time'} = $date->clone;
118       if ($::form->{$type . '_time'}) {
119         my ($hour, $min) = split ':', $::form->{$type . '_time'};
120         $attributes{$type . '_time'}->set_hour($hour)  if $hour;
121         $attributes{$type . '_time'}->set_minute($min) if $min;
122       }
123     }
124   }
125
126   # do not overwright staff member if you do not have the right
127   delete $attributes{staff_member_id} if !$_[0]->can_edit_all;
128   $attributes{staff_member_id} = SL::DB::Manager::Employee->current->id if $is_new;
129
130   $attributes{employee_id}     = SL::DB::Manager::Employee->current->id;
131
132   $time_recording->assign_attributes(%attributes);
133
134   return $time_recording;
135 }
136
137 sub init_can_view_all {
138   $::auth->assert('time_recording_show_all', 1) || $::auth->assert('time_recording_edit_all', 1)
139 }
140
141 sub init_can_edit_all {
142   $::auth->assert('time_recording_edit_all', 1)
143 }
144
145 sub init_models {
146   my ($self) = @_;
147
148   my @where;
149   push @where, (staff_member_id => SL::DB::Manager::Employee->current->id) if !$self->can_view_all;
150
151   SL::Controller::Helper::GetModels->new(
152     controller     => $_[0],
153     sorted         => \%sort_columns,
154     disable_plugin => 'paginated',
155     query          => \@where,
156     with_objects   => [ 'customer', 'part', 'project', 'staff_member', 'employee' ],
157   );
158 }
159
160 sub init_all_employees {
161   SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
162 }
163
164 sub init_all_time_recording_articles {
165   my $selectable_parts = SL::DB::Manager::TimeRecordingArticle->get_all_sorted(
166     query        => [or => [ 'part.obsolete' => 0, 'part.obsolete' => undef ]],
167     with_objects => ['part']);
168
169   my $res              = [ map { {id => $_->part_id, description => $_->part->displayable_name} } @$selectable_parts];
170   my $curr_id          = $_[0]->time_recording->part_id;
171
172   if ($curr_id && !grep { $curr_id == $_->{id} } @$res) {
173     unshift @$res, {id => $curr_id, description => $_[0]->time_recording->part->displayable_name};
174   }
175
176   return $res;
177 }
178
179 sub check_auth {
180   $::auth->assert('time_recording');
181 }
182
183 sub check_auth_edit {
184   my ($self) = @_;
185
186   if (!$self->can_edit_all && ($self->time_recording->staff_member_id != SL::DB::Manager::Employee->current->id)) {
187     $::form->error(t8('You do not have permission to access this entry.'));
188   }
189 }
190
191 sub prepare_report {
192   my ($self) = @_;
193
194   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
195   $self->{report} = $report;
196
197   my @columns  = qw(start_time end_time customer part project description staff_member duration);
198
199   my %column_defs = (
200     start_time   => { text => t8('Start'),        sub => sub { $_[0]->start_time_as_timestamp },
201                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
202     end_time     => { text => t8('End'),          sub => sub { $_[0]->end_time_as_timestamp },
203                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
204     customer     => { text => t8('Customer'),     sub => sub { $_[0]->customer->displayable_name } },
205     part         => { text => t8('Article'),      sub => sub { $_[0]->part && $_[0]->part->displayable_name } },
206     project      => { text => t8('Project'),      sub => sub { $_[0]->project && $_[0]->project->displayable_name } },
207     description  => { text => t8('Description'),  sub => sub { $_[0]->description_as_stripped_html },
208                       raw_data => sub { $_[0]->description_as_restricted_html }, # raw_data only used for html(?)
209                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
210     staff_member => { text => t8('Mitarbeiter'),  sub => sub { $_[0]->staff_member->safe_name } },
211     duration     => { text => t8('Duration'),     sub => sub { $_[0]->duration_as_duration_string },
212                       align => 'right'},
213   );
214
215   $report->set_options(
216     controller_class      => 'TimeRecording',
217     std_column_visibility => 1,
218     output_format         => 'HTML',
219     title                 => t8('Time Recordings'),
220     allow_pdf_export      => 1,
221     allow_csv_export      => 1,
222   );
223
224   $report->set_columns(%column_defs);
225   $report->set_column_order(@columns);
226   $report->set_export_options(qw(list filter));
227   $report->set_options_from_form;
228
229   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
230   $self->models->add_additional_url_params(filter => $::form->{filter});
231   $self->models->finalize;
232   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => [keys %sort_columns]);
233
234   $report->set_options(
235     raw_top_info_text    => $self->render('time_recording/report_top',    { output => 0 }),
236     raw_bottom_info_text => $self->render('time_recording/report_bottom', { output => 0 }, models => $self->models),
237     attachment_basename  => t8('time_recordings') . strftime('_%Y%m%d', localtime time),
238   );
239 }
240
241 sub make_filter_summary {
242   my ($self) = @_;
243
244   my $filter = $::form->{filter} || {};
245   my @filter_strings;
246
247   my $staff_member = $filter->{staff_member_id} ? SL::DB::Employee->new(id => $filter->{staff_member_id})->load->safe_name : '';
248
249   my @filters = (
250     [ $filter->{"start_time:date::ge"},                        t8('From Start')      ],
251     [ $filter->{"start_time:date::le"},                        t8('To Start')        ],
252     [ $filter->{"customer"}->{"name:substr::ilike"},           t8('Customer')        ],
253     [ $filter->{"customer"}->{"customernumber:substr::ilike"}, t8('Customer Number') ],
254     [ $staff_member,                                           t8('Mitarbeiter')     ],
255   );
256
257   for (@filters) {
258     push @filter_strings, "$_->[1]: $_->[0]" if $_->[0];
259   }
260
261   $self->{filter_summary} = join ', ', @filter_strings;
262 }
263
264 sub setup_list_action_bar {
265   my ($self) = @_;
266
267   for my $bar ($::request->layout->get('actionbar')) {
268     $bar->add(
269       action => [
270         t8('Update'),
271         submit    => [ '#filter_form', { action => 'TimeRecording/list' } ],
272         accesskey => 'enter',
273       ],
274       action => [
275         t8('Add'),
276         link => $self->url_for(action => 'edit', callback => $self->models->get_callback),
277       ],
278     );
279   }
280 }
281
282 sub setup_edit_action_bar {
283   my ($self) = @_;
284
285   for my $bar ($::request->layout->get('actionbar')) {
286     $bar->add(
287       action => [
288         t8('Save'),
289         submit => [ '#form', { action => 'TimeRecording/save' } ],
290         checks => [ 'kivi.validate_form' ],
291       ],
292       action => [
293         t8('Delete'),
294         submit  => [ '#form', { action => 'TimeRecording/delete' } ],
295         only_if => $self->time_recording->id,
296       ],
297       action => [
298         t8('Cancel'),
299         link  => $self->url_for(safe_callback()),
300       ],
301     );
302   }
303 }
304
305 sub safe_callback {
306   $::form->{callback} || (action => 'list')
307 }
308
309 1;