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