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