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