action_database_administration gibt es nicht mehr
[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_used_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   # Assign empty arrays if the browser doesn't send those controls.
139   $params->{clients} ||= [];
140   $params->{groups}  ||= [];
141
142   $self->user($is_new ? SL::DB::AuthUser->new : SL::DB::AuthUser->new(id => $params->{id})->load)
143     ->assign_attributes(%{ $params })
144     ->config_values({ %{ $self->user->config_values }, %{ $props } });
145
146   my @errors = $self->user->validate;
147
148   if (@errors) {
149     flash('error', @errors);
150     $self->edit_user_form(title => $is_new ? t8('Create a new user') : t8('Edit User'));
151     return;
152   }
153
154   $self->user->save;
155
156   if ($::auth->can_change_password && $::form->{new_password}) {
157     $::auth->change_password($self->user->login, $::form->{new_password});
158   }
159
160   flash_later('info', $is_new ? t8('The user has been created.') : t8('The user has been saved.'));
161   $self->redirect_to(action => 'show');
162 }
163
164 sub action_delete_user {
165   my ($self) = @_;
166
167   my @clients = @{ $self->user->clients || [] };
168
169   if (!$self->user->delete) {
170     flash('error', t8('The user could not be deleted.'));
171     $self->edit_user_form(title => t8('Edit User'));
172     return;
173   }
174
175   # Flag corresponding entries in 'employee' as deleted.
176   foreach my $client (@clients) {
177     my $dbh = $client->dbconnect(AutoCommit => 1) || next;
178     $dbh->do(qq|UPDATE employee SET deleted = TRUE WHERE login = ?|, undef, $self->user->login);
179     $dbh->disconnect;
180   }
181
182   flash_later('info', t8('The user has been deleted.'));
183   $self->redirect_to(action => 'show');
184 }
185
186 #
187 # actions: clients
188 #
189
190 sub action_new_client {
191   my ($self) = @_;
192
193   $self->client(SL::DB::AuthClient->new(
194     dbhost   => $::auth->{DB_config}->{host},
195     dbport   => $::auth->{DB_config}->{port},
196     dbuser   => $::auth->{DB_config}->{user},
197     dbpasswd => $::auth->{DB_config}->{password},
198   ));
199
200   $self->edit_client_form(title => t8('Create a new client'));
201 }
202
203 sub action_edit_client {
204   my ($self) = @_;
205   $self->edit_client_form(title => t8('Edit Client'));
206 }
207
208 sub action_save_client {
209   my ($self) = @_;
210   my $params = delete($::form->{client}) || { };
211   my $is_new = !$params->{id};
212
213   # Assign empty arrays if the browser doesn't send those controls.
214   $params->{groups} ||= [];
215   $params->{users}  ||= [];
216
217   $self->client($is_new ? SL::DB::AuthClient->new : SL::DB::AuthClient->new(id => $params->{id})->load)->assign_attributes(%{ $params });
218
219   my @errors = $self->client->validate;
220
221   if (@errors) {
222     flash('error', @errors);
223     $self->edit_client_form(title => $is_new ? t8('Create a new client') : t8('Edit Client'));
224     return;
225   }
226
227   $self->client->save;
228   if ($self->client->is_default) {
229     SL::DB::Manager::AuthClient->update_all(set => { is_default => 0 }, where => [ '!id' => $self->client->id ]);
230   }
231
232   flash_later('info', $is_new ? t8('The client has been created.') : t8('The client has been saved.'));
233   $self->redirect_to(action => 'show');
234 }
235
236 sub action_delete_client {
237   my ($self) = @_;
238
239   if (!$self->client->delete) {
240     flash('error', t8('The client could not be deleted.'));
241     $self->edit_client_form(title => t8('Edit Client'));
242     return;
243   }
244
245   flash_later('info', t8('The client has been deleted.'));
246   $self->redirect_to(action => 'show');
247 }
248
249 sub action_test_database_connectivity {
250   my ($self)    = @_;
251
252   my %cfg       = %{ $::form->{client} || {} };
253   my $dbconnect = 'dbi:Pg:dbname=' . $cfg{dbname} . ';host=' . $cfg{dbhost} . ';port=' . $cfg{dbport};
254   my $dbh       = DBI->connect($dbconnect, $cfg{dbuser}, $cfg{dbpasswd});
255
256   my $ok        = !!$dbh;
257   my $error     = $DBI::errstr;
258
259   $dbh->disconnect if $dbh;
260
261   $self->render('admin/test_db_connection', { layout => 0 },
262                 title => t8('Database Connection Test'),
263                 ok    => $ok,
264                 error => $error);
265 }
266
267 #
268 # actions: groups
269 #
270
271 sub action_new_group {
272   my ($self) = @_;
273
274   $self->group(SL::DB::AuthGroup->new);
275   $self->edit_group_form(title => t8('Create a new group'));
276 }
277
278 sub action_edit_group {
279   my ($self) = @_;
280   $self->edit_group_form(title => t8('Edit User Group'));
281 }
282
283 sub action_save_group {
284   my ($self) = @_;
285
286   my $params = delete($::form->{group}) || { };
287   my $is_new = !$params->{id};
288
289   # Assign empty arrays if the browser doesn't send those controls.
290   $params->{clients} ||= [];
291   $params->{users}   ||= [];
292
293   $self->group($is_new ? SL::DB::AuthGroup->new : SL::DB::AuthGroup->new(id => $params->{id})->load)->assign_attributes(%{ $params });
294
295   my @errors = $self->group->validate;
296
297   if (@errors) {
298     flash('error', @errors);
299     $self->edit_group_form(title => $is_new ? t8('Create a new user group') : t8('Edit User Group'));
300     return;
301   }
302
303   $self->group->save;
304
305   flash_later('info', $is_new ? t8('The user group has been created.') : t8('The user group has been saved.'));
306   $self->redirect_to(action => 'show');
307 }
308
309 sub action_delete_group {
310   my ($self) = @_;
311
312   if (!$self->group->delete) {
313     flash('error', t8('The user group could not be deleted.'));
314     $self->edit_group_form(title => t8('Edit User Group'));
315     return;
316   }
317
318   flash_later('info', t8('The user group has been deleted.'));
319   $self->redirect_to(action => 'show');
320 }
321
322 #
323 # actions: printers
324 #
325
326 sub action_list_printers {
327   my ($self) = @_;
328   $self->render('admin/list_printers', title => t8('Printer management'));
329 }
330
331 sub action_new_printer {
332   my ($self) = @_;
333
334   $self->printer(SL::DB::Printer->new);
335   $self->edit_printer_form(title => t8('Create a new printer'));
336 }
337
338 sub action_edit_printer {
339   my ($self) = @_;
340   $self->edit_printer_form(title => t8('Edit Printer'));
341 }
342
343 sub action_save_printer {
344   my ($self) = @_;
345   my $params = delete($::form->{printer}) || { };
346   my $is_new = !$params->{id};
347
348   $self->printer($is_new ? SL::DB::Printer->new : SL::DB::Printer->new(id => $params->{id})->load)->assign_attributes(%{ $params });
349
350   my @errors = $self->printer->validate;
351
352   if (@errors) {
353     flash('error', @errors);
354     $self->edit_printer_form(title => $is_new ? t8('Create a new printer') : t8('Edit Printer'));
355     return;
356   }
357
358   $self->printer->save;
359
360   flash_later('info', $is_new ? t8('The printer has been created.') : t8('The printer has been saved.'));
361   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
362 }
363
364 sub action_delete_printer {
365   my ($self) = @_;
366
367   if (!$self->printer->delete) {
368     flash('error', t8('The printer could not be deleted.'));
369     $self->edit_printer_form(title => t8('Edit Printer'));
370     return;
371   }
372
373   flash_later('info', t8('The printer has been deleted.'));
374   $self->redirect_to(action => 'list_printers', 'client.id' => $self->client->id);
375 }
376
377 #
378 # actions: database administration
379 #
380
381 sub action_create_dataset_login {
382   my ($self) = @_;
383
384   $self->database_administration_login_form(
385     title       => t8('Create Dataset'),
386     next_action => 'create_dataset',
387   );
388 }
389
390 sub action_create_dataset {
391   my ($self) = @_;
392   $self->create_dataset_form;
393 }
394
395 sub action_do_create_dataset {
396   my ($self) = @_;
397
398   my @errors;
399   push @errors, t8("Dataset missing!")          if !$::form->{db};
400   push @errors, t8("Default currency missing!") if !$::form->{defaultcurrency};
401
402   if (@errors) {
403     flash('error', @errors);
404     return $self->create_dataset_form;
405   }
406
407   $::form->{encoding} = 'UNICODE';
408   User->new->dbcreate($::form);
409
410   flash_later('info', t8("The dataset #1 has been created.", $::form->{db}));
411   $self->redirect_to(action => 'show');
412 }
413
414 sub action_delete_dataset_login {
415   my ($self) = @_;
416
417   $self->database_administration_login_form(
418     title       => t8('Delete Dataset'),
419     next_action => 'delete_dataset',
420   );
421 }
422
423 sub action_delete_dataset {
424   my ($self) = @_;
425   $self->delete_dataset_form;
426 }
427
428 sub action_do_delete_dataset {
429   my ($self) = @_;
430
431   my @errors;
432   push @errors, t8("Dataset missing!") if !$::form->{db};
433
434   if (@errors) {
435     flash('error', @errors);
436     return $self->create_dataset_form;
437   }
438
439   User->new->dbdelete($::form);
440
441   flash_later('info', t8("The dataset #1 has been deleted.", $::form->{db}));
442   $self->redirect_to(action => 'show');
443 }
444
445 #
446 # actions: locking, unlocking
447 #
448
449 sub action_show_lock {
450   my ($self) = @_;
451
452   $self->render(
453     "admin/show_lock",
454     title => "kivitendo " . t8('Administration'),
455   );
456 }
457
458 sub action_unlock_system {
459   my ($self) = @_;
460
461   SL::System::InstallationLock->unlock;
462   flash_later('info', t8('Lockfile removed!'));
463   $self->redirect_to(action => 'show');
464 }
465
466 sub action_lock_system {
467   my ($self) = @_;
468
469   SL::System::InstallationLock->lock;
470   flash_later('info', t8('Lockfile created!'));
471   $self->redirect_to(action => 'show');
472 }
473
474 #
475 # initializers
476 #
477
478 sub init_db_cfg            { $::lx_office_conf{'authentication/database'}                                                    }
479 sub init_is_locked         { SL::System::InstallationLock->is_locked                                                         }
480 sub init_client            { SL::DB::Manager::AuthClient->find_by(id => ($::form->{id} || ($::form->{client}  || {})->{id})) }
481 sub init_user              { SL::DB::AuthUser  ->new(id => ($::form->{id} || ($::form->{user}    || {})->{id}))->load        }
482 sub init_group             { SL::DB::AuthGroup ->new(id => ($::form->{id} || ($::form->{group}   || {})->{id}))->load        }
483 sub init_printer           { SL::DB::Printer   ->new(id => ($::form->{id} || ($::form->{printer} || {})->{id}))->load        }
484 sub init_all_clients       { SL::DB::Manager::AuthClient->get_all_sorted                                                     }
485 sub init_all_users         { SL::DB::Manager::AuthUser  ->get_all_sorted                                                     }
486 sub init_all_groups        { SL::DB::Manager::AuthGroup ->get_all_sorted                                                     }
487 sub init_all_printers      { SL::DB::Manager::Printer   ->get_all_sorted                                                     }
488 sub init_all_dateformats   { [ qw(mm/dd/yy dd/mm/yy dd.mm.yy yyyy-mm-dd)      ]                                              }
489 sub init_all_numberformats { [ '1,000.00', '1000.00', '1.000,00', '1000,00'   ]                                              }
490 sub init_all_stylesheets   { [ qw(lx-office-erp.css Mobile.css kivitendo.css) ]                                              }
491 sub init_all_dbsources             { [ sort User->dbsources($::form)                               ] }
492 sub init_all_used_dbsources        { { map { (join(':', $_->dbhost || 'localhost', $_->dbport || 5432, $_->dbname) => $_->name) } @{ $_[0]->all_clients }  } }
493 sub init_all_accounting_methods    { [ { id => 'accrual',   name => t8('Accrual accounting')  }, { id => 'cash',     name => t8('Cash accounting')       } ] }
494 sub init_all_inventory_systems     { [ { id => 'perpetual', name => t8('Perpetual inventory') }, { id => 'periodic', name => t8('Periodic inventory')    } ] }
495 sub init_all_profit_determinations { [ { id => 'balance',   name => t8('Balancing')           }, { id => 'income',   name => t8('Cash basis accounting') } ] }
496
497 sub init_all_charts {
498   tie my %dir_h, 'IO::Dir', 'sql/';
499
500   return [
501     map { s/-chart\.sql$//; +{ id => $_ } }
502     sort
503     grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ }
504     keys %dir_h
505   ];
506 }
507
508 sub init_all_menustyles    {
509   return [
510     { id => 'old', title => $::locale->text('Old (on the side)') },
511     { id => 'v3',  title => $::locale->text('Top (CSS)') },
512     { id => 'neu', title => $::locale->text('Top (Javascript)') },
513   ];
514 }
515
516 sub init_all_rights {
517   my (@sections, $current_section);
518
519   foreach my $entry ($::auth->all_rights_full) {
520     if ($entry->[0] =~ m/^--/) {
521       push @sections, { description => $entry->[1], rights => [] };
522
523     } elsif (@sections) {
524       push @{ $sections[-1]->{rights} }, {
525         name        => $entry->[0],
526         description => $entry->[1],
527       };
528
529     } else {
530       die "Right without sections: " . join('::', @{ $entry });
531     }
532   }
533
534   return \@sections;
535 }
536
537 sub init_all_countrycodes {
538   my %cc = User->country_codes;
539   return [ map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc ];
540 }
541
542 #
543 # filters
544 #
545
546 sub setup_layout {
547   my ($self, $action) = @_;
548
549   $::request->layout(SL::Layout::Dispatcher->new(style => 'admin'));
550   $::form->{favicon} = "favicon.ico";
551   %::myconfig        = (
552     countrycode      => 'de',
553     numberformat     => '1.000,00',
554     dateformat       => 'dd.mm.yy',
555   ) if !%::myconfig;
556 }
557
558 sub setup_client {
559   my ($self) = @_;
560
561   $self->client(SL::DB::Manager::AuthClient->get_default || $self->all_clients->[0]) if !$self->client;
562   $::auth->set_client($self->client->id);
563 }
564
565 #
566 # displaying forms
567 #
568
569 sub use_multiselect_js {
570   my ($self) = @_;
571
572   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side);
573   return $self;
574 }
575
576 sub login_form {
577   my ($self, %params) = @_;
578   my $version         = $::form->read_version;
579   $::request->layout->no_menu(1);
580   $self->render('admin/adminlogin', title => t8('kivitendo v#1 administration', $version), %params, version => $version);
581 }
582
583 sub edit_user_form {
584   my ($self, %params) = @_;
585   $self->use_multiselect_js->render('admin/edit_user', %params);
586 }
587
588 sub edit_client_form {
589   my ($self, %params) = @_;
590   $self->use_multiselect_js->render('admin/edit_client', %params);
591 }
592
593 sub edit_group_form {
594   my ($self, %params) = @_;
595   $self->use_multiselect_js->render('admin/edit_group', %params);
596 }
597
598 sub edit_printer_form {
599   my ($self, %params) = @_;
600   $self->render('admin/edit_printer', %params);
601 }
602
603 sub database_administration_login_form {
604   my ($self, %params) = @_;
605
606   $self->render(
607     'admin/dbadmin',
608     dbhost    => $::form->{dbhost}    || $::auth->{DB_config}->{host} || 'localhost',
609     dbport    => $::form->{dbport}    || $::auth->{DB_config}->{port} || 5432,
610     dbuser    => $::form->{dbuser}    || $::auth->{DB_config}->{user} || 'kivitendo',
611     dbpasswd  => $::form->{dbpasswd}  || $::auth->{DB_config}->{password},
612     dbdefault => $::form->{dbdefault} || 'template1',
613     %params,
614   );
615 }
616
617 sub create_dataset_form {
618   my ($self, %params) = @_;
619   $self->render('admin/create_dataset', title => (t8('Database Administration') . " / " . t8('Create Dataset')));
620 }
621
622 sub delete_dataset_form {
623   my ($self, %params) = @_;
624   $self->render('admin/delete_dataset', title => (t8('Database Administration') . " / " . t8('Delete Dataset')));
625 }
626
627 #
628 # helpers
629 #
630
631 sub check_auth_db_and_tables {
632   my ($self) = @_;
633
634   if (!$::auth->check_database) {
635     $self->render('admin/check_auth_database', title => t8('Authentification database creation'));
636     return 0;
637   }
638
639   if (!$::auth->check_tables) {
640     $self->render('admin/check_auth_tables', title => t8('Authentification tables creation'));
641     return 0;
642   }
643
644   return 1;
645 }
646
647 sub apply_dbupgrade_scripts {
648   return SL::DBUpgrade2->new(form => $::form, auth => 1)->apply_admin_dbupgrade_scripts(1);
649 }
650
651 sub authenticate_root {
652   my ($self) = @_;
653
654   return 1 if $::auth->authenticate_root($::form->{'{AUTH}admin_password'}) == $::auth->OK();
655
656   $::auth->punish_wrong_login;
657   $::auth->delete_session_value('admin_password');
658
659   $self->login_form(error => t8('Incorrect password!'));
660
661   return undef;
662 }
663
664 1;