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