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