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