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