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