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