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