Bug 17855: Onboarding tool
[koha.git] / installer / onboarding.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Copyright (C) 2017 Catalyst IT
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 #Recommended pragmas
21 use Modern::Perl;
22 use diagnostics;
23 use C4::InstallAuth;
24 use CGI qw ( -utf8 );
25 use C4::Output;
26 use C4::Members;
27 use Koha::Patrons;
28 use Koha::Libraries;
29 use Koha::Database;
30 use Koha::DateUtils;
31 use Koha::Patron::Categories;
32 use Koha::Patron::Category;
33 use Koha::ItemTypes;
34 use Koha::IssuingRule;
35 use Koha::IssuingRules;
36
37 #Setting variables
38 my $input = new CGI;
39 my $step  = $input->param('step');
40
41 #Getting the appropriate template to display to the user
42 my ( $template, $loggedinuser, $cookie ) =
43   C4::InstallAuth::get_template_and_user(
44     {
45         template_name => "/onboarding/onboardingstep"
46           . ( $step ? $step : 1 ) . ".tt",
47         query           => $input,
48         type            => "intranet",
49         authnotrequired => 0,
50         debug           => 1,
51     }
52   );
53
54 #Check database connection
55 my %info;
56 $info{'dbname'} = C4::Context->config("database");
57 $info{'dbms'}   = (
58       C4::Context->config("db_scheme")
59     ? C4::Context->config("db_scheme")
60     : "mysql"
61 );
62
63 $info{'hostname'} = C4::Context->config("hostname");
64 $info{'port'}     = C4::Context->config("port");
65 $info{'user'}     = C4::Context->config("user");
66 $info{'password'} = C4::Context->config("pass");
67 my $dbh = DBI->connect(
68     "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
69       . ( $info{port} ? ";port=$info{port}" : "" ),
70     $info{'user'}, $info{'password'}
71 );
72
73 #Store the value of the template input name='op' in the variable $op so we can check if the user has pressed the button with the name="op" and value="finish" meaning the user has finished the onboarding tool.
74 my $op = $input->param('op') || '';
75 $template->param( 'op' => $op );
76
77 my $schema = Koha::Database->new()->schema();
78
79 if ( $op && $op eq 'finish' )
80 { #If the value of $op equals 'finish' then redirect user to /cgi-bin/koha/mainpage.pl
81     print $input->redirect("/cgi-bin/koha/mainpage.pl");
82     exit;
83 }
84
85 my $libraries = Koha::Libraries->search( {}, { order_by => ['branchcode'] }, );
86 $template->param(
87      libraries   => $libraries,
88      group_types => [
89      {
90             categorytype => 'searchdomain',
91             categories   => [
92                Koha::LibraryCategories->search(
93                    { categorytype => 'searchdomain' }
94                )
95             ],
96      },
97      {
98             categorytype => 'properties',
99             categories   => [
100                Koha::LibraryCategories->search(
101                    { categorytype => 'properties' }
102                )
103             ],
104      },
105      ]
106 );
107
108
109 #Select all the patron category records in the categories database table and give them to the template
110     my $categories = Koha::Patron::Categories->search();
111     $template->param( 'categories' => $categories, );
112
113 #Check if the $step variable equals 1 i.e. the user has clicked to create a library in the create library screen 1
114     my $itemtypes = Koha::ItemTypes->search();
115     $template->param( 'itemtypes' => $itemtypes, );
116
117 if ( $step && $step == 1 ) {
118     #store inputted parameters in variables
119     my $branchcode = $input->param('branchcode');
120     $branchcode = uc($branchcode);
121     my $categorycode = $input->param('categorycode');
122     my $op = $input->param('op') || 'list';
123     my $message;
124     my $library;
125
126     #Take the text 'branchname' and store it in the @fields array
127     my @fields = qw(
128       branchname
129     );
130
131     $template->param( 'branchcode' => $branchcode );
132     $branchcode =~ s|\s||g
133       ; # Use a regular expression to check the value of the inputted branchcode
134
135 #Create a new library object and store the branchcode and @fields array values in this new library object
136     $library = Koha::Library->new(
137         {
138             branchcode => $branchcode,
139             ( map { $_ => scalar $input->param($_) || undef } @fields )
140         }
141     );
142
143     eval { $library->store; }; #Use the eval{} function to store the library object
144     if ($library) {
145         $message = 'success_on_insert';
146     }
147     else {
148         $message = 'error_on_insert';
149     }
150     $template->param( 'message' => $message );
151
152 #Check if the $step variable equals 2 i.e. the user has clicked to create a patron category in the create patron category screen 1
153 }
154 elsif ( $step && $step == 2 ) {
155     if ($op eq "add_validate_category"){
156         #Initialising values
157         my $searchfield  = $input->param('description') // q||;
158         my $categorycode = $input->param('categorycode');
159         my $op           = $input->param('op') // 'list';
160         my $message;
161         my $category;
162         $template->param( 'categorycode' => $categorycode );
163
164         my ( $template, $loggedinuser, $cookie ) =
165             C4::InstallAuth::get_template_and_user(
166             {
167                 template_name   => "/onboarding/onboardingstep2.tt",
168                 query           => $input,
169                 type            => "intranet",
170                 authnotrequired => 0,
171                 flagsrequired =>
172                 { parameters => 'parameters_remaining_permissions' },
173                 debug => 1,
174             }
175             );
176
177         #Once the user submits the page, this code validates the input and adds it
178         #to the database as a new patron category
179         $categorycode = $input->param('categorycode');
180         my $description           = $input->param('description');
181         my $overduenoticerequired = $input->param('overduenoticerequired');
182         my $category_type         = $input->param('category_type');
183         my $default_privacy       = $input->param('default_privacy');
184         my $enrolmentperiod       = $input->param('enrolmentperiod');
185         my $enrolmentperioddate   = $input->param('enrolmentperioddate') || undef;
186
187         #Converts the string into a date format
188         if ($enrolmentperioddate) {
189             $enrolmentperioddate = output_pref(
190                 {
191                     dt         => dt_from_string($enrolmentperioddate),
192                     dateformat => 'iso',
193                     dateonly   => 1,
194                 }
195             );
196         }
197
198         #Adds a new patron category to the database
199         $category = Koha::Patron::Category->new(
200             {
201                 categorycode          => $categorycode,
202                 description           => $description,
203                 overduenoticerequired => $overduenoticerequired,
204                 category_type         => $category_type,
205                 default_privacy       => $default_privacy,
206                 enrolmentperiod       => $enrolmentperiod,
207                 enrolmentperioddate   => $enrolmentperioddate,
208             }
209         );
210
211         eval { $category->store; };
212
213         #Error messages
214         if ($category) {
215             $message = 'success_on_insert';
216         }
217         else {
218             $message = 'error_on_insert';
219         }
220
221         $template->param( 'message' => $message );
222     }
223     #Create a patron
224 }
225 elsif ( $step && $step == 3 ) {
226     my $firstpassword  = $input->param('password') || '';
227     my $secondpassword = $input->param('password2') || '';
228
229
230     #Find all patron records in the database and hand them to the template
231     my %currentpatrons = Koha::Patrons->search();
232     my $currentpatrons = values %currentpatrons;
233     $template->param( 'patrons' =>$currentpatrons);
234
235
236 #Find all library records in the database and hand them to the template to display in the library dropdown box
237     my $libraries =
238       Koha::Libraries->search( {}, { order_by => ['branchcode'] }, );
239     $template->param(
240         libraries   => $libraries,
241         group_types => [
242             {
243                 categorytype => 'searchdomain',
244                 categories   => [
245                     Koha::LibraryCategories->search(
246                         { categorytype => 'searchdomain' }
247                     )
248                 ],
249             },
250             {
251                 categorytype => 'properties',
252                 categories   => [
253                     Koha::LibraryCategories->search(
254                         { categorytype => 'properties' }
255                     )
256                 ],
257             },
258         ]
259     );
260
261 #Find all patron categories in the database and hand them to the template to display in the patron category dropdown box
262     my $categories = Koha::Patron::Categories->search();
263     $template->param( 'categories' => $categories, );
264
265 #Incrementing the highest existing patron cardnumber to prevent duplicate cardnumber entry
266
267     my $existing_cardnumber = $schema->resultset('Borrower')->get_column('cardnumber')->max() // 0;
268
269     my $new_cardnumber = $existing_cardnumber + 1;
270     $template->param( "newcardnumber" => $new_cardnumber );
271
272     my $op = $input->param('op') // 'list';
273     my $minpw = C4::Context->preference("minPasswordLength");
274     $template->param( "minPasswordLength" => $minpw );
275     my @messages;
276     my @errors;
277     my $nok            = $input->param('nok');
278     my $cardnumber     = $input->param('cardnumber');
279     my $borrowernumber = $input->param('borrowernumber');
280     my $userid         = $input->param('userid');
281
282     # function to designate mandatory fields (visually with css)
283     my $check_BorrowerMandatoryField =
284       C4::Context->preference("BorrowerMandatoryField");
285     my @field_check = split( /\|/, $check_BorrowerMandatoryField );
286     foreach (@field_check) {
287         $template->param( "mandatory$_" => 1 );
288         $template->param(
289             BorrowerMandatoryField =>
290               C4::Context->preference("BorrowerMandatoryField")
291             ,    #field to test with javascript
292         );
293     }
294
295  #If the entered cardnumber causes an error hand this error to the @errors array
296     if ( my $error_code = checkcardnumber( $cardnumber, $borrowernumber ) ) {
297         push @errors,
298             $error_code == 1 ? 'ERROR_cardnumber_already_exists'
299           : $error_code == 2 ? 'ERROR_cardnumber_length'
300           :                    ();
301     }
302
303    #If the entered password causes an error hand this error to the @errors array
304     push @errors, "ERROR_password_mismatch"
305       if $firstpassword ne $secondpassword;
306     push @errors, "ERROR_short_password"
307       if ( $firstpassword
308         && $minpw
309         && $firstpassword ne '****'
310         && ( length($firstpassword) < $minpw ) );
311
312     #Passing errors to template
313     $nok = $nok || scalar(@errors);
314
315 #If errors have been generated from the users inputted cardnumber or password then display the error and do not insert the patron into the borrowers table
316     if ($nok) {
317         foreach my $error (@errors) {
318             if ( $error eq 'ERROR_password_mismatch' ) {
319                 $template->param( errorpasswordmismatch => 1 );
320             }
321             if ( $error eq 'ERROR_login_exist' ) {
322                 $template->param( errorloginexists => 1 );
323             }
324             if ( $error eq 'ERROR_cardnumber_already_exists' ) {
325                 $template->param( errorcardnumberexists => 1 );
326             }
327             if ( $error eq 'ERROR_cardnumber_length' ) {
328                 $template->param( errorcardnumberlength => 1 );
329             }
330             if ( $error eq 'ERROR_short_password' ) {
331                 $template->param( errorshortpassword => 1 );
332             }
333         }
334         $template->param( 'nok' => 1 );
335
336 #Else if no errors have been caused by the users inputted card number or password then insert the patron into the borrowers table
337     }
338     else {
339         my ( $template, $loggedinuser, $cookie ) =
340           C4::InstallAuth::get_template_and_user(
341             {
342                 template_name   => "/onboarding/onboardingstep3.tt",
343                 query           => $input,
344                 type            => "intranet",
345                 authnotrequired => 0,
346                 flagsrequired   => { borrowers => 1 },
347                 debug           => 1,
348             }
349           );
350
351         if ( $op eq 'add_validate' ) {
352             my %newdata;
353
354             #Store the template form values in the newdata hash
355             $newdata{borrowernumber} = $input->param('borrowernumber');
356             $newdata{surname}        = $input->param('surname');
357             $newdata{firstname}      = $input->param('firstname');
358             $newdata{cardnumber}     = $input->param('cardnumber');
359             $newdata{branchcode}     = $input->param('libraries');
360             $newdata{categorycode}   = $input->param('categorycode_entry');
361             $newdata{userid}         = $input->param('userid');
362             $newdata{password}       = $input->param('password');
363             $newdata{password2}      = $input->param('password2');
364             $newdata{privacy}        = "default";
365             $newdata{address}        = "";
366             $newdata{city}           = "";
367
368 #Hand tne the dateexpiry of the patron based on the patron category it is created from
369             my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
370             $newdata{dateexpiry} = $patron_category->get_expiry_date( $newdata{dateenrolled} );
371
372 #Hand the newdata hash to the AddMember subroutine in the C4::Members module and it creates a patron and hands back a borrowernumber which is being stored
373             my $borrowernumber = &AddMember(%newdata);
374
375 #Create a hash named member2 and fill it with the borrowernumber of the borrower that has just been created
376             my %member2;
377             $member2{'borrowernumber'} = $borrowernumber;
378
379 #Perform data validation on the flag that has been handed to onboarding.pl by the template
380             my $flag = $input->param('flag');
381             if ( $input->param('newflags') ) {
382                 my $dbh              = C4::Context->dbh();
383                 my @perms            = $input->multi_param('flag');
384                 my %all_module_perms = ();
385                 my %sub_perms        = ();
386                 foreach my $perm (@perms) {
387                     if ( $perm !~ /:/ ) {
388                         $all_module_perms{$perm} = 1;
389                     }
390                     else {
391                         my ( $module, $sub_perm ) = split /:/, $perm, 2;
392                         push @{ $sub_perms{$module} }, $sub_perm;
393                     }
394                 }
395
396                 # construct flags
397                 my @userflags = $schema->resultset('Userflag')->search({},{
398                         order_by => { -asc =>'bit'},
399                         }
400                 );
401
402 #Setting superlibrarian permissions for new patron
403                 my $flags = Koha::Patrons->find($borrowernumber)->set({flags=>1})->store;
404
405                 #Error handling checking if the patron was created successfully
406                 if ( !$borrowernumber ) {
407                     push @messages,
408                       { type => 'error', code => 'error_on_insert' };
409                 }
410                 else {
411                     push @messages,
412                       { type => 'message', code => 'success_on_insert' };
413                 }
414             }
415         }
416     }
417 }
418 elsif ( $step && $step == 4 ) {
419     my ( $template, $borrowernumber, $cookie ) =
420       C4::InstallAuth::get_template_and_user(
421         {
422             template_name   => "/onboarding/onboardingstep4.tt",
423             query           => $input,
424             type            => "intranet",
425             authnotrequired => 0,
426             flagsrequired =>
427               { parameters => 'parameters_remaining_permissions' },
428             debug => 1,
429         }
430     );
431   if ($op eq "add_validate"){
432         my $description   = $input->param('description');
433         my $itemtype_code = $input->param('itemtype');
434         $itemtype_code = uc($itemtype_code);
435
436   #Create a new itemtype object using the user inputted itemtype and description
437         my $itemtype = Koha::ItemType->new(
438             {
439                 itemtype    => $itemtype_code,
440                 description => $description,
441             }
442         );
443         eval { $itemtype->store; };
444         my $message;
445
446 #Fill the $message variable with an error if the item type object was not successfully created and inserted into the itemtypes table
447         if ($itemtype) {
448             $message = 'success_on_insert';
449         }
450         else {
451             $message = 'error_on_insert';
452         }
453         $template->param( 'message' => $message );
454     }
455 }
456 elsif ( $step && $step == 5 ) {
457
458   #Find all the existing categories to display in a dropdown box in the template
459     my $categories;
460     $categories = Koha::Patron::Categories->search();
461     $template->param( categories => $categories, );
462
463  #Find all the exisiting item types to display in a dropdown box in the template
464     my $itemtypes;
465     $itemtypes = Koha::ItemTypes->search();
466     $template->param( itemtypes => $itemtypes, );
467
468   #Find all the exisiting libraries to display in a dropdown box in the template
469     my $libraries =
470       Koha::Libraries->search( {}, { order_by => ['branchcode'] }, );
471     $template->param(
472         libraries   => $libraries,
473         group_types => [
474             {
475                 categorytype => 'searchdomain',
476                 categories   => [
477                     Koha::LibraryCategories->search(
478                         { categorytype => 'searchdomain' }
479                     )
480                 ],
481             },
482             {
483                 categorytype => 'properties',
484                 categories   => [
485                     Koha::LibraryCategories->search(
486                         { categorytype => 'properties' }
487                     )
488                 ],
489             },
490         ]
491     );
492
493     my $input = CGI->new;
494     my $dbh   = C4::Context->dbh;
495
496     my ( $template, $loggedinuser, $cookie ) =
497       C4::InstallAuth::get_template_and_user(
498         {
499             template_name   => "/onboarding/onboardingstep5.tt",
500             query           => $input,
501             type            => "intranet",
502             authnotrequired => 0,
503             flagsrequired   => { parameters => 'manage_circ_rules' },
504             debug           => 1,
505         }
506       );
507
508     #If no libraries exist then set the $branch value to *
509     my $branch = $input->param('branch');
510     unless ($branch) {
511         if ( C4::Context->preference('DefaultToLoggedInLibraryCircRules') ) {
512             $branch =
513               Koha::Libraries->search->count() == 1
514               ? undef
515               : C4::Context::mybranch();
516         }
517         else {
518             $branch =
519               C4::Context::only_my_library()
520               ? ( C4::Context::mybranch() || '*' )
521               : '*';
522         }
523     }
524     $branch = '*' if $branch eq 'NO_LIBRARY_SET';
525     my $op = $input->param('op') || q{};
526
527     if ( $op eq 'add_validate' ) {
528         my $type            = $input->param('type');
529         my $br              = $input->param('branch');
530         my $bor             = $input->param('categorycode');
531         my $itemtype        = $input->param('itemtype');
532         my $maxissueqty     = $input->param('maxissueqty');
533         my $issuelength     = $input->param('issuelength');
534         my $lengthunit      = $input->param('lengthunit');
535         my $renewalsallowed = $input->param('renewalsallowed');
536         my $renewalperiod   = $input->param('renewalperiod');
537         my $onshelfholds    = $input->param('onshelfholds') || 0;
538         $maxissueqty =~ s/\s//g;
539         $maxissueqty = undef if $maxissueqty !~ /^\d+/;
540         $issuelength = $issuelength eq q{} ? undef : $issuelength;
541
542         my $params = {
543             branchcode      => $br,
544             categorycode    => $bor,
545             itemtype        => $itemtype,
546             maxissueqty     => $maxissueqty,
547             renewalsallowed => $renewalsallowed,
548             renewalperiod   => $renewalperiod,
549             issuelength     => $issuelength,
550             lengthunit      => $lengthunit,
551             onshelfholds    => $onshelfholds,
552         };
553
554         my @messages;
555
556 #Allows for the 'All' option to work when selecting all libraries for a circulation rule to apply to.
557         if ( $branch eq "*" ) {
558             my $search_default_rules = $schema->resultset('DefaultCircRule')->count();
559             my $insert_default_rules = $schema->resultset('Issuingrule')->new(
560                     { maxissueqty => $maxissueqty, onshelfholds => $onshelfholds }
561                 );
562         }
563 #Allows for the 'All' option to work when selecting all patron categories for a circulation rule to apply to.
564         elsif ( $bor eq "*" ) {
565
566             my $search_default_rules = $schema->resultset('DefaultCircRule')->count();
567             my $insert_default_rules = $schema->resultset('Issuingrule')->new(
568                         { maxissueqty => $maxissueqty}
569             );
570         }
571
572 #Allows for the 'All' option to work when selecting all itemtypes for a circulation rule to apply to
573         elsif ( $itemtype eq "*" ) {
574             my $search_default_rules = $schema->resultset('DefaultCircRule')->search({},{
575                     branchcode => $branch
576                     }
577
578             );
579
580             my $insert_default_rules = $schema->resultset('Issuingrule')->new(
581                            { branchcode => $branch, onshelfholds => $onshelfholds }
582             );
583         }
584
585         my $issuingrule = Koha::IssuingRules->find(
586             { categorycode => $bor, itemtype => $itemtype, branchcode => $br }
587         );
588         if ($issuingrule) {
589             $issuingrule->set($params)->store();
590             push @messages,
591               {
592                 type => 'error',
593                 code => 'error_on_insert'
594               }; #Stops crash of the onboarding tool if someone makes a circulation rule with the same item type, library and patron categroy as an exisiting circulation rule.
595
596         }
597         else {
598             Koha::IssuingRule->new()->set($params)->store();
599         }
600     }
601 }
602
603 output_html_with_http_headers $input, $cookie, $template->output;