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