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