Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / SL / Controller / Admin.pm
1 package SL::Controller::Admin;
2
3 use strict;
4
5 use parent qw(SL::Controller::Base);
6
7 use IO::Dir;
8 use List::Util qw(first);
9
10 use SL::Common ();
11 use SL::DB::AuthUser;
12 use SL::DB::AuthGroup;
13 use SL::DB::Printer;
14 use SL::Helper::Flash;
15 use SL::Locale::String qw(t8);
16 use SL::System::InstallationLock;
17 use SL::User;
18
19 use Rose::Object::MakeMethods::Generic
20 (
21   'scalar --get_set_init' => [ qw(client user group printer db_cfg is_locked
22                                   all_dateformats all_numberformats all_countrycodes all_stylesheets all_menustyles all_clients all_groups all_users all_rights all_printers
23                                   all_dbsources all_unused_dbsources all_accounting_methods all_inventory_systems all_profit_determinations all_charts) ],
24 );
25
26 __PACKAGE__->run_before(\&setup_layout);
27 __PACKAGE__->run_before(\&setup_client, only => [ qw(list_printers new_printer edit_printer save_printer delete_printer) ]);
28
29 sub get_auth_level { "admin" };
30 sub keep_auth_vars {
31   my ($class, %params) = @_;
32   return $params{action} eq 'login';
33 }
34
35 #
36 # actions: login, logout
37 #
38
39 sub action_login {
40   my ($self) = @_;
41
42   return $self->login_form if !$::form->{do_login};
43   return                   if !$self->authenticate_root;
44   return                   if !$self->check_auth_db_and_tables;
45   return                   if  $self->apply_dbupgrade_scripts;
46
47   $self->redirect_to(action => 'show');
48 }
49
50 sub action_logout {
51   my ($self) = @_;
52   $::auth->destroy_session;
53   $self->redirect_to(action => 'login');
54 }
55
56 #
57 # actions: creating the authentication database & tables, applying database ugprades
58 #
59
60 sub action_apply_dbupgrade_scripts {
61   my ($self) = @_;
62
63   return if $self->apply_dbupgrade_scripts;
64   $self->redirect_to(action => 'show');
65 }
66
67 sub action_create_auth_db {
68   my ($self) = @_;
69
70   $::auth->create_database(superuser          => $::form->{db_superuser},
71                            superuser_password => $::form->{db_superuser_password},
72                            template           => $::form->{db_template});
73   $self->check_auth_db_and_tables;
74 }
75
76 sub action_create_auth_tables {
77   my ($self) = @_;
78
79   $::auth->create_tables;
80   $::auth->set_session_value('admin_password', $::lx_office_conf{authentication}->{admin_password});
81   $::auth->create_or_refresh_session;
82
83   my $group = (SL::DB::Manager::AuthGroup->get_all(limit => 1))[0];
84   if (!$group) {
85     SL::DB::AuthGroup->new(
86       name        => t8('Full Access'),
87       description => t8('Full access to all functions'),
88       rights      => [ map { SL::DB::AuthGroupRight->new(right => $_, granted => 1) } SL::Auth::all_rights() ],
89     )->save;
90   }
91
92   if (!$self->apply_dbupgrade_scripts) {
93     $self->action_login;
94   }
95 }
96
97 #
98 # actions: users
99 #
100
101 sub action_show {
102   my ($self) = @_;
103
104   $self->render(
105     "admin/show",
106     title => "kivitendo " . t8('Administration'),
107   );
108 }
109
110 sub action_new_user {
111   my ($self) = @_;
112
113   $self->user(SL::DB::AuthUser->new(
114     config_values => {
115       vclimit      => 200,
116       countrycode  => "de",
117       numberformat => "1.000,00",
118       dateformat   => "dd.mm.yy",
119       stylesheet   => "kivitendo.css",
120       menustyle    => "neu",
121     },
122   ));
123
124   $self->edit_user_form(title => t8('Create a new user'));
125 }
126
127 sub action_edit_user {
128   my ($self) = @_;
129   $self->edit_user_form(title => t8('Edit User'));
130 }
131
132 sub action_save_user {
133   my ($self) = @_;
134   my $params = delete($::form->{user})          || { };
135   my $props  = delete($params->{config_values}) || { };
136   my $is_new = !$params->{id};
137
138   $self->user($is_new ? SL::DB::AuthUser->new : SL::DB::AuthUser->new(id => $params->{id})->load)
139     ->assign_attributes(%{ $params })
140     ->config_values({ %{ $self->user->config_values }, %{ $props } });
141
142   my @errors = $self->user->validate;
143
144   if (@errors) {
145     flash('error', @errors);
146     $self->edit_user_form(title => $is_new ? t8('Create a new user') : t8('Edit User'));
147     return;
148   }
149
150   $self->user->save;
151
152   if ($::auth->can_change_password && $::form->{new_password}) {
153     $::auth->change_password($self->user->login, $::form->{new_password});
154   }
155
156   flash_later('info', $is_new ? t8('The user has been created.') : t8('The user has been saved.'));
157   $self->redirect_to(action => 'show');
158 }
159
160 sub action_delete_user {
161   my ($self) = @_;
162
163   my @clients = @{ $self->user->clients || [] };
164
165   if (!$self->user->delete) {
166     flash('error', t8('The user could not be deleted.'));
167     $self->edit_user_form(title => t8('Edit User'));
168     return;
169   }
170
171   # Flag corresponding entries in 'employee' as deleted.
172   foreach my $client (@clients) {
173     my $dbh = $client->dbconnect(AutoCommit => 1) || next;
174     $dbh->do(qq|UPDATE employee SET deleted = TRUE WHERE login = ?|, undef, $self->user->login);
175     $dbh->disconnect;
176   }
177
178   flash_later('info', t8('The user has been deleted.'));
179   $self->redirect_to(action => 'show');
180 }
181
182 #
183 # actions: clients
184 #
185
186 sub action_new_client {
187   my ($self) = @_;
188
189   $self->client(SL::DB::AuthClient->new(
190     dbhost   => $::auth->{DB_config}->{host},
191     dbport   => $::auth->{DB_config}->{port},
192     dbuser   => $::auth->{DB_config}->{user},
193     dbpasswd => $::auth->{DB_config}->{password},
194   ));
195
196   $self->edit_client_form(title => t8('Create a new client'));
197 }
198
199 sub action_edit_client {
200   my ($self) = @_;
201   $self->edit_client_form(title => t8('Edit Client'));
202 }
203
204 sub action_save_client {
205   my ($self) = @_;
206   my $params = delete($::form->{client}) || { };
207   my $is_new = !$params->{id};
208
209   $self->client($is_new ? SL::DB::AuthClient->new : SL::DB::AuthClient->new(id => $params->{id})->load)->assign_attributes(%{ $params });
210
211   my @errors = $self->client->validate;
212
213   if (@errors) {
214     flash('error', @errors);
215     $self->edit_client_form(title => $is_new ? t8('Create a new client') : t8('Edit Client'));
216     return;
217   }
218
219   $self->client->save;
220   if ($self->client->is_default) {
221     SL::DB::Manager::AuthClient->update_all(set => { is_default => 0 }, where => [ '!id' => $self->client->id ]);
222   }
223
224   flash_later('info', $is_new ? t8('The client has been created.') : t8('The client has been saved.'));
225   $self->redirect_to(action => 'show');
226 }
227
228 sub action_delete_client {
229   my ($self) = @_;
230
231   if (!$self->client->delete) {
232     flash('error', t8('The client could not be deleted.'));
233     $self->edit_client_form(title => t8('Edit Client'));
234     return;
235   }
236
237   flash_later('info', t8('The client has been deleted.'));
238   $self->redirect_to(action => 'show');
239 }
240
241 sub action_test_database_connectivity {
242   my ($self)    = @_;
243
244   my %cfg       = %{ $::form->{client} || {} };
245   my $dbconnect = 'dbi:Pg:dbname=' . $cfg{dbname} . ';host=' . $cfg{dbhost} . ';port=' . $cfg{dbport};
246   my $dbh       = DBI->connect($dbconnect, $cfg{dbuser}, $cfg{dbpasswd});
247
248   my $ok        = !!$dbh;
249   my $error     = $DBI::errstr;
250
251   $dbh->disconnect if $dbh;
252
253   $self->render('admin/test_db_connection',
254                 title => t8('Database Connection Test'),
255                 ok    => $ok,
256                 error => $error);
257 }
258
259 #
260 # actions: groups
261 #
262
263 sub action_new_group {
264   my ($self) = @_;
265
266   $self->group(SL::DB::AuthGroup->new);
267   $self->edit_group_form(title => t8('Create a new group'));
268 }
269
270 sub action_edit_group {
271   my ($self) = @_;
272   $self->edit_group_form(title => t8('Edit User Group'));
273 }
274
275 sub action_save_group {
276   my ($self) = @_;
277
278   my $params = delete($::form->{group}) || { };
279   my $is_new = !$params->{id};
280
281   $self->group($is_new ? SL::DB::AuthGroup->new : SL::DB::AuthGroup->new(id => $params->{id})->load)->assign_attributes(%{ $params });
282
283   my @errors = $self->group->validate;
284
285   if (@errors) {
286     flash('error', @errors);
287     $self->edit_group_form(title => $is_new ? t8('Create a new user group') : t8('Edit User Group'));
288     return;
289   }
290
291   $self->group->save;
292
293   flash_later('info', $is_new ? t8('The user group has been created.') : t8('The user group has been saved.'));
294   $self->redirect_to(action => 'show');
295 }
296
297 sub action_delete_group {
298   my ($self) = @_;
299
300   if (!$self->group->delete) {
301     flash('error', t8('The user group could not be deleted.'));
302     $self->edit_group_form(title => t8('Edit User Group'));
303     return;
304   }
305
306   flash_later('info', t8('The user group has been deleted.'));
307   $self->redirect_to(action => 'show');
308 }
309
310 #
311 # actions: printers
312 #
313
314 sub action_list_printers {
315   my ($self) = @_;
316   $self->render('admin/list_printers', title => t8('Printer management'));
317 }
318
319 sub action_new_printer {
320   my ($self) = @_;
321
322   $self->printer(SL::DB::Printer->new);
323   $self->edit_printer_form(title => t8('Create a new printer'));
324 }
325
326 sub action_edit_printer {
327   my ($self) = @_;
328   $self->edit_printer_form(title => t8('Edit Printer'));
329 }
330
331 sub action_save_printer {
332   my ($self) = @_;
333   my $params = delete($::form->{printer}) || { };
334   my $is_new = !$params->{id};
335
336   $self->printer($is_new ? SL::DB::Printer->new : SL::DB::Printer->new(id => $params->{id})->load)->assign_attributes(%{ $params });
337
338   my @errors = $self->printer->validate;
339
340   if (@errors) {
341     flash('error', @errors);
342     $self->edit_printer_form(title => $is_new ? t8('Create a new printer') : t8('Edit Printer'));
343     return;
344   }
345
346   $self->printer->save;
347
348   flash_later('info', $is_new ? t8('The printer has been created.') : t8('The printer has been saved.'));
349   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
350 }
351
352 sub action_delete_printer {
353   my ($self) = @_;
354
355   if (!$self->printer->delete) {
356     flash('error', t8('The printer could not be deleted.'));
357     $self->edit_printer_form(title => t8('Edit Printer'));
358     return;
359   }
360
361   flash_later('info', t8('The printer has been deleted.'));
362   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
363 }
364
365 #
366 # actions: database administration
367 #
368
369 sub action_database_administration {
370   my ($self) = @_;
371
372   $::form->{dbhost}    ||= $::auth->{DB_config}->{host} || 'localhost';
373   $::form->{dbport}    ||= $::auth->{DB_config}->{port} || 5432;
374   $::form->{dbuser}    ||= $::auth->{DB_config}->{user} || 'kivitendo';
375   $::form->{dbpasswd}  ||= $::auth->{DB_config}->{password};
376   $::form->{dbdefault} ||= 'template1';
377
378   $::request->layout->focus('#dbhost');
379
380   $self->render('admin/dbadmin', title => t8('Database Administration'));
381 }
382
383 sub action_create_dataset {
384   my ($self) = @_;
385   $self->create_dataset_form;
386 }
387
388 sub action_do_create_dataset {
389   my ($self) = @_;
390
391   my @errors;
392   push @errors, t8("Dataset missing!")          if !$::form->{db};
393   push @errors, t8("Default currency missing!") if !$::form->{defaultcurrency};
394
395   if (@errors) {
396     flash('error', @errors);
397     return $self->create_dataset_form;
398   }
399
400   $::form->{encoding} = 'UNICODE';
401   User->new->dbcreate($::form);
402
403   flash_later('info', t8("The dataset #1 has been created.", $::form->{db}));
404   $self->redirect_to(action => 'database_administration');
405 }
406
407 sub action_delete_dataset {
408   my ($self) = @_;
409   $self->delete_dataset_form;
410 }
411
412 sub action_do_delete_dataset {
413   my ($self) = @_;
414
415   my @errors;
416   push @errors, t8("Dataset missing!") if !$::form->{db};
417
418   if (@errors) {
419     flash('error', @errors);
420     return $self->create_dataset_form;
421   }
422
423   User->new->dbdelete($::form);
424
425   flash_later('info', t8("The dataset #1 has been deleted.", $::form->{db}));
426   $self->redirect_to(action => 'database_administration');
427 }
428
429 #
430 # actions: locking, unlocking
431 #
432
433 sub action_unlock_system {
434   my ($self) = @_;
435
436   SL::System::InstallationLock->unlock;
437   flash_later('info', t8('Lockfile removed!'));
438   $self->redirect_to(action => 'show');
439 }
440
441 sub action_lock_system {
442   my ($self) = @_;
443
444   SL::System::InstallationLock->unlock;
445   flash_later('info', t8('Lockfile created!'));
446   $self->redirect_to(action => 'show');
447 }
448
449 #
450 # initializers
451 #
452
453 sub init_db_cfg            { $::lx_office_conf{'authentication/database'}                                                    }
454 sub init_is_locked         { SL::System::InstallationLock->is_locked                                                         }
455 sub init_client            { SL::DB::Manager::AuthClient->find_by(id => ($::form->{id} || ($::form->{client}  || {})->{id})) }
456 sub init_user              { SL::DB::AuthUser  ->new(id => ($::form->{id} || ($::form->{user}    || {})->{id}))->load        }
457 sub init_group             { SL::DB::AuthGroup ->new(id => ($::form->{id} || ($::form->{group}   || {})->{id}))->load        }
458 sub init_printer           { SL::DB::Printer   ->new(id => ($::form->{id} || ($::form->{printer} || {})->{id}))->load        }
459 sub init_all_clients       { SL::DB::Manager::AuthClient->get_all_sorted                                                     }
460 sub init_all_users         { SL::DB::Manager::AuthUser  ->get_all_sorted                                                     }
461 sub init_all_groups        { SL::DB::Manager::AuthGroup ->get_all_sorted                                                     }
462 sub init_all_printers      { SL::DB::Manager::Printer   ->get_all_sorted                                                     }
463 sub init_all_dateformats   { [ qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd)      ]                                              }
464 sub init_all_numberformats { [ qw(1,000.00 1000.00 1.000,00 1000,00)          ]                                              }
465 sub init_all_stylesheets   { [ qw(lx-office-erp.css Mobile.css kivitendo.css) ]                                              }
466 sub init_all_dbsources             { [ sort User->dbsources($::form)                               ] }
467 sub init_all_unused_dbsources      { [ sort User->dbsources_unused($::form)                        ] }
468 sub init_all_accounting_methods    { [ { id => 'accrual',   name => t8('Accrual accounting')  }, { id => 'cash',     name => t8('Cash accounting')       } ] }
469 sub init_all_inventory_systems     { [ { id => 'perpetual', name => t8('Perpetual inventory') }, { id => 'periodic', name => t8('Periodic inventory')    } ] }
470 sub init_all_profit_determinations { [ { id => 'balance',   name => t8('Balancing')           }, { id => 'income',   name => t8('Cash basis accounting') } ] }
471
472 sub init_all_charts {
473   tie my %dir_h, 'IO::Dir', 'sql/';
474
475   return [
476     map { s/-chart\.sql$//; +{ id => $_ } }
477     sort
478     grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ }
479     keys %dir_h
480   ];
481 }
482
483 sub init_all_menustyles    {
484   return [
485     { id => 'old', title => $::locale->text('Old (on the side)') },
486     { id => 'v3',  title => $::locale->text('Top (CSS)') },
487     { id => 'neu', title => $::locale->text('Top (Javascript)') },
488   ];
489 }
490
491 sub init_all_rights {
492   my (@sections, $current_section);
493
494   foreach my $entry ($::auth->all_rights_full) {
495     if ($entry->[0] =~ m/^--/) {
496       push @sections, { description => $entry->[1], rights => [] };
497
498     } elsif (@sections) {
499       push @{ $sections[-1]->{rights} }, {
500         name        => $entry->[0],
501         description => $entry->[1],
502       };
503
504     } else {
505       die "Right without sections: " . join('::', @{ $entry });
506     }
507   }
508
509   return \@sections;
510 }
511
512 sub init_all_countrycodes {
513   my %cc = User->country_codes;
514   return [ map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc ];
515 }
516
517 #
518 # filters
519 #
520
521 sub setup_layout {
522   my ($self, $action) = @_;
523
524   $::request->layout(SL::Layout::Dispatcher->new(style => 'admin'));
525   $::request->layout->use_stylesheet("lx-office-erp.css");
526   $::form->{favicon} = "favicon.ico";
527 }
528
529 sub setup_client {
530   my ($self) = @_;
531
532   $self->client((first { $_->is_default } @{ $self->all_clients }) || $self->all_clients->[0]) if !$self->client;
533   $::auth->set_client($self->client->id);
534 }
535
536
537 #
538 # displaying forms
539 #
540
541 sub use_multiselect_js {
542   my ($self) = @_;
543
544   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
545   return $self;
546 }
547
548 sub login_form {
549   my ($self, %params) = @_;
550   $::request->layout->focus('#admin_password');
551   $self->render('admin/adminlogin', title => t8('kivitendo v#1 administration', $::form->read_version), %params);
552 }
553
554 sub edit_user_form {
555   my ($self, %params) = @_;
556   $self->use_multiselect_js->render('admin/edit_user', %params);
557 }
558
559 sub edit_client_form {
560   my ($self, %params) = @_;
561   $self->use_multiselect_js->render('admin/edit_client', %params);
562 }
563
564 sub edit_group_form {
565   my ($self, %params) = @_;
566   $self->use_multiselect_js->render('admin/edit_group', %params);
567 }
568
569 sub edit_printer_form {
570   my ($self, %params) = @_;
571   $self->render('admin/edit_printer', %params);
572 }
573
574 sub create_dataset_form {
575   my ($self, %params) = @_;
576   $self->render('admin/create_dataset', title => (t8('Database Administration') . " / " . t8('Create Dataset')));
577 }
578
579 sub delete_dataset_form {
580   my ($self, %params) = @_;
581   $self->render('admin/delete_dataset', title => (t8('Database Administration') . " / " . t8('Delete Dataset')));
582 }
583
584 #
585 # helpers
586 #
587
588 sub check_auth_db_and_tables {
589   my ($self) = @_;
590
591   if (!$::auth->check_database) {
592     $self->render('admin/check_auth_database', title => t8('Authentification database creation'));
593     return 0;
594   }
595
596   if (!$::auth->check_tables) {
597     $self->render('admin/check_auth_tables', title => t8('Authentification tables creation'));
598     return 0;
599   }
600
601   return 1;
602 }
603
604 sub apply_dbupgrade_scripts {
605   return SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(1);
606 }
607
608 sub authenticate_root {
609   my ($self) = @_;
610
611   return 1 if $::auth->authenticate_root($::form->{'{AUTH}admin_password'}) == $::auth->OK();
612
613   $::auth->punish_wrong_login;
614   $::auth->delete_session_value('admin_password');
615
616   $self->login_form(error => t8('Incorrect password!'));
617
618   return undef;
619 }
620
621 1;