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