38771d1fc1f0d54ceb7423225a59a4d6165a510e
[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 List::Util qw(sum0);
9 use POSIX qw(strftime);
10
11 use SL::Controller::Helper::GetModels;
12 use SL::Controller::Helper::ReportGenerator;
13 use SL::Controller::Helper::ReportGenerator::ControlRow qw(make_control_row);
14 use SL::DB::Customer;
15 use SL::DB::Employee;
16 use SL::DB::Order;
17 use SL::DB::Part;
18 use SL::DB::Project;
19 use SL::DB::TimeRecording;
20 use SL::DB::TimeRecordingArticle;
21 use SL::Helper::Flash qw(flash);
22 use SL::Helper::Number qw(_round_number _parse_number _round_total);
23 use SL::Helper::UserPreferences::TimeRecording;
24 use SL::Locale::String qw(t8);
25 use SL::Presenter::Tag qw(checkbox_tag);
26 use SL::ReportGenerator;
27
28 use Rose::Object::MakeMethods::Generic
29 (
30 # scalar                  => [ qw() ],
31  'scalar --get_set_init' => [ qw(time_recording models all_employees all_time_recording_articles all_orders can_view_all can_edit_all use_duration) ],
32 );
33
34
35 # safety
36 __PACKAGE__->run_before('check_auth');
37 __PACKAGE__->run_before('check_auth_edit',     only => [ qw(edit save delete) ]);
38 __PACKAGE__->run_before('check_auth_edit_all', only => [ qw(mark_as_booked) ]);
39
40
41 my %sort_columns = (
42   date         => t8('Date'),
43   start_time   => t8('Start'),
44   end_time     => t8('End'),
45   order        => t8('Sales Order'),
46   customer     => t8('Customer'),
47   part         => t8('Article'),
48   project      => t8('Project'),
49   description  => t8('Description'),
50   staff_member => t8('Mitarbeiter'),
51   duration     => t8('Duration'),
52   booked       => t8('Booked'),
53 );
54
55 #
56 # actions
57 #
58
59 sub action_list {
60   my ($self, %params) = @_;
61
62   $::form->{filter} //=  {
63     staff_member_id => SL::DB::Manager::Employee->current->id,
64     "date:date::ge" => DateTime->today_local->add(weeks => -2)->to_kivitendo,
65   };
66
67   $self->setup_list_action_bar;
68   $self->make_filter_summary;
69   $self->prepare_report;
70
71   my $objects = $self->models->get;
72
73   my $total   = sum0 map { _round_total($_->duration_in_hours) } @$objects;
74   my $total_h = int($total);
75   my $total_m = int($total * 60.0 + 0.5) % 60;
76   my $total_s = sprintf('%d:%02d', $total_h, $total_m);
77
78   push @$objects, make_control_row("separator");
79   push @$objects, make_control_row("data",
80                                    row => {
81                                      map( { $_ => {class => 'listtotal'} } keys %{$self->{report}->{columns}} ),
82                                      description => {data => t8('Total'), class => 'listtotal'},
83                                      duration    => {data => $total_s,    class => 'listtotal'}
84                                    });
85
86   $self->report_generator_list_objects(report => $self->{report}, objects => $objects);
87 }
88
89 sub action_mark_as_booked {
90   my ($self) = @_;
91
92   if (scalar @{ $::form->{ids} }) {
93     my $trs = SL::DB::Manager::TimeRecording->get_all(query => [id => $::form->{ids}]);
94     $_->update_attributes(booked => 1) for @$trs;
95   }
96
97   $self->redirect_to(safe_callback());
98 }
99
100 sub action_edit {
101   my ($self) = @_;
102
103   $::request->{layout}->use_javascript("${_}.js") for qw(kivi.TimeRecording ckeditor/ckeditor ckeditor/adapters/jquery kivi.Validator);
104
105   if ($self->use_duration) {
106     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;
107   } else {
108     flash('warning', t8('This entry is using date and duration. This information will be overwritten on saving.'))  if $self->time_recording->is_duration_used;
109   }
110
111   if ($self->time_recording->start_time) {
112     $self->{start_date} = $self->time_recording->start_time->to_kivitendo;
113     $self->{start_time} = $self->time_recording->start_time->to_kivitendo_time;
114   }
115   if ($self->time_recording->end_time) {
116     $self->{end_date}   = $self->time_recording->end_time->to_kivitendo;
117     $self->{end_time}   = $self->time_recording->end_time->to_kivitendo_time;
118   }
119
120   my $inputs_to_disable = $self->get_inputs_to_disable;
121
122   $self->setup_edit_action_bar;
123
124   $self->render('time_recording/form',
125                 title             => t8('Time Recording'),
126                 inputs_to_disable => $inputs_to_disable,
127   );
128 }
129
130 sub action_save {
131   my ($self) = @_;
132
133   if ($self->use_duration) {
134     $self->time_recording->start_time(undef);
135     $self->time_recording->end_time(undef);
136   }
137
138   my @errors = $self->time_recording->validate;
139   if (@errors) {
140     $::form->error(t8('Saving the time recording entry failed: #1', join '<br>', @errors));
141     return;
142   }
143
144   if ( !eval { $self->time_recording->save; 1; } ) {
145     $::form->error(t8('Saving the time recording entry failed: #1', $EVAL_ERROR));
146     return;
147   }
148
149   $self->redirect_to(safe_callback());
150 }
151
152 sub action_delete {
153   my ($self) = @_;
154
155   $self->time_recording->delete;
156
157   $self->redirect_to(safe_callback());
158 }
159
160 sub action_ajaj_get_order_info {
161
162   my $order = SL::DB::Order->new(id => $::form->{id})->load;
163   my $data  = { customer => { id    => $order->customer_id,
164                               value => $order->customer->displayable_name,
165                               type  => 'customer'
166                 },
167                 project => { id     =>  $order->globalproject_id,
168                              value  => ($order->globalproject_id ? $order->globalproject->displayable_name : undef),
169                 },
170   };
171
172   $_[0]->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
173 }
174
175 sub action_ajaj_get_project_info {
176
177   my $project = SL::DB::Project->new(id => $::form->{id})->load;
178
179   my $data;
180   if ($project->customer_id) {
181     $data = { customer => { id    => $project->customer_id,
182                             value => $project->customer->displayable_name,
183                             type  => 'customer'
184                           },
185     };
186   }
187
188   $_[0]->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
189 }
190
191 sub init_time_recording {
192   my ($self) = @_;
193
194   my $is_new         = !$::form->{id};
195   my $time_recording = !$is_new            ? SL::DB::TimeRecording->new(id => $::form->{id})->load
196                      : $self->use_duration ? SL::DB::TimeRecording->new(date => DateTime->today_local)
197                      :                       SL::DB::TimeRecording->new(start_time => DateTime->now_local);
198
199   my %attributes = %{ $::form->{time_recording} || {} };
200
201   if ($self->use_duration) {
202     if (exists $::form->{duration_h} || exists $::form->{duration_m}) {
203       $attributes{duration} = _round_number(_parse_number($::form->{duration_h}) * 60 + _parse_number($::form->{duration_m}), 0);
204     }
205
206   } else {
207     foreach my $type (qw(start end)) {
208       if ($::form->{$type . '_date'}) {
209         my $date = DateTime->from_kivitendo($::form->{$type . '_date'});
210         $attributes{$type . '_time'} = $date->clone;
211         if ($::form->{$type . '_time'}) {
212           my ($hour, $min) = split ':', $::form->{$type . '_time'};
213           $attributes{$type . '_time'}->set_hour($hour)  if $hour;
214           $attributes{$type . '_time'}->set_minute($min) if $min;
215         }
216       }
217     }
218   }
219
220   # do not overwrite staff member if you do not have the right
221   delete $attributes{staff_member_id}                                     if !$_[0]->can_edit_all;
222   $attributes{staff_member_id} ||= SL::DB::Manager::Employee->current->id if $is_new;
223
224   $attributes{employee_id}       = SL::DB::Manager::Employee->current->id;
225
226   $time_recording->assign_attributes(%attributes);
227
228   return $time_recording;
229 }
230
231 sub init_can_view_all {
232   $::auth->assert('time_recording_show_all', 1) || $::auth->assert('time_recording_edit_all', 1)
233 }
234
235 sub init_can_edit_all {
236   $::auth->assert('time_recording_edit_all', 1)
237 }
238
239 sub init_models {
240   my ($self) = @_;
241
242   my @where;
243   push @where, (staff_member_id => SL::DB::Manager::Employee->current->id) if !$self->can_view_all;
244
245   SL::Controller::Helper::GetModels->new(
246     controller     => $_[0],
247     sorted         => \%sort_columns,
248     disable_plugin => 'paginated',
249     query          => \@where,
250     with_objects   => [ 'customer', 'part', 'project', 'staff_member', 'employee', 'order' ],
251   );
252 }
253
254 sub init_all_employees {
255   SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
256 }
257
258 sub init_all_time_recording_articles {
259   my $selectable_parts = SL::DB::Manager::TimeRecordingArticle->get_all_sorted(
260     query        => [or => [ 'part.obsolete' => 0, 'part.obsolete' => undef ]],
261     with_objects => ['part']);
262
263   my $res              = [ map { {id => $_->part_id, description => $_->part->displayable_name} } @$selectable_parts];
264   my $curr_id          = $_[0]->time_recording->part_id;
265
266   if ($curr_id && !grep { $curr_id == $_->{id} } @$res) {
267     unshift @$res, {id => $curr_id, description => $_[0]->time_recording->part->displayable_name};
268   }
269
270   return $res;
271 }
272
273 sub init_all_orders {
274   my $orders = SL::DB::Manager::Order->get_all(query => [or             => [ closed    => 0, closed    => undef ],
275                                                          or             => [ quotation => 0, quotation => undef ],
276                                                          '!customer_id' => undef]);
277   return [ map { [$_->id, sprintf("%s %s", $_->number, $_->customervendor->name) ] } sort { $a->number <=> $b->number } @{$orders||[]} ];
278 }
279
280 sub init_use_duration {
281   return SL::Helper::UserPreferences::TimeRecording->new()->get_use_duration();
282 }
283
284 sub check_auth {
285   $::auth->assert('time_recording');
286 }
287
288 sub check_auth_edit {
289   my ($self) = @_;
290
291   if (!$self->can_edit_all && ($self->time_recording->staff_member_id != SL::DB::Manager::Employee->current->id)) {
292     $::form->error(t8('You do not have permission to access this entry.'));
293   }
294 }
295
296 sub check_auth_edit_all {
297   my ($self) = @_;
298
299   $::auth->assert('time_recording_edit_all');
300 }
301
302 sub prepare_report {
303   my ($self) = @_;
304
305   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
306   $self->{report} = $report;
307
308   my @columns  = qw(ids date start_time end_time order customer project part description staff_member duration booked);
309
310   my %column_defs = (
311     ids          => { raw_header_data => checkbox_tag("", id => "check_all", checkall  => "[data-checkall=1]"),
312                       align           => 'center',
313                       raw_data        => sub { $_[0]->booked ? '' : checkbox_tag("ids[]", value => $_[0]->id, "data-checkall" => 1) }   },
314     date         => { text => t8('Date'),         sub => sub { $_[0]->date_as_date },
315                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
316     start_time   => { text => t8('Start'),        sub => sub { $_[0]->start_time_as_timestamp },
317                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
318     end_time     => { text => t8('End'),          sub => sub { $_[0]->end_time_as_timestamp },
319                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
320     order        => { text => t8('Sales Order'),  sub => sub { $_[0]->order && $_[0]->order->number } },
321     customer     => { text => t8('Customer'),     sub => sub { $_[0]->customer->displayable_name } },
322     part         => { text => t8('Article'),      sub => sub { $_[0]->part && $_[0]->part->displayable_name } },
323     project      => { text => t8('Project'),      sub => sub { $_[0]->project && $_[0]->project->full_description(sytle => 'both') } },
324     description  => { text => t8('Description'),  sub => sub { $_[0]->description_as_stripped_html },
325                       raw_data => sub { $_[0]->description_as_restricted_html }, # raw_data only used for html(?)
326                       obj_link => sub { $self->url_for(action => 'edit', 'id' => $_[0]->id, callback => $self->models->get_callback) }  },
327     staff_member => { text => t8('Mitarbeiter'),  sub => sub { $_[0]->staff_member->safe_name } },
328     duration     => { text => t8('Duration'),     sub => sub { $_[0]->duration_as_duration_string },
329                       align => 'right'},
330     booked       => { text => t8('Booked'),       sub => sub { $_[0]->booked ? t8('Yes') : t8('No') } },
331   );
332
333   if (!$self->can_edit_all) {
334     @columns = grep {'ids' ne $_} @columns;
335     delete $column_defs{ids};
336   }
337
338   my $title        = t8('Time Recordings');
339   $report->{title} = $title;    # for browser titlebar (title-tag)
340
341   $report->set_options(
342     controller_class      => 'TimeRecording',
343     std_column_visibility => 1,
344     output_format         => 'HTML',
345     title                 => $title, # for heading
346     allow_pdf_export      => 1,
347     allow_csv_export      => 1,
348   );
349
350   $report->set_columns(%column_defs);
351   $report->set_column_order(@columns);
352   $report->set_export_options(qw(list filter));
353   $report->set_options_from_form;
354
355   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
356   $self->models->add_additional_url_params(filter => $::form->{filter});
357   $self->models->finalize;
358   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => [keys %sort_columns]);
359
360   $report->set_options(
361     raw_top_info_text    => $self->render('time_recording/report_top',    { output => 0 }),
362     raw_bottom_info_text => $self->render('time_recording/report_bottom', { output => 0 }, models => $self->models),
363     attachment_basename  => t8('time_recordings') . strftime('_%Y%m%d', localtime time),
364   );
365 }
366
367 sub make_filter_summary {
368   my ($self) = @_;
369
370   my $filter = $::form->{filter} || {};
371   my @filter_strings;
372
373   my $staff_member = $filter->{staff_member_id} ? SL::DB::Employee->new(id => $filter->{staff_member_id})->load->safe_name                         : '';
374   my $project      = $filter->{project_id}      ? SL::DB::Project->new (id => $filter->{project_id})     ->load->full_description(sytle => 'both') : '';
375
376   my @filters = (
377     [ $filter->{"date:date::ge"},                              t8('From Date')       ],
378     [ $filter->{"date:date::le"},                              t8('To Date')         ],
379     [ $filter->{"customer"}->{"name:substr::ilike"},           t8('Customer')        ],
380     [ $filter->{"customer"}->{"customernumber:substr::ilike"}, t8('Customer Number') ],
381     [ $filter->{"order"}->{"ordnumber:substr::ilike"},         t8('Order Number')    ],
382     [ $project,                                                t8('Project')         ],
383     [ $filter->{"description:substr::ilike"},                  t8('Description')     ],
384     [ $staff_member,                                           t8('Mitarbeiter')     ],
385   );
386
387   for (@filters) {
388     push @filter_strings, "$_->[1]: $_->[0]" if $_->[0];
389   }
390
391   $self->{filter_summary} = join ', ', @filter_strings;
392 }
393
394 sub setup_list_action_bar {
395   my ($self) = @_;
396
397   for my $bar ($::request->layout->get('actionbar')) {
398     $bar->add(
399       action => [
400         t8('Update'),
401         submit    => [ '#filter_form', { action => 'TimeRecording/list' } ],
402         accesskey => 'enter',
403       ],
404       combobox => [
405         action => [
406           t8('Actions'),
407           only_if => $self->can_edit_all,
408         ],
409         action => [
410           t8('Mark as booked'),
411           submit  => [ '#form', { action => 'TimeRecording/mark_as_booked', callback => $self->models->get_callback } ],
412           checks  => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
413           confirm => $::locale->text('Do you really want to mark the selected entries as booked?'),
414           only_if => $self->can_edit_all,
415         ],
416       ],
417       action => [
418         t8('Add'),
419         link => $self->url_for(action => 'edit', callback => $self->models->get_callback),
420       ],
421     );
422   }
423 }
424
425 sub setup_edit_action_bar {
426   my ($self) = @_;
427
428   for my $bar ($::request->layout->get('actionbar')) {
429     $bar->add(
430       action => [
431         t8('Save'),
432         submit => [ '#form', { action => 'TimeRecording/save' } ],
433         checks => [ 'kivi.validate_form' ],
434       ],
435       action => [
436         t8('Delete'),
437         submit  => [ '#form', { action => 'TimeRecording/delete' } ],
438         only_if => $self->time_recording->id,
439       ],
440       action => [
441         t8('Cancel'),
442         link  => $self->url_for(safe_callback()),
443       ],
444     );
445   }
446 }
447
448 sub safe_callback {
449   $::form->{callback} || (action => 'list')
450 }
451
452 sub get_inputs_to_disable {
453   my ($self) = @_;
454
455   return [qw(customer project)]  if $self->time_recording->order_id;
456   return [qw(customer)]          if $self->time_recording->project_id && $self->time_recording->project->customer_id;
457 }
458
459
460 1;