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