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