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